content
stringlengths 10
4.9M
|
---|
import ast
import operator as op
import re
import signal
from typing import Callable, Dict, Iterable, List, Union
def AVG(*values): # noqa
if not isinstance(values, Iterable):
values = [values]
return sum(values) / len(values) if values else 0
def IF(*values) -> Union[float, int, str]: # noqa
condition, value1, value2 = values
return value1 if condition else value2
FunctionEvaluator = Callable[[List[Union[float, int]]], Union[float, int, str]]
FUNCTIONS_MAP: Dict[str, FunctionEvaluator] = {
"SUM": sum,
"MIN": min,
"MAX": max,
"AVG": AVG,
"IF": IF,
}
OPERATORS = {
ast.Add: op.add,
ast.Sub: op.sub,
ast.Mult: op.mul,
ast.Div: op.truediv,
ast.Pow: op.pow,
ast.BitXor: op.xor,
ast.USub: op.neg,
ast.Gt: op.gt,
ast.GtE: op.ge,
ast.LtE: op.le,
ast.Lt: op.lt,
}
def custom_eval(node, value_map=None):
"""
for safely using `eval`
"""
if isinstance(node, ast.Call):
values = [custom_eval(v) for v in node.args]
func_name = node.func.id
if func_name in {"AVG", "IF"}:
return FUNCTIONS_MAP[func_name](*values)
elif func_name in FUNCTIONS_MAP:
return FUNCTIONS_MAP[func_name](values)
else:
raise NotImplementedError(func_name)
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.Str):
return node.s
elif isinstance(node, ast.BinOp):
return OPERATORS[type(node.op)](
custom_eval(node.left, value_map=value_map),
custom_eval(node.right, value_map=value_map),
)
elif isinstance(node, ast.UnaryOp):
return OPERATORS[type(node.op)](custom_eval(node.operand, value_map=value_map))
elif isinstance(node, ast.Compare):
return OPERATORS[type(node.ops[0])](
custom_eval(node.left, value_map=value_map),
custom_eval(node.comparators[0], value_map=value_map),
)
elif isinstance(node, ast.Name):
name = node.id
if value_map is None:
raise ValueError("value_map must not be None")
if name not in value_map:
raise KeyError()
try:
return value_map[name]
except KeyError as e:
raise e
else:
raise ArithmeticError()
def handle_special_char(expr: str):
"""
handler for '^' to '**', 10% to 0.1
"""
def handle_percent_sign(matched):
span = matched.group("number")
span = float(span[:-1])
return str(span / 100)
expr = expr.replace("^", "**")
res = re.sub("(?P<number>[0-9]+%)", handle_percent_sign, expr)
return res
def calculate(expr, value_map=None, millisecond=100):
"""
calculate expression, each expression only have 100 millisecond to execute
"""
def signal_handler(_, __):
raise TimeoutError()
signal.signal(signal.SIGALRM, signal_handler)
seconds = millisecond / 10 ** 3
signal.setitimer(signal.ITIMER_REAL, seconds, seconds)
expr = handle_special_char(expr)
try:
res = custom_eval(ast.parse(expr, mode='eval').body, value_map=value_map)
except TimeoutError as e:
raise e
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
return res
if __name__ == "__main__":
a = {"122": 1122}
b = "(2*id_122 + 1)*2 * SUM(2,3) + IF(1>2,1,3)"
print(calculate(b, value_map={"id_122": 2}))
a = calculate("5*(2+3)")
print(a)
b = calculate("-40*1+2*6-2")
print(b)
c = calculate("9**9**9**9**9**9**9**9")
print(c)
d = calculate("__import__('os').remove('docker.md')")
print("--", d)
|
Sometime back, I posted how to solve the Monty Hall problem with a million doors. Christophe Poucet wondered if I was making a mistake in my solution: maybe I was not ensuring that the host is not opening a door with a car. I did not think so, but then I have been wrong in the past. So, I wanted to check my solution. First I thought of using QuickCheck to test if the host function was correct, but that would mean that I write a test property and then call it to check that everything was correct. And then make sure that there was no difference between the test and the main problem. But I am lazy, and wanted an easier solution. Enter the assert function from Control.Exception . I just made two changes in my previous program.
I added a new import import Control.Exception (assert) I changed the randomVariable function to randomVariable :: (Door -> [Door] -> Door) -> MC Double randomVariable strategy = do u <- nature c <- contestant h <- host (options u c) let r = assert (all (\d -> open u d == Goat) h) $ reward u (strategy c h) return r
recompiled the code, and voila, no error messages. This means that my reasoning was correct. And now I can assert that my reasoning is correct. See GHC documentation and Haddock for more details on assertions.
Advertisements |
import { gql } from 'apollo-server-express'
export default gql`
#################################################
# MUTATION PAYLOADS
#################################################
type AddCommentPayload {
code: String!
success: Boolean!
message: String!
clientMutationId: String
comment: Comment
}
type UpdateCommentPayload {
code: String!
success: Boolean!
message: String!
clientMutationId: String
comment: Comment
}
type DeleteCommentPayload {
code: String!
success: Boolean!
message: String!
clientMutationId: String
comment: Comment
}
type CommentPayload {
code: String!
success: Boolean!
message: String!
clientMutationId: String
comment: Comment
}
type LikePayload {
code: String!
success: Boolean!
message: String!
clientMutationId: String
comment: Comment
}
type UnLikePayload {
code: String!
success: Boolean!
message: String!
clientMutationId: String
comment: Comment
}
#################################################
# MUTATIONS
#################################################
extend type Mutation {
addComment(input: AddCommentInput!): AddCommentPayload!
updateComment(input: UpdateCommentInput!): UpdateCommentPayload!
deleteComment(input: DeleteCommentInput!): DeleteCommentPayload!
like(input: LikeInput!): LikePayload! @auth
unlike(input: UnLikeInput!): UnLikePayload! @auth
}
`
|
/** Get string representing name of shader stage
*
* @param stage Shader stage
*
* @return String with name of shader stage
**/
const glw::GLchar* Utils::getShaderStageName(Utils::SHADER_STAGES stage)
{
const GLchar* result = 0;
switch (stage)
{
case COMPUTE_SHADER:
result = "compute";
break;
case VERTEX_SHADER:
result = "vertex";
break;
case TESS_CTRL_SHADER:
result = "tesselation control";
break;
case TESS_EVAL_SHADER:
result = "tesselation evaluation";
break;
case GEOMETRY_SHADER:
result = "geomtery";
break;
case FRAGMENT_SHADER:
result = "fragment";
break;
default:
TCU_FAIL("Invalid enum");
}
return result;
} |
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// GameFieldMultBase::Update_CheckForCollision Private
///
/// Check for intra-block collision in the update function after the blocks have been moved.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
void GameFieldMultBase::Update_CheckForCollision()
{
for( int32 colIndex = 0; colIndex < FIELD_WIDTH; ++colIndex )
{
if( m_Cols[ colIndex ].size() == 0 )
continue;
Update_CheckForCollision_Column( *(m_Cols[ colIndex ].begin()), colIndex );
}
} |
package com.netease.music.leetcode;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by dezhonger on 2020/4/10
*/
public class Leetcode0761 {
public static void main(String[] args) {
System.out.println(new Leetcode0761().makeLargestSpecial("11011000"));
}
//把1视为左括号,0视为右括号
public String makeLargestSpecial(String S) {
int len = S.length();
int cnt = 0;
int left = 0;
List<String> sortList = new ArrayList<>();
for (int i = 0; i < len; i++) {
char c = S.charAt(i);
if (c == '1') cnt++;
else cnt--;
if (cnt == 0) {
//递归处理子问题
sortList.add("1" + makeLargestSpecial(S.substring(left + 1, i)) + "0");
left = i + 1;
}
}
Collections.sort(sortList, Collections.reverseOrder());
return String.join("", sortList);
}
}
|
def fit_alternative_regression(regressions, reg_types, data):
reg_results = defaultdict(dict)
for reg_id in regressions.keys():
regression = regressions[reg_id]
reg_type = reg_types[reg_id]
reg_result = fit_regression(regression, reg_type, data)
reg_results.update(reg_result)
return reg_results |
// ListBlocks returns IDs of blocks matching given prefix.
func (bm *Manager) ListBlocks(prefix string) ([]string, error) {
bm.lock()
defer bm.unlock()
var result []string
appendToResult := func(i Info) error {
if i.Deleted || !strings.HasPrefix(i.BlockID, prefix) {
return nil
}
if bi, ok := bm.packIndexBuilder[i.BlockID]; ok && bi.Deleted {
return nil
}
result = append(result, i.BlockID)
return nil
}
for _, bi := range bm.packIndexBuilder {
_ = appendToResult(*bi)
}
_ = bm.committedBlocks.listBlocks(prefix, appendToResult)
return result, nil
} |
Brian O'Kelley
Programmatic advertising is dead.
I invented it when I built the first ad exchange at Right Media in 2006, and now I'm here to deliver its eulogy.
To clarify: I don't mean that we'll see an end to "digital ad buying that involves automation and data-driven decision-making, frequently in real-time," which is how Cowen & Co. defines programmatic. All of that will still happen.
But programmatic is an obsolescent technology built for the one-dimensional and monolithic internet of Eudora and Netscape. It's wholly inadequate for the dynamic ecosystem of music and video streaming, interactive gaming, app stores, the "Internet of Things," GPS, cloud cognitive software and virtual reality.
In fact, there's not really one "Internet" (capital I) anymore. There's my internet (small i), yours and everybody else's. And this highly personal, programmable internet requires a monetization engine that can match both its intelligence and its capacity to customize user experience.
It needs programmable advertising. Here's what that looks like.
Pillar No. 1: Data Economy
In the Programmatic Age, marketers and advertisers could target large consumer segments with static, standardized creative, but it was largely impossible to customize campaigns at the individual level. Moreover, the conversation took place across a single channel. Your streaming platform wasn't talking to your newspaper, which wasn't talking to your watch, which wasn't talking to satellite weather feeds.
The Programmable Age will be different.
Today, the most sophisticated ad tech platforms empower marketers to build customized algorithms that govern when and where creative gets served, based on data as diverse as weather patterns and psychographic profiles. Tomorrow, even the creative will be programmable. A consumer opening an app in Boston in January will see an ad set against a snow-capped Faneuil Hall; another consumer may view the same ad six months later in Tokyo, set against a sunny Mount Fuji.
Not every marketer or agency will have the incentive or wherewithal to build an in-house data science team, but all will enjoy the ability to license third-party algorithms. In effect, data science will become its own service economy.
Pillar No. 2: Adaptive Intelligence
Data can be predictive, but it should also be adaptive. Other industries have embraced machine learning to replicate human insight at scale. The Programmable Age will demand that capability for marketers and advertisers.
What does that mean in real terms? It might mean applying logistical regression to predict whether a particular ad unit will be viewable before a buyer bids on and pays for that unit. Or a recipe blog's landing page might look different for someone who recently purchased avocados and chips versus someone whose shopping cart is filled with ingredients for chicken soup.
Far from replacing creativity, machine learning will fortify the ingenuity behind great campaigns and deliver a higher return on advertising spend. The programmable internet is highly personalized; its advertising must be as well.
Pillar No. 3: Frictionless Supply Chains
Programmatic advertising has long been synonymous with an over-complicated and inefficient supply chain.
From the moment a consumer clicks a link or opens an app, a single ad unit might bounce between multiple supply-side platforms and networks. Layer in rich media vendors, buy-side and sell-side ad servers, third-party verification partners and data management platforms, and you have the digital equivalent of a Rube Goldberg machine.
It's expensive, because each middleman takes a cut. It creates latency and eats away at the consumer's data plan, which contributes to widespread adoption of ad blocking. And it's opaque.
A hallmark of the Programmable Age is a compressed and frictionless supply chain. Rather than stitch together a patchwork of point solutions, marketers and publishers will increasingly migrate to consolidated platforms that power the entire market. They'll pay a transparent and reasonable technology fee, rather than exorbitant margins to broker-dealers in the middle.
The end result: radical transparency, frictionless execution, better user experience.
Growth Hacking
When he coined the phrase in 2010, entrepreneur Sean Ellis stipulated that "a growth hacker is a person whose true north is growth." It's a concept deeply engrained in the Programmable Age.
In everyday terms, that means an open ecosystem—namely, platforms with open APIs—that host innovation rather than preclude it.
Innovative data science and dynamic creative agencies will provide value by plugging into consolidated, open platforms and, by so doing, will rapidly productize new offerings and establish new revenue streams.
Walled gardens aren't built to do that. They're ill-suited to the Programmable Age.
Takeaway
Programmatic advertising automated the delivery of static creative to consumers. But in the interconnected and personalized Programmable Age, marketers and advertisers have the opportunity to reinvent how they engage with customers, creating a fluid and relevant experience designed around the eye of the beholder.
About the Author
As co-founder, CEO and chairman of the board of directors, Brian O'Kelley leads AppNexus' strategic initiatives. He has more than a decade of experience in online advertising, including CTO of Right Media (later sold to Yahoo!), where he invented the world's first advertising exchange. Brian is a contributor to Forbes on technology-related topics, has been named to Crain's 40 Under 40 and Adweek 50 lists, and was recognized as an Ernst & Young Entrepreneur of the Year in the New York region.
Brian holds a B.S.E. in computer science from Princeton University. He lives in New York with his wife and daughter.
About the Sponsor
AppNexus is a technology company that provides trading solutions and powers marketplaces for Internet advertising. Its open, unified and powerful programmatic platform empowers customers to more effectively buy and sell media, allowing them to innovate, differentiate and transform their businesses. As the world's leading independent ad tech company, AppNexus is led by the pioneers of the web's original ad exchanges. Headquartered in New York with 23 global offices, AppNexus employs more than 1,000 of the brightest minds in advertising and technology who believe that advertising powers the Internet. For more information, follow us at @AppNexus or visit us at www.appnexus.com/en |
<reponame>znikola/spartacus<filename>feature-libs/organization/administration/components/cost-center/budgets/assigned/index.ts
export * from './cost-center-assigned-budget-list.component';
export * from './cost-center-assigned-budget-list.service';
|
Tender Branson — last surviving member of the so-called "Creedish Death Cult" — is dictating his incredible life story into the flight recorder of Flight 2039, cruising on autopilot at 39,000 feet somewhere over the Pacific Ocean. He is all alone in the plane, which will shortly reach terminal velocity and crash into the vast Australian outback. Before it does, he will unfold the tale of his journey from an obedient Creedish child and humble domestic servant to an ultra-buffed, steroid- and collagen-packed media messiah, author of a best-selling autobiography, Saved from Salvation, and the even better selling Book of Very Common Prayer (The Prayer to Delay Orgasm, The Prayer to Prevent Hair Loss, The Prayer to Silence Car Alarms). He'll even share his insight that "the only difference between suicide and martyrdom is press coverage," and deny responsibility for the Tender Branson Sensitive Materials Landfill — a 20,000-acre repository for the nation's outdated pornography. Among other matters both bizarre and trenchant. |
class PollTrackUsersMixin:
"""
To use this Mixin, you need to provide self.object that is an instance of Poll model
"""
def dispatch(self, request, *args, **kwargs):
# Ignore everything related to Telemetry if "telemetry" field is False.
if not self.request.user.user_profile.telemetry or not self.object.telemetry:
return super().dispatch(self.request, *args, **kwargs)
telemetry = UsersPollTelemetry.objects.get(poll=self.object)
if self.request.user.is_authenticated:
self._authenticated_telemetry(telemetry)
else:
self._anonymous_telemetry(telemetry)
return super().dispatch(self.request, *args, **kwargs)
def _authenticated_telemetry(self, telemetry):
telemetry.users.add(self.request.user)
telemetry.save()
def _anonymous_telemetry(self, telemetry):
client_ip = self.request.META['REMOTE_ADDR']
address_object = AnonymousUserPollTelemetry.objects.get_or_create(
anonymous_user=client_ip
)[0]
telemetry.anonymous_users.add(address_object)
telemetry.save() |
//! Equations
//!
//! Combine two `Formula`s into an `Equation`! Use them to model something and use the s5 to
//! solve for the unknowns.
use crate::formulas::Formula;
use crate::variables::Variable;
use std::collections::HashSet;
/// Represents an equation of the form `left = right`.
#[derive(Clone, Debug)]
pub struct Equation {
/// Left side of equation
pub left: Formula,
/// Right side of equation
pub right: Formula,
}
impl Equation {
/// Create a new `Equation` of the form `left = right`.
pub fn new(left: Formula, right: Formula) -> Equation {
Equation { left, right }
}
/// Create a new `Equation` of the form `left = right`, where `left` is a `Variable`.
pub fn new_assignment(left: &Variable, right: Formula) -> Equation {
Equation {
left: left.into(),
right,
}
}
/// Return a variables involved in this equation.
pub fn variables(&self) -> HashSet<&Variable> {
let mut rv = self.left.variables();
rv.extend(&self.right.variables());
rv
}
/// Flip the sides of an equation. Return a new `Equation` where `right = left`.
pub fn flip(&self) -> Equation {
Equation {
left: self.right.clone(),
right: self.left.clone(),
}
}
}
|
// These two functions need to be moved into Quat class
// Compute a rotation required to Pose "from" into "to".
Quatf vectorAlignmentRotation(const Vector3f &from, const Vector3f &to) {
Vector3f axis = from.Cross(to);
if (axis.LengthSq() == 0)
return Quatf();
float angle = from.Angle(to);
return Quatf(axis, angle);
} |
class NetmaskOrPrefix(basestring):
"""
netmask. Possible values: dotted decimal or
hex integer (range: 0x1 .. 0xffffffff)
or '/' followed by hex integer (range: 0x1 .. 0x40)
Default if not specified is classful:
Class A address - 255.0.0.0 or 0xff000000 or /8
Class B address - 255.255.0.0 or 0xffff0000 or /16
Class C address - 255.255.255.0 or 0xffffff00 or /24
IPV6 address prefix - /1 through /128
"""
@staticmethod
def get_api_name():
return "netmask-or-prefix"
|
/**
* Serializes a peer address into a MongoDB specific document format.
*
* @param address that should be serialized
* @return MongoDB specific document format
*/
BasicDBObject serializePeerAddress(PeerChannelAddress address) {
BasicDBObject contactParams = new BasicDBObject();
int i = 0;
for (Serializable o : address.getContactParameters()) {
contactParams.append((i++)+"", o);
}
BasicDBObject doc = new BasicDBObject()
.append("_id", address.getPeerId().getId()+"."+address.getChannelType().getId())
.append("peerId", address.getPeerId().getId())
.append("adapterId", address.getChannelType().getId())
.append("contactParameters", contactParams);
log.trace("Saving peer address in mongoDB: {}", doc);
return doc;
} |
Though infinitely less well-known than their caped and cowled counterparts, the more paranormal-themed characters of DC comics are some of the most interesting and storied characters in the publishers’ pantheon. Characters like John Constantine, Swamp Thing, and others represent a dark flip-side to the more bright, colorful worlds of the DC, a more complex underbelly full of antiheroes and uncertainty. At no point was this distinction and the potency of this more apparent than in the late 80s and 90s, when these characters thrived under DC’s Vertigo imprint. Vertigo was created as a mature-audiences imprint of DC, a line of comics tailored for darker, more complex stories. It was the place where legendary writers like Neil Gaiman, Alan Moore, Garth Ennis, and others wrote stories that would shape their careers and the comics industry at large in books like The Sandman, Swamp Thing and Hellblazer. Though those halcyon days are behind us, the characters that became poster children for this era are still around, and they’re among the subjects of DC Animation’s latest film, Justice League Dark.
But there’s a problem, at least if you’re a part of that group of comic-book fans who hold 80s/90s Vertigo comics in a special esteem: while Justice League Dark has some familiar faces and a few fun shout-outs to offer Vertigo fans, make no mistake — you aren’t the target audience. Justice League Dark is intended as a primer on these characters for new audiences, and probably also as a proof-of-concept for the in-development live-action movie of the same name. While JLD could have been a slavish and artistically-charged tribute to this special era of comics, that simply isn’t the route they took. The good news is that if you’re able to adjust your expectations accordingly, it’s still a fun enough romp through DC’s paranormal areas, with a brisk pace and some fun visuals.
The story opens with a plague of grisly murders rocking the DCU, as ordinary citizens start hallucinating that their friends, family and neighbors are hideous demons. The Justice League are stumped, so Batman enlists the help of several paranormal characters to try and get to the bottom of things. This team includes Zatanna, DC’s resident stage magician/magical superhero, British urban sorcerer John Constantine, the ghostly acrobat Deadman, and demonic Etrigan. The adventure leads them on a whistle-stop tour of the DC Universe’s paranormal hotspots, with cameos from the likes of Felix Faust and Swamp Thing.
While early entries in the DC Animated canon felt like they had a bit more character to them, stylistically they’ve since settled into a consistent house approach in terms of animation, and to a lesser extent tone. While this makes it easier to present the films as installments in a consistent universe, it also leaves less room for experimentation and style. And if any DC Animated film could have benefited from a little style, it’s Justice League Dark. That isn’t to say that the animation and overall presentation is bad; it’s just a little on the bland side. Very rarely, if ever, does it feel like the animation or style really suits the characters, or adds to the film’s atmosphere of paranormal spookitude. This is the biggest hurdle the film has to overcome for layman viewers. While anime-infused projects like Batman: Gotham Knights could coast on visuals, Justice League Dark relies on its script and characters to carry it.
And carry it they do, for the most part. For many, the make or break is the depiction of John Constantine, the hard-bitten London mage with a knack for getting himself embroiled in magical trouble. Constantine is a hard character to get right, as the ill-fated Keanu Reeves movie demonstrated. He’s harder still to get right in the confines of a film where he can’t curse or smoke — two of his favorite activities. Surprisingly though, Justice League Dark pulls off a fairly faithful depiction of the character, despite these limitations. The supporting cast fare a bit less well, but not by much. Deadman, Zatanna, Etrigan, and Batman are pretty much along for the ride, only getting in little bits of characterization here and there where they can.
Frequently it feels like Batman in particular is excess baggage, there only to demonstrate how nervous DC gets about any property that doesn’t involve their golden boy. His monosyllabic grunts are occasionally amusing, at least, but bit players like Swamp Thing get the worst of it. The character once molded into a nuanced, tragic, and endlessly interesting hero by Alan Moore now feels tragically shoehorned into the story, only appearing in a few key sequences. Perhaps even worse is a cameo by Black Orchid, whose Neil Gaiman-penned miniseries almost single-handedly launched the Vertigo phenomenon. She feels like pure window dressing, a pointless addition that will be confusing for non-fans, as the film never quite explains who or what she is. If you have no knowledge of Black Orchid, the film won’t really fill you in. If you do, however, you may get more than a bit irked by seeing the character reduced to Constantine’s housemaid.
And that’s Justice League Dark in a nutshell, honestly. Longtime DC fans, particularly those with fond memories of the Vertigo golden years, may find themselves chafing under the film’s depictions of characters who once leaped of the page in nuanced, artistically charged stories. They feel homogenized, dumbed down, stripped of nuance. Newcomers, meanwhile, will fare much better, even if the occasionally ham-fisted exposition and uneven characterization leaves something to be desired. It’s far from DC Animation’s previous greatest-hits, like Under the Red Hood or Assault on Arkham, but for someone just looking for an hour and change of paranormal superhero fun, Justice League Dark is a pleasant enough distraction. But if you’re a Vertigo die-hard, you’d be better off keeping away, as the film’s versions of the characters that once haunted the pages of that hallowed imprint feel like shallow echoes of their former selves. |
/**
* Add all columns to current table builder
* @param cols columns
* @return current builder
*/
public Builder columns(String[] cols) {
this.cols = cols;
this.width = cols == null ? 0 : cols.length;
this.hasCols = width > 0;
return this;
} |
<filename>hw2skeleton/comparison_func.py
###comparison functions###
def silhouette(cluster1,cluster2):
'''
The silhouette score compares how similar each item is to all the other items in the cluster it belongs to compared to another cluster.
INPUT: 3 clusters as lists
OUTPUT: Silhouette Score
'''
mean_cluster1=mean(cluster1) #we want to find the closest cluster to compare this to
mean_cluster2=mean(cluster2)
mean_cluster3=mean(cluster3)
#find the closest cluster
clu1_2=math.mean(sqrt((mean_cluster1-mean_cluster2)**2))
clu1_3=math.mean(sqrt((mean_cluster1-mean_cluster3)**2))
if min(clu1_2,clu1_3)==clu1_3:
cluster2=cluster3
for i in cluster1:
a_list=[]
b_list=[]
for j in cluster1:
a_list.append(math.mean(sqrt((j-i)**2))) #finding the eucledian distance between each values in the same cluster
for j in cluster2:
b_list.append(math.mean(sqrt((j-i)**2))) #finding the eucledian distance between each values in the other cluster
s=(mean(a_list)-mean(b_list))/(min(a_list)-min(b_list)
#return s
def jacard_index(cluster1, cluster2):
'''
To compare the two clustering algorithms, we are using the Jacard Index, which determines the length of the union of the two clusters over the intersection.
We are going to the three cluster level.
The higher the Jacard index, the better the clusters compare (more intersection per item in the two indexes).
Input: one representative cluster from each algorithm
Output: Jacard Index
'''
union = list(set(cluster1).union(cluster2))
intersection = list(set(cluster1) & set(cluster2))
return len(intersection)/len(union)
|
"""Torch Module for APPNPConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from .graphconv import EdgeWeightNorm
class APPNPConv(nn.Module):
r"""Approximate Personalized Propagation of Neural Predictions layer from `Predict then
Propagate: Graph Neural Networks meet Personalized PageRank
<https://arxiv.org/pdf/1810.05997.pdf>`__
.. math::
H^{0} &= X
H^{l+1} &= (1-\alpha)\left(\tilde{D}^{-1/2}
\tilde{A} \tilde{D}^{-1/2} H^{l}\right) + \alpha H^{0}
where :math:`\tilde{A}` is :math:`A` + :math:`I`.
Parameters
----------
k : int
The number of iterations :math:`K`.
alpha : float
The teleport probability :math:`\alpha`.
edge_drop : float, optional
The dropout rate on edges that controls the
messages received by each node. Default: ``0``.
Example
-------
>>> import dgl
>>> import numpy as np
>>> import torch as th
>>> from dgl.nn import APPNPConv
>>>
>>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3]))
>>> feat = th.ones(6, 10)
>>> conv = APPNPConv(k=3, alpha=0.5)
>>> res = conv(g, feat)
>>> print(res)
tensor([[0.8536, 0.8536, 0.8536, 0.8536, 0.8536, 0.8536, 0.8536, 0.8536, 0.8536,
0.8536],
[0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268,
0.9268],
[0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634,
0.9634],
[0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268, 0.9268,
0.9268],
[0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634, 0.9634,
0.9634],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000,
0.5000]])
"""
def __init__(self, k, alpha, edge_drop=0.0):
super(APPNPConv, self).__init__()
self._k = k
self._alpha = alpha
self.edge_drop = nn.Dropout(edge_drop)
def forward(self, graph, feat, edge_weight=None):
r"""
Description
-----------
Compute APPNP layer.
Parameters
----------
graph : DGLGraph
The graph.
feat : torch.Tensor
The input feature of shape :math:`(N, *)`. :math:`N` is the
number of nodes, and :math:`*` could be of any shape.
edge_weight: torch.Tensor, optional
edge_weight to use in the message passing process. This is equivalent to
using weighted adjacency matrix in the equation above, and
:math:`\tilde{D}^{-1/2}\tilde{A} \tilde{D}^{-1/2}`
is based on :class:`dgl.nn.pytorch.conv.graphconv.EdgeWeightNorm`.
Returns
-------
torch.Tensor
The output feature of shape :math:`(N, *)` where :math:`*`
should be the same as input shape.
"""
with graph.local_scope():
if edge_weight is None:
src_norm = th.pow(
graph.out_degrees().to(feat).clamp(min=1), -0.5
)
shp = src_norm.shape + (1,) * (feat.dim() - 1)
src_norm = th.reshape(src_norm, shp).to(feat.device)
dst_norm = th.pow(
graph.in_degrees().to(feat).clamp(min=1), -0.5
)
shp = dst_norm.shape + (1,) * (feat.dim() - 1)
dst_norm = th.reshape(dst_norm, shp).to(feat.device)
else:
edge_weight = EdgeWeightNorm("both")(graph, edge_weight)
feat_0 = feat
for _ in range(self._k):
# normalization by src node
if edge_weight is None:
feat = feat * src_norm
graph.ndata["h"] = feat
w = (
th.ones(graph.num_edges(), 1)
if edge_weight is None
else edge_weight
)
graph.edata["w"] = self.edge_drop(w).to(feat.device)
graph.update_all(fn.u_mul_e("h", "w", "m"), fn.sum("m", "h"))
feat = graph.ndata.pop("h")
# normalization by dst node
if edge_weight is None:
feat = feat * dst_norm
feat = (1 - self._alpha) * feat + self._alpha * feat_0
return feat
|
// Run runs and blocks until the bot stops.
func (bot *DiscordBot) Run(ctx context.Context) error {
bot.Lock()
bot.tasks = NewTaskGroup(ctx)
bot.Unlock()
bot.tasks.SpawnCtx(func(_ context.Context) error { return bot.client.Open() })
bot.tasks.SpawnCtx(func(ctx context.Context) error {
for SleepCtx(ctx, discordStatusInterval) {
bot.setStatus()
}
return ctx.Err()
})
bot.tasks.SpawnCtx(func(ctx context.Context) error {
<-ctx.Done()
return bot.client.Close()
})
return bot.tasks.Wait().ToError()
} |
// http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem
#include <bits/stdc++.h>
using namespace std;
bool isSubsetSum(int *set, int n, int sum){
bool cache[sum+1][n+1];
for(int i=0; i<=n; i++)
cache[0][i] = 1;
for(int i=1; i<=sum; i++)
cache[i][0] = 0;
for(int i=1; i<=sum; i++){
for(int j=1; j<=n; j++){
if(set[j-1] > i)
cache[i][j] = cache[i][j-1];
else
cache[i][j] = cache[i][j-1] || cache[i-set[j-1]][j-1];
}
}
return cache[sum][n];
}
int main(){
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set)/sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
}
|
<filename>src/utils.c
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
uint8_t *hex_string_to_bin(const char *hex_string) {
size_t i, len = strlen(hex_string) / 2;
uint8_t *ret = (uint8_t *)malloc(len);
if (!ret) {
return NULL;
}
const char *pos = hex_string;
for (i = 0; i < len; ++i, pos += 2) {
sscanf(pos, "%2hhx", &ret[i]);
}
return ret;
}
off_t get_file_size(char *file) {
off_t size = 0;
FILE *fp = fopen(file, "r");
if (fp == NULL) {
return size;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
fclose(fp);
return size;
}
void to_hex(char *out, uint8_t *in, int size) {
while (size--) {
if (*in >> 4 < 0xA) {
*out++ = '0' + (*in >> 4);
} else {
*out++ = 'A' + (*in >> 4) - 0xA;
}
if ((*in & 0xf) < 0xA) {
*out++ = '0' + (*in & 0xF);
} else {
*out++ = 'A' + (*in & 0xF) - 0xA;
}
in++;
}
}
|
/**
* Find NEAT number less than n - 788 -> 779 (both NEAT)
* NEAT number is any number where the digits are in increasing order.
* Digit n should be greater than or equal to digit n-1
* Given any number, find the next lower NEAT number in O(log n) time
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println( "Lesser NEAT number => " +getLowerNeatNumber(br.readLine().trim()));
}
} |
def klDivergence(probDist1, probDist2):
M = 0.0000000000001
if probDist1.logified: probDist1 = probDist1.delogify()
if probDist1.logified: probDist1 = probDist1.delogify()
kl = 0
for key, value in probDist1.items():
try: q = value / probDist2[key]
except: q = value / M
if q == 0: q = M
kl += value * math.log(q, 2)
return kl |
#ifndef COLLISION_HPP
#define COLLISION_HPP
bool checkCircleCollision(float x1, float y1, float r1,
float x2, float y2, float r2);
#endif // COLLISION_HPP
|
A Study of the Cultural Factors on the Social Integration Concerning Social Controlling
ABSTRACT The present research focuses on a study of cultural factors influencing the social integration concerning the social controlling among the adults above 18 years of age living in Bushehr, based on metrical method. Based on the concerned method, the data collection was commenced through distributing questionnaires. Since social integration is considered as an essential need of society, social controlling plays an important role. Therefore, in this paper, an attempt is made to study the elements effective on the social integration, from a cultural perspective. Based on the existing theories on social investments, controlling, and integration and the issues like self-controlling, political and religious commitments, and informal controlling, the theoretical framework is set. The statistical society used in the paper pertains to the individuals above 18 years old. The sample volume Cochran factor with the error rate of five percent was 267. Considering the results from the descriptive, inferential analysis, there is a relationship between the variants of self-control, religious commitment and political legitimacy, and social integration. However, there is no meaningful relationship between the informal controlling and social integration variants. |
<gh_stars>0
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.store.connector.sink;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.table.store.file.FileStore;
import org.apache.flink.table.store.file.ValueKind;
import org.apache.flink.table.store.file.manifest.ManifestCommittable;
import org.apache.flink.table.store.file.mergetree.Increment;
import org.apache.flink.table.store.file.mergetree.sst.SstFileMeta;
import org.apache.flink.table.store.file.operation.FileStoreCommit;
import org.apache.flink.table.store.file.operation.FileStoreExpire;
import org.apache.flink.table.store.file.operation.FileStoreRead;
import org.apache.flink.table.store.file.operation.FileStoreScan;
import org.apache.flink.table.store.file.operation.FileStoreWrite;
import org.apache.flink.table.store.file.operation.Lock;
import org.apache.flink.table.store.file.stats.FieldStats;
import org.apache.flink.table.store.file.utils.RecordWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import static org.apache.flink.table.store.file.mergetree.compact.CompactManagerTest.row;
/** Test {@link FileStore}. */
public class TestFileStore implements FileStore {
public final Set<ManifestCommittable> committed = new HashSet<>();
public final Map<BinaryRowData, Map<Integer, List<String>>> committedFiles = new HashMap<>();
public boolean expired = false;
@Override
public FileStoreWrite newWrite() {
return new FileStoreWrite() {
@Override
public RecordWriter createWriter(
BinaryRowData partition, int bucket, ExecutorService compactExecutor) {
TestRecordWriter writer = new TestRecordWriter();
writer.records.addAll(
committedFiles
.computeIfAbsent(partition, k -> new HashMap<>())
.computeIfAbsent(bucket, k -> new ArrayList<>()));
committedFiles.get(partition).remove(bucket);
return writer;
}
@Override
public RecordWriter createEmptyWriter(
BinaryRowData partition, int bucket, ExecutorService compactExecutor) {
return new TestRecordWriter();
}
};
}
@Override
public FileStoreRead newRead() {
throw new UnsupportedOperationException();
}
@Override
public FileStoreCommit newCommit() {
return new TestCommit();
}
@Override
public FileStoreExpire newExpire() {
return () -> expired = true;
}
@Override
public FileStoreScan newScan() {
throw new UnsupportedOperationException();
}
static class TestRecordWriter implements RecordWriter {
final List<String> records = new ArrayList<>();
boolean synced = false;
boolean closed = false;
private String rowToString(RowData row) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < row.getArity(); i++) {
if (i != 0) {
builder.append("/");
}
builder.append(row.getInt(i));
}
return builder.toString();
}
@Override
public void write(ValueKind valueKind, RowData key, RowData value) {
records.add(
valueKind.toString()
+ "-key-"
+ rowToString(key)
+ "-value-"
+ rowToString(value));
}
@Override
public Increment prepareCommit() {
List<SstFileMeta> newFiles =
records.stream()
.map(
s ->
new SstFileMeta(
s,
0,
0,
null,
null,
new FieldStats[] {
new FieldStats(null, null, 0),
new FieldStats(null, null, 0),
new FieldStats(null, null, 0)
},
0,
0,
0))
.collect(Collectors.toList());
return new Increment(newFiles, Collections.emptyList(), Collections.emptyList());
}
@Override
public void sync() {
synced = true;
}
@Override
public List<SstFileMeta> close() {
closed = true;
return Collections.emptyList();
}
}
class TestCommit implements FileStoreCommit {
Lock lock;
@Override
public FileStoreCommit withLock(Lock lock) {
this.lock = lock;
return this;
}
@Override
public List<ManifestCommittable> filterCommitted(
List<ManifestCommittable> committableList) {
return committableList.stream()
.filter(c -> !committed.contains(c))
.collect(Collectors.toList());
}
@Override
public void commit(ManifestCommittable committable, Map<String, String> properties) {
try {
lock.runWithLock(() -> committed.add(committable));
} catch (Exception e) {
throw new RuntimeException(e);
}
committable
.newFiles()
.forEach(
(part, bMap) ->
bMap.forEach(
(bucket, files) -> {
List<String> committed =
committedFiles
.computeIfAbsent(
part, k -> new HashMap<>())
.computeIfAbsent(
bucket,
k -> new ArrayList<>());
files.stream()
.map(SstFileMeta::fileName)
.forEach(committed::add);
}));
}
@Override
public void overwrite(
Map<String, String> partition,
ManifestCommittable committable,
Map<String, String> properties) {
if (partition.isEmpty()) {
committedFiles.clear();
} else {
BinaryRowData partRow = row(Integer.parseInt(partition.get("part")));
committedFiles.remove(partRow);
}
commit(committable, properties);
}
}
}
|
package party.lemons.ass.blockentity.screen.widget;
import com.mojang.blaze3d.systems.RenderSystem;
import io.github.cottonmc.cotton.gui.widget.WWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.LiteralText;
import net.minecraft.text.StringRenderable;
import net.minecraft.util.Identifier;
import party.lemons.ass.Ass;
import party.lemons.ass.util.DrawUtil;
import java.util.List;
import java.util.function.IntSupplier;
public class HorizontalEnergyBarWidget extends WWidget
{
private final IntSupplier maxEnergyGetter;
private final IntSupplier energyGetter;
public HorizontalEnergyBarWidget(IntSupplier maxEnergyGetter, IntSupplier energyGetter)
{
this.maxEnergyGetter = maxEnergyGetter;
this.energyGetter = energyGetter;
this.width = 54;
}
@Override
public void paint(MatrixStack matrices, int x, int y, int mouseX, int mouseY)
{
super.paint(matrices, x, y, mouseX, mouseY);
int dX = x;
int dY = y + 4;
DrawUtil.texturedRect(dX, dY, 54, 10, 0, 125, 54, 135, DrawUtil.ICON_TEXTURE);
DrawUtil.powerIcon(dX - 9, dY + 1);
if(energyGetter.getAsInt() > 0)
{
float perc = (float)energyGetter.getAsInt() / (float)maxEnergyGetter.getAsInt();
int width = (int)(52F * perc);
DrawUtil.texturedRect(dX + 1, dY + 1, width, 8, 0, 135, width, 143, DrawUtil.ICON_TEXTURE);
}
if(isWithinBounds(mouseX, mouseY))
{
RenderSystem.disableDepthTest();
int highlightX = dX + 1;
int highlightY = dY + 1;
RenderSystem.colorMask(true, true, true, false);
DrawUtil.fillGradient(matrices, highlightX, highlightY, highlightX + 52, highlightY + 8, -2130706433, -2130706433);
RenderSystem.colorMask(true, true, true, true);
RenderSystem.enableDepthTest();
}
}
@Override
public void addTooltip(List<StringRenderable> tooltip)
{
super.addTooltip(tooltip);
tooltip.add(new LiteralText(energyGetter.getAsInt() + "/" + maxEnergyGetter.getAsInt()));
}
}
|
class Function:
"""
Function Class for Cells
"""
def __init__(self, function):
self._function = function
@property
def function(self):
return self._function
def __call__(self, args, _sheetname, **kwargs):
class callable:
def __init__(self, function, args, *, _sheetname, **kwargs):
self.function = function
self._args = args.split(";") #arguments in function may be separated by semicolons
self.kwargs = kwargs
self.spreadsheet = Spreadsheet.sheets[str(_sheetname)]
self.sheetname = _sheetname
@property
def args(self):
final = list()
for arg in self._args:
arg = arg.lower()
data = re.findall(r"^([\W\w]+!)?([a-z]+[0-9]+(?::[a-z]+[0-9]+)?)$", arg)
if len(data) == 1:
sheetname, cell = data[0]
if cell != "":
sheetname = sheetname != "" and sheetname or self.sheetname
final.append(Spreadsheet.sheets[str(sheetname)].range(cell))
else:
data = re.findall(r"^([\W\w]+!)?([a-z]+:[a-z]+)$", arg)
if len(data) == 1:
sheetname, cell = data[0]
if cell != "":
sheetname = sheetname != "" and sheetname or self.sheetname
final.append(Spreadsheet.sheets[str(sheetname)].range(cell))
else:
data = re.findall(r"^([\W\w]+!)?([0-9]+:[0-9]+)$", arg)
if len(data) == 1:
sheetname, cell = data[0]
if cell != "":
sheetname = sheetname != "" and sheetname or self.sheetname
final.append(Spreadsheet.sheets[str(sheetname)].range(cell))
else:
final.append(arg)
return final
def __repr__(self):
return "Functions.{function}({args})".format(function = self.function,
args = ", ".join([arg.__repr__() for arg in self.args]+
[key+"="+self.kwargs[key].__repr__()
for key in self.kwargs]))
def __sylk__(self):
return "{};E{function}({args})".format(eval(str(self.__repr__())),
function = self.function, #TODO Verify semicolon in args
args = "; ".join([sylk(arg) for arg in self.args]+
[key+"="+sylk(self.kwargs[key])
for key in self.kwargs]))
return callable(self.function, args, _sheetname=_sheetname, **kwargs)
def __sylk__(self):
pass
def __csv__(self):
pass |
//Get a subset the aliases in the cluster.
//
//Use case: You want to see some basic info on a subset of the aliases of the cluster
func (c *Client) GetAliases(alias string) ([]Alias, error) {
var aliases []Alias
path := fmt.Sprintf("_cat/aliases/%s?h=alias,index,filter,routing.index,routing.search", alias)
err := handleErrWithStruct(c.buildGetRequest(path), &aliases)
if err != nil {
return nil, err
}
return aliases, nil
} |
<filename>UI/src/app/admin/user-list/admin-user-list.component.ts
import { AdminService } from '../../services/index';
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { AdminUserView } from '../Dto/AdminUserView';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator'
import { ErrorHandlerService } from '../../services/index';
import { Router } from '@angular/router';
import { debug } from 'util';
import { MatDialog } from '@angular/material/dialog';
import { MAT_DIALOG_DATA, MatDialogRef, MatDialogConfig } from "@angular/material";
import { NotifyUserComponent } from '../user-notification/user-notification.component';
import { NotifyUserDto } from '../Dto/NotifyUserDto';
import { SuccessDialogComponent } from '../../dialogs/success-dialog/success-dialog.component';
@Component({
selector: 'admin-user-list',
templateUrl: './admin-user-list.component.html',
styleUrls: ['./admin-user-list.component.scss']
})
export class AdminUserListComponent implements OnInit, AfterViewInit {
public displayedColumns = ['name', 'dob', "email", "update"];
public dataSource = new MatTableDataSource<AdminUserView>();
public preferredFormat = "dd/MM/yyyy";
ready: boolean = true;
@ViewChild(MatSort, { static: true }) sort: MatSort;
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
dialogConfig = {
height: '300px',
width: '400px',
disableClose: true,
data: {}
}
constructor(private dialog: MatDialog, private userService: AdminService, private errorService: ErrorHandlerService, private router: Router) { }
ngOnInit() {
this.getUsers();
}
public getUsers = () => {
this.ready = false;
this.userService.getAll()
.subscribe(res => {
this.dataSource.data = res as AdminUserView[];
this.ready = true;
},
(error) => {
this.errorService.handleError(error);
this.ready = true;
})
}
ngAfterViewInit(): void {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
}
public customSort = (event) => {
console.log(event);
}
public doFilter = (value: string) => {
this.dataSource.filter = value.trim().toLocaleLowerCase();
}
public notify = (id: number) => {
this.openNotificationDialog(id);
}
openNotificationDialog(id: number) {
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus = true;
dialogConfig.width = "500px";
dialogConfig.height = "300px";
dialogConfig.data = {};
dialogConfig.data = {
email: (this.dataSource.data.filter(u => u.id == id)[0]['email'])
};
const dialogRef = this.dialog.open(NotifyUserComponent, dialogConfig);
dialogRef.afterClosed().subscribe(result => {
let notification: NotifyUserDto = { email: result.email, notification: result.notification };
this.userService.notify(notification)
.subscribe(res => {
if (res.success) {
(this.dialogConfig.data as any).message = res.message;
let dialogRef = this.dialog.open(SuccessDialogComponent, this.dialogConfig);
dialogRef.afterClosed()
.subscribe(result => {
setTimeout(() =>
this.getUsers(), 0)
});
} else {
(this.dialogConfig.data as any).message = res.error.message;
this.errorService.dialogConfig = { ...this.dialogConfig };
this.errorService.handleErrorMessage(res.error.message);
}
},
(error => {
this.errorService.dialogConfig = { ...this.dialogConfig };
this.errorService.handleError(error);
})
)
});
}
} |
def _initialize_models(self):
self.db = Database(self.settings)
self.db.run_migrations()
for channel in self.settings.CHANNEL_LIST:
self.channel_models[channel] = self.db.get_models(channel) |
def update_solution_bound(galini, tree, delta_t):
update_gauge(galini, 'branch_and_bound.lower_bound', tree.lower_bound)
update_gauge(galini, 'branch_and_bound.upper_bound', tree.upper_bound)
gap = relative_gap(tree.lower_bound, tree.upper_bound, galini.mc)
gap = np.min([gap, 1.0])
update_gauge(galini, 'branch_and_bound.relative_gap', gap, initial_value=1.0)
update_counter(galini, 'branch_and_bound.relative_gap_integral', gap * delta_t, initial_value=0.0) |
def validate_system(system):
required = {'requires', 'build-backend'}
if not (required <= set(system)):
message = "Missing required fields: {missing}".format(
missing=required-set(system),
)
raise ValueError(message) |
def path(edges, current, end, closed):
if end in current:
return True
closed.append(current)
childs = [n for n in edges if n not in closed and (current[0] in n or current[1] in n)]
if len(childs)==0:
return False
for c in childs:
if end in c:
return True
for c in childs:
if path(edges, c, end, closed):
return True
return False
if __name__ == '__main__':
n,m = [int(x) for x in raw_input().split()]
edgesByColour = {}
for i in xrange(m):
edge = [int(x) for x in raw_input().split()]
edgesByColour.setdefault(edge[2], []).append(edge[:2])
q = int(raw_input())
queries = []
for i in xrange(q):
queries += [[int(x) for x in raw_input().split()]]
results = ''
for start,end in queries:
res = 0
for colour in edgesByColour:
startNodes = [n for n in edgesByColour[colour] if start in n]
if len(startNodes) > 0:
for n in startNodes:
if path(edgesByColour[colour], n, end, []):
res += 1
break
results += '{}\n'.format(res)
print results[:-1] |
#!/usr/bin/env python3
import crayons
print(crayons.red('red string'))
print(f"{crayons.red('red')} white {crayons.blue('blue')}")
crayons.disable()
print(f"{crayons.red('red')} white {crayons.blue('blue')}")
crayons.DISABLE_COLOR = False
print(f"{crayons.red('red')} white {crayons.blue('blue')}")
print(crayons.red('red string', bold=True))
print(crayons.yellow('yellow string', bold=True))
print(crayons.magenta('magenta string', bold=True))
print(crayons.white('white string', bold=True))
|
use crate::fields::FieldContent;
use serde::Serialize;
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LungeExerciseName {
AlternatingBarbellForwardLunge,
AlternatingDumbbellLungeWithReach,
BackFootElevatedDumbbellSplitSquat,
BarbellBoxLunge,
BarbellBulgarianSplitSquat,
BarbellCrossoverLunge,
BarbellFrontSplitSquat,
BarbellLunge,
BarbellReverseLunge,
BarbellSideLunge,
BarbellSplitSquat,
CoreControlRearLunge,
DiagonalLunge,
DropLunge,
DumbbellBoxLunge,
DumbbellBulgarianSplitSquat,
DumbbellCrossoverLunge,
DumbbellDiagonalLunge,
DumbbellLunge,
DumbbellLungeAndRotation,
DumbbellOverheadBulgarianSplitSquat,
DumbbellReverseLungeToHighKneeAndPress,
DumbbellSideLunge,
ElevatedFrontFootBarbellSplitSquat,
FrontFootElevatedDumbbellSplitSquat,
GunslingerLunge,
LawnmowerLunge,
LowLungeWithIsometricAdduction,
LowSideToSideLunge,
Lunge,
LungeMatrix,
LungeWithArmReach,
LungeWithDiagonalReach,
LungeWithSideBend,
OffsetDumbbellLunge,
OffsetDumbbellReverseLunge,
OverheadBulgarianSplitSquat,
OverheadDumbbellReverseLunge,
OverheadDumbbellSplitSquat,
OverheadLunge,
OverheadLungeWithRotation,
ReverseBarbellBoxLunge,
ReverseBoxLunge,
ReverseDumbbellBoxLunge,
ReverseDumbbellCrossoverLunge,
ReverseDumbbellDiagonalLunge,
ReverseLungeWithReachBack,
ReverseLungeWithTwistAndOverheadReach,
ReverseSlidingBoxLunge,
ReverseSlidingLunge,
RunnersLungeToBalance,
ShiftingSideLunge,
SideAndCrossoverLunge,
SideLunge,
SideLungeAndPress,
SideLungeJumpOff,
SideLungeSweep,
SideLungeToCrossoverTap,
SideToSideLungeChops,
SiffJumpLunge,
SingleArmReverseLungeAndPress,
SlidingLateralLunge,
WalkingBarbellLunge,
WalkingDumbbellLunge,
WalkingLunge,
WeightedLunge,
WeightedLungeMatrix,
WeightedReverseLungeWithReachBack,
WeightedReverseLungeWithTwistAndOverheadReach,
WeightedReverseSlidingBoxLunge,
WeightedReverseSlidingLunge,
WeightedRunnersLungeToBalance,
WeightedSideAndCrossoverLunge,
WeightedSideLunge,
WeightedSideLungeSweep,
WeightedSideLungeToCrossoverTap,
WeightedSideToSideLungeChops,
WeightedSiffJumpLunge,
WeightedSlidingLateralLunge,
WeightedWalkingLunge,
WideGripOverheadBarbellSplitSquat,
UnknownValue(u64),
}
impl From<FieldContent> for LungeExerciseName {
fn from(field: FieldContent) -> Self {
if let FieldContent::UnsignedInt16(enum_value) = field {
match enum_value {
0 => LungeExerciseName::OverheadLunge,
1 => LungeExerciseName::LungeMatrix,
2 => LungeExerciseName::WeightedLungeMatrix,
3 => LungeExerciseName::AlternatingBarbellForwardLunge,
4 => LungeExerciseName::AlternatingDumbbellLungeWithReach,
5 => LungeExerciseName::BackFootElevatedDumbbellSplitSquat,
6 => LungeExerciseName::BarbellBoxLunge,
7 => LungeExerciseName::BarbellBulgarianSplitSquat,
8 => LungeExerciseName::BarbellCrossoverLunge,
9 => LungeExerciseName::BarbellFrontSplitSquat,
10 => LungeExerciseName::BarbellLunge,
11 => LungeExerciseName::BarbellReverseLunge,
12 => LungeExerciseName::BarbellSideLunge,
13 => LungeExerciseName::BarbellSplitSquat,
14 => LungeExerciseName::CoreControlRearLunge,
15 => LungeExerciseName::DiagonalLunge,
16 => LungeExerciseName::DropLunge,
17 => LungeExerciseName::DumbbellBoxLunge,
18 => LungeExerciseName::DumbbellBulgarianSplitSquat,
19 => LungeExerciseName::DumbbellCrossoverLunge,
20 => LungeExerciseName::DumbbellDiagonalLunge,
21 => LungeExerciseName::DumbbellLunge,
22 => LungeExerciseName::DumbbellLungeAndRotation,
23 => LungeExerciseName::DumbbellOverheadBulgarianSplitSquat,
24 => LungeExerciseName::DumbbellReverseLungeToHighKneeAndPress,
25 => LungeExerciseName::DumbbellSideLunge,
26 => LungeExerciseName::ElevatedFrontFootBarbellSplitSquat,
27 => LungeExerciseName::FrontFootElevatedDumbbellSplitSquat,
28 => LungeExerciseName::GunslingerLunge,
29 => LungeExerciseName::LawnmowerLunge,
30 => LungeExerciseName::LowLungeWithIsometricAdduction,
31 => LungeExerciseName::LowSideToSideLunge,
32 => LungeExerciseName::Lunge,
33 => LungeExerciseName::WeightedLunge,
34 => LungeExerciseName::LungeWithArmReach,
35 => LungeExerciseName::LungeWithDiagonalReach,
36 => LungeExerciseName::LungeWithSideBend,
37 => LungeExerciseName::OffsetDumbbellLunge,
38 => LungeExerciseName::OffsetDumbbellReverseLunge,
39 => LungeExerciseName::OverheadBulgarianSplitSquat,
40 => LungeExerciseName::OverheadDumbbellReverseLunge,
41 => LungeExerciseName::OverheadDumbbellSplitSquat,
42 => LungeExerciseName::OverheadLungeWithRotation,
43 => LungeExerciseName::ReverseBarbellBoxLunge,
44 => LungeExerciseName::ReverseBoxLunge,
45 => LungeExerciseName::ReverseDumbbellBoxLunge,
46 => LungeExerciseName::ReverseDumbbellCrossoverLunge,
47 => LungeExerciseName::ReverseDumbbellDiagonalLunge,
48 => LungeExerciseName::ReverseLungeWithReachBack,
49 => LungeExerciseName::WeightedReverseLungeWithReachBack,
50 => LungeExerciseName::ReverseLungeWithTwistAndOverheadReach,
51 => LungeExerciseName::WeightedReverseLungeWithTwistAndOverheadReach,
52 => LungeExerciseName::ReverseSlidingBoxLunge,
53 => LungeExerciseName::WeightedReverseSlidingBoxLunge,
54 => LungeExerciseName::ReverseSlidingLunge,
55 => LungeExerciseName::WeightedReverseSlidingLunge,
56 => LungeExerciseName::RunnersLungeToBalance,
57 => LungeExerciseName::WeightedRunnersLungeToBalance,
58 => LungeExerciseName::ShiftingSideLunge,
59 => LungeExerciseName::SideAndCrossoverLunge,
60 => LungeExerciseName::WeightedSideAndCrossoverLunge,
61 => LungeExerciseName::SideLunge,
62 => LungeExerciseName::WeightedSideLunge,
63 => LungeExerciseName::SideLungeAndPress,
64 => LungeExerciseName::SideLungeJumpOff,
65 => LungeExerciseName::SideLungeSweep,
66 => LungeExerciseName::WeightedSideLungeSweep,
67 => LungeExerciseName::SideLungeToCrossoverTap,
68 => LungeExerciseName::WeightedSideLungeToCrossoverTap,
69 => LungeExerciseName::SideToSideLungeChops,
70 => LungeExerciseName::WeightedSideToSideLungeChops,
71 => LungeExerciseName::SiffJumpLunge,
72 => LungeExerciseName::WeightedSiffJumpLunge,
73 => LungeExerciseName::SingleArmReverseLungeAndPress,
74 => LungeExerciseName::SlidingLateralLunge,
75 => LungeExerciseName::WeightedSlidingLateralLunge,
76 => LungeExerciseName::WalkingBarbellLunge,
77 => LungeExerciseName::WalkingDumbbellLunge,
78 => LungeExerciseName::WalkingLunge,
79 => LungeExerciseName::WeightedWalkingLunge,
80 => LungeExerciseName::WideGripOverheadBarbellSplitSquat,
n => LungeExerciseName::UnknownValue(n as u64),
}
} else {
panic!("can't convert LungeExerciseName to {:?}", field);
}
}
}
|
package yamahari.ilikewood.provider.loot;
import com.google.common.collect.ImmutableList;
import com.mojang.datafixers.util.Pair;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.loot.LootTableProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.LootTables;
import net.minecraft.world.level.storage.loot.ValidationContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import yamahari.ilikewood.util.Constants;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
public final class DefaultBlockLootTableProvider extends LootTableProvider {
private final List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>>
lootTables;
private final String name;
public DefaultBlockLootTableProvider(final DataGenerator generator,
final Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>> supplier,
final String name) {
super(generator);
this.lootTables = ImmutableList.of(Pair.of(supplier, LootContextParamSets.BLOCK));
this.name = name;
}
@Nonnull
@Override
protected List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>> getTables() {
return this.lootTables;
}
@Override
protected void validate(@Nonnull final Map<ResourceLocation, LootTable> map,
@Nonnull final ValidationContext context) {
map.forEach((location, lootTable) -> LootTables.validate(context, location, lootTable));
}
@Override
public String getName() {
return String.format("%s - loot tables - %s", Constants.MOD_ID, this.name);
}
}
|
# Copyright 2022 The PEGASUS Authors..
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pathlib
from absl.testing import absltest
import tensorflow_datasets as tfds
from pegasus.flax import input_pipeline
from pegasus.flax.configs import default
_MAX_LENGTH = 32
class InputPipelineTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.train_ds, self.eval_ds, self.predict_ds = self._get_datasets()
def _get_datasets(self):
config = default.get_config()
config.per_device_batch_size = 1
config.max_input_length = _MAX_LENGTH
config.max_target_length = _MAX_LENGTH
config.tokenizer_mode = 'sp_tokenizer'
config.tokenizer_type = 'sentencepiece'
config.tokenizer_path = 'third_party/tensorflow_text/python/ops/test_data/test_oss_model.model'
# Go two directories up to the root of the long-summ directory.
flax_root_dir = pathlib.Path(__file__).parents[2]
data_dir = str(flax_root_dir) + '/.tfds/metadata' # pylint: disable=unused-variable
with tfds.testing.mock_data(num_examples=128):
train_ds, eval_ds, predict_ds, _ = input_pipeline.get_summ_datasets(
n_devices=2, config=config)
return train_ds, eval_ds, predict_ds
def test_train_ds(self):
expected_shape = [2, _MAX_LENGTH] # 2 devices.
# For training we pack multiple short examples in one example.
# *_position and *_segmentation indicate the boundaries.
for batch in self.train_ds.take(3):
self.assertEqual({k: v.shape.as_list() for k, v in batch.items()}, {
'inputs': expected_shape,
'targets': expected_shape,
})
def test_eval_ds(self):
expected_shape = [2, _MAX_LENGTH] # 2 devices.
for batch in self.eval_ds.take(3):
self.assertEqual({k: v.shape.as_list() for k, v in batch.items()}, {
'inputs': expected_shape,
'targets': expected_shape,
})
def test_predict_ds(self):
expected_shape = [2, _MAX_LENGTH] # 2 devices.
for batch in self.predict_ds.take(3):
self.assertEqual({k: v.shape.as_list() for k, v in batch.items()}, {
'inputs': expected_shape,
'targets': expected_shape,
})
if __name__ == '__main__':
absltest.main()
|
Last week, Mitt Romney declared that if his new, one-page economic policy plan were implemented, the country would add “12 million new jobs by the end of [his] first term.”
Now, usually politicians (Barack Obama included) get hammered for overstating how much the economy will improve under their watch. But by at least some forecasts, Mr. Romney’s promises may actually be a little underambitious, in that his promised job growth is pretty close to what’s already expected.
In its semi-annual long-term economic forecast released in April, Macroeconomic Advisers projected that the economy would add 11.8 million jobs from 2012 to 2016. That means Mr. Romney believes his newly announced policies would add an extra 200,000 jobs on top of what people already expected, or a jobs bonus of about 2 percent. The more jobs the better, of course, but that’s not really much to write home about.
Moody’s Analytics, another forecasting firm, projects similar job growth:
Payroll Employment Change Year Millions of jobs 2010 -0.93 2011 1.50 2012 1.85 2013 1.89 2014 3.12 2015 3.76 2016 3.07 2017 1.35 2013-2016 11.84 Sources: BLS, Moody’s Analytics
In an e-mail Monday, Mark Zandi, the chief economist at Moody’s Analytics, emphasized that he actually expects the economy to remain on about the same path regardless of who is elected:
The forecast is agnostic with regard to who is elected in November. The key assumption is that whoever wins they will reasonably gracefully address the fiscal cliff, increase the Treasury debt ceiling without major incident, and achieve something close to fiscal sustainability. My view, is that the economy’s fundamentals are much improved, as households deleverage, the financial system re-capitalizes, and American businesses become global competitive. Moreover, the construction cycle is on the verge of turning up significantly, which by itself will create a boat load of jobs, particularly in 2014-15. If policymakers can get it roughly right soon after election, all of this will shine through quickly.
Not everyone is so upbeat.
Jan Hatzius, the chief economist at Goldman Sachs, told me that he has not developed explicit forecasts that go through the end of 2016, but he says he expected an average job growth of just under 150,000 a month from now through the end of 2013.
Given those expectations for the start of the next presidential term, he said that Mr. Romney’s promise of job growth averaging 250,000 a month over the next four years “would be quite a good outcome.”
Additionally, the Congressional Budget Office’s latest long-term economic forecast, released in January, showed that employment would grow by just 10 million from the first quarter of 2013 to the first quarter of 2017, the dates of the next presidential term. (Two asides: The numbers are the same if you use the last quarter of 2012 through the last quarter of 2016. Additionally, note that the C.B.O.’s forecast refers to the number of workers employed, as opposed to the number of payroll jobs in existence, which was the metric in the other forecasts cited.)
That C.B.O. forecast implies that Mr. Romney would be promising an extra 2 million jobs, or a 20 percent bonus from what’s already expected. Pretty impressive.
By law, though, the Congressional Budget Office must base its projections on the laws that are on the books rather than on what Congress is expected to do. That means that the office’s forecast assumes the “fiscal cliff” — with its sharp tax increases and deep spending cuts — materializes at the end of this year. Most economists do not believe Congress will allow this to happen.
Needless to say, the C.B.O.’s jobs numbers would probably look stronger if they likewise assumed Congress does not allow the country to go over the cliff. In that case, Mr. Romney’s job growth premium would be at least somewhat less impressive.
So what to make of all these figures?
First, as you can probably tell from both these forecasts and the events of the last decade, there is a huge margin of error when it comes to predicting economic trends for the next week, let alone the next four years. So it’s very hard to judge whether a promised gain of 12 million jobs under Mr. Romney’s policy overhaul significantly deviates from what would happen without the overhaul.
Perhaps the more important corollary, though, is that there’s a huge margin of error in what Mr. Romney is promising, too. And that’s true for just about any economic forecast you hear from any politician (or pundit or journalist for that matter).
Politicians throw out lots of different numbers for what the economy will do under the assumption that their exact agenda is passed, which is a pretty unrealistic assumption in the first place. Even if their policies do sail through the sausage factory that is Washington unscathed, there’s no telling what effect they’ll have when they move out of the world of bullet points and into the actual economy. So take any forecasts you hear from either presidential campaign with a boulder-size grain of salt. |
package org.apache.cordova.referrer;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;
public class Referrer extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String referrerString = extras.getString("referrer");
String utm_sourceString = extras.getString("utm_source");
String utm_mediumString = extras.getString("utm_medium");
String utm_campaignString = extras.getString("utm_campaign");
if (referrerString != null || utm_sourceString!=null || utm_mediumString!=null || utm_campaignString!=null) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.putString("referrer", referrerString);
edit.putString("utm_source", utm_sourceString);
edit.putString("utm_medium", utm_mediumString);
edit.putString("utm_campaign", utm_campaignString);
edit.commit();
}
}
}
} // end of class
|
// Create a pulse dbus service with 2 clients.
func main() {
pulse, e := pulseaudio.New()
if e != nil {
log.Panicln("connect", e)
}
app := &AppPulse{}
pulse.Register(app)
two := &ClientTwo{pulse}
pulse.Register(two)
two.Show()
streams, _ := two.Core().ListPath("PlaybackStreams")
for _, stream := range streams {
dev := two.Stream(stream)
e = dev.Set("Mute", true)
if e != nil {
log.Println(e)
}
}
pulse.Listen()
} |
/**
* Remove relation with music (Remove entity in `playlist_item` table)
* @param music: music to remove
*/
public void removeRelationWithMusic(Music music) {
try {
PreparedStatement stmt = Context.getConnection().prepareStatement("DELETE FROM `playlist_item` WHERE playlist_id = ? AND music_id = ?");
stmt.setInt(1, this.id);
stmt.setInt(2, music.id);
stmt.executeUpdate();
if (this.musics.contains(music))
this.musics.remove(music);
} catch (SQLException e) {
e.printStackTrace();
}
} |
/**
* Class MyTimeSeries buffers the item adds and then adds them all at once
*
*
* @author IDV Development Team
*/
private static class MyTimeSeries extends TimeSeries {
/** items */
List<TimeSeriesDataItem> items = new ArrayList<TimeSeriesDataItem>();
/** Keeps track of seen items */
HashSet<TimeSeriesDataItem> seen = new HashSet<TimeSeriesDataItem>();
/**
* ctor
*
* @param name time series name
* @param c domain type
*/
public MyTimeSeries(String name, Class c) {
super(name, c);
}
/**
* add
*
* @param item item
*/
public void add(TimeSeriesDataItem item) {
if (seen.contains(item)) {
return;
}
seen.add(item);
items.add(item);
}
/**
* add
*
* @param period period
* @param value value
*/
public void add(RegularTimePeriod period, double value) {
TimeSeriesDataItem item = new TimeSeriesDataItem(period, value);
add(item);
}
/**
* Sort the items add add them to the list
*/
public void finish() {
items = new ArrayList<TimeSeriesDataItem>(Misc.sort(items));
for (TimeSeriesDataItem item : items) {
this.data.add(item);
}
fireSeriesChanged();
}
} |
import { Injectable } from '@angular/core';
import { HintService } from '.././hint/hint.service';
import { Suggestion, TestResult } from '.././core/models';
import { SuggestionRepository } from '.././core/persistence';
@Injectable()
export class SuggestionService {
private repository: SuggestionRepository;
constructor(private hintService: HintService) {
this.repository = new SuggestionRepository();
this.hintService = hintService;
}
list(): Suggestion[] {
let suggestions = this.repository.find({
query: { discarded: false }
});
this.validateSuggestions(suggestions);
return suggestions;
}
listDiscarded(): Suggestion[] {
return this.repository.find({
query: { discarded: true }
});
}
save(suggestion: Suggestion) {
this.repository.save(suggestion);
}
find(id: number): Suggestion {
return this.repository.findOne(id);
}
delete(suggestion: Suggestion) {
this.repository.delete(suggestion);
}
public validateSuggestion(suggestion: Suggestion): void {
this.validateSuggestions([ suggestion ]);
}
public validateSuggestions(suggestions: Suggestion[]): void {
suggestions.forEach(s => {
let results: TestResult[] = [];
this.hintService.list().forEach(hint => results = results.concat(hint.test(s.label)));
s.results = results;
});
}
}
|
<reponame>eugeneilyin/mdi-norm<filename>es/OutlineBackspace.d.ts
export { default as OutlineBackspace } from './Icon';
|
package com.example.vibhor.fragmentmodulardesigndemo;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener {
ListView listView;
Comunicator comunicator;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
}
@Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comunicator = (Comunicator) getActivity();
listView = (ListView) getActivity().findViewById(R.id.listView);
ArrayAdapter arrayAdapter=ArrayAdapter.createFromResource(getActivity(),
R.array.titles,android.R.layout.simple_list_item_1);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
comunicator.respond(position);
}
}
|
"House of Cards" is holding two casting calls this week - one in Annapolis and another in White Marsh.
Here's the notice for those interested in trying to work on the Netflix political thriller:
Casting Calls At Two Locations This Weekend!
SEEKING PAID BACKGROUND PERFORMERS FOR A POPULAR POLITICAL DRAMA
* Government Official Types * Black Tie Affair * Men In Black *
* Cocktail Party Dresses, Business Casual, Art Gallery Types, Working Class *
ANNAPOLIS Open Casting Call: Saturday, May 30th, 2015
More than 1,000 people turned out in Bel Air on Friday afternoon for the first open casting call for extra's for Season 4 of the popular Netflix political drama "House of Cards," which is mainly filmed in Harford County. (Nicole Munchel for The Aegis / Baltimore Sun Media Group) (Nicole Munchel for The Aegis / Baltimore Sun Media Group)
Time : Between 10 am and 2 pm we won’t turn anyone away
LOCATION : PIP MOYER REC. CENTER , 273 HILLTOP LANE
ANNAPOLIS, MARYLAND 21403
WHITE MARSH Open Casting Call: Sunday May 31st, 2015
Time : Between 9 am and 1 pm we won’t turn anyone away
LOCATION : THE AVENUE AT WHITE MARSH, 8125 HONEYGO BLVD
BALTIMORE, MARYLAND 21236
YOU MUST PARK BEHIND KOBE STEAKHOUSE
Ages 18 & up only at this time please
PLEASE DRESS IN YOUR *BEST* business attire & come “camera ready”. Men use hair product, Women please have your hairstyle and make up applied as we will be taking photos for you.
* CURRENT SAG MEMBERS * WILL HAVE A SPECIAL LINE TBD
We Do Not Discriminate Regarding Age, Race, Religion, Ability, or Orientation
PRIOR TO OPEN CALL, PLEASE REGISTER ON
www.marinellahumecasting.com (Google Chrome only)
Can’t attend? Email current selfies name sizes ht & wt union status to: [email protected] |
def ipv6(self, ipv6: str):
self._ipv6 = ipv6 |
<reponame>timanema/brb-thesis
package brb
import (
"fmt"
"reflect"
)
type brachaWrapper struct {
messageType uint8
msg Size
}
func (b brachaWrapper) SizeOf() uintptr {
return reflect.TypeOf(b.messageType).Size() + b.msg.SizeOf()
}
type BrachaDolev struct {
b *Bracha
d *DolevImproved
n Network
app Application
cfg Config
brachaBroadcast map[int]struct{}
}
var _ Protocol = (*BrachaDolev)(nil)
var _ Network = (*BrachaDolev)(nil)
var _ Application = (*BrachaDolev)(nil)
func (bd *BrachaDolev) Init(n Network, app Application, cfg Config) {
bd.n = n
bd.app = app
bd.cfg = cfg
bd.brachaBroadcast = make(map[int]struct{})
sil := cfg.Silent
if !cfg.Silent && cfg.Byz {
fmt.Printf("process %v is a Bracha-Dolev Byzantine node\n", cfg.Id)
}
cfg.Silent = true
// Create bracha instance with BD as the network
if bd.b == nil {
bd.b = &Bracha{}
}
bCfg := cfg
nodes := cfg.Graph.Nodes()
bCfg.Neighbours = make([]uint64, 0, nodes.Len())
bCfg.Graph = nil
for nodes.Next() {
i := uint64(nodes.Node().ID())
if i != cfg.Id {
bCfg.Neighbours = append(bCfg.Neighbours, i)
}
}
bd.b.Init(bd, app, bCfg)
// Create dolev (improved) instance with BD as the application
if bd.d == nil {
bd.d = &DolevImproved{}
}
bd.d.Init(n, bd, cfg)
cfg.Silent = sil
}
func (bd *BrachaDolev) Send(messageType uint8, _ uint64, uid uint32, data Size, bc BroadcastInfo) {
if _, ok := bd.brachaBroadcast[bc.Id]; !ok {
// Bracha is sending a message through Dolev
bd.d.Broadcast(uid, brachaWrapper{
messageType: messageType,
msg: data,
}, BroadcastInfo{})
//fmt.Printf("proc %v is broadcasting %v (%v for %v) through dolev with type %v\n", bd.cfg.Id, data, reflect.TypeOf(data).Name(), src, messageType)
// A message is broadcast only once to all
bd.brachaBroadcast[bc.Id] = struct{}{}
}
}
func (bd *BrachaDolev) Deliver(uid uint32, payload Size, src uint64) {
if src == bd.cfg.Id {
return
}
// Dolev is delivering a message, so send it to Bracha
m := payload.(brachaWrapper)
bd.b.Receive(m.messageType, src, uid, m.msg)
//fmt.Printf("proc %v has Dolev delivered %v (%v from %v) through dolev with type %v\n", bd.cfg.Id, m.msg, reflect.TypeOf(m.msg).Name(), src, m.messageType)
}
func (bd *BrachaDolev) Receive(_ uint8, src uint64, uid uint32, data Size) {
// Network is delivering a messages, pass to Dolev
bd.d.Receive(0, src, uid, data)
}
func (bd *BrachaDolev) Broadcast(uid uint32, payload Size, _ BroadcastInfo) {
// Application is requesting a broadcast, pass to Bracha
bd.b.Broadcast(uid, payload, BroadcastInfo{})
}
func (bd *BrachaDolev) Category() ProtocolCategory {
return BrachaDolevCat
}
func (bd *BrachaDolev) TriggerStat(uid uint32, n NetworkStat) {
bd.n.TriggerStat(uid, n)
}
|
/**
* Sleep without caring the time.
* it takes longer than regular sleep.
*/
public void sleepTimeIndependent() {
int seconds;
World world = getLocation().getWorld();
Writer.write("You fall asleep.");
seconds = PartOfDay.getSecondsToNext(world.getWorldDate(), PartOfDay.DAWN);
seconds += nextRandomTimeChunk();
seconds *= 3;
statistics.getHeroStatistics().incrementSleepingTime(seconds);
while (seconds > 0) {
final int cycleDuration = Math.min(DREAM_DURATION_IN_SECONDS, seconds);
Engine.rollDateAndRefresh(cycleDuration);
long timeForSleep = (long) MILLISECONDS_TO_SLEEP_AN_HOUR * cycleDuration / HOUR.as(SECOND);
Sleeper.sleep(timeForSleep);
if (cycleDuration == DREAM_DURATION_IN_SECONDS) {
Writer.write(Libraries.getDreamLibrary().next());
}
seconds -= cycleDuration;
if (!getHealth().isFull()) {
int healing = getHealth().getMaximum() * cycleDuration / SECONDS_TO_REGENERATE_FULL_HEALTH;
getHealth().incrementBy(healing);
}
}
Writer.write("You wake up.");
} |
Request by This one, of them all, definitely took the longest to complete, for fairly obvious reasons. (A.K.A. More 'scenery,' yet not really. LoL)Once more, the request was to draw the ponies within their human forms, without the skin tones originally given, and then to also make them each a Guardian of the Veil (and also notable allies).In the case of Sunset Shimmer, here, however, she was requested last minute, in general, but also if she could take the position of Orube/'Rebecca Rudolph,' and her "Might wanna start running, because I'm about to literally kick your ass" fighting attire (with same pose, another fave of mine).And, once again, as I do not watch the series or am involved within the community as a result, I had to ask SEGASister for lots of info, one of which was what people usually make the ponies, ethnicity and/or ancestry wise, whenever drawn within human form. However, this time around, since, according to her, this one's a pretty new character, 'no one' really knows or has a set ethnicity upon her yet.Sooooo, I just left her more or less the skin tone she does possess within the canon.And as for the hairstyle, it was rather "....Huh...." when looking at the reference SEGASister gave me, and then also looking at a few on Google and seeing she seems to have two, but . . . not . . . really? o_O' LoL EITHER way, I used the ref SEGA gave, which I can say to YOU, those viewing/reading this, that think of it as Sunset assuming Orube's role even more, in the sense that when Orube's within her 'fighter garb,' her hairstyle is different by comparison to when she's masquerading around as 'Innocent Earth Civilian' Rebecca.Also, I did decide to keep, or show, rather, her pony ear, as well as keeping Orube's rather long kitty-like nails within combination just to sort of maintain the "I'm actually an alien, and your Earthly ways and customs are just . . . wtf to me at the moment" notion of Orube's character within the beginning.Finally, as for the scowl, again, I know zero about Sunset Shimmer, but am assuming she's clearly the typical counterpart most series do where main characters are concerned. So she's most probably Twilight Sparkle's rival, or was, judging from a few of the screenshots I saw within Google Images. Regardless, I used, or 'kept' the scowl I kept seeing on her face within said image search . . . which works with this pose, considering she's being Orube at the moment, and probably about to beat someone's ass into the ground, anyway.ANYWAY! Was really fun to attempt drawing Orube-related crap, again (since I haven't in years and years, since the first, and 'last' Orube drawing I'd done during my beginnings of attempting more active color-based works), even if I had to 'morph' her head into another person's . . . which took a few tries to get it ALL right, overall.Still.I'M just glad I'm FINALLY done with this damned 'series' (not the show-series, although it's still not my personal cup of tea, this version, nope ^_^' But I STILL have my soft spot for cutie Fluttershy, gotdamn it >_< LoL), because it just feels like I've been doing it my entire pregnancy . . . which, technically, I have, now being 2 weeks away from meeting Evie.NEXT time someone asks for possible MLP artwork, I'll definitely reopen my commissions for them, if they'll be this many, again, anyway. ^_^' Phew. . . .-------------------- |
<filename>test/import/FSHImporter.SDRules.test.ts
import {
assertCardRule,
assertAssignmentRule,
assertFlagRule,
assertOnlyRule,
assertBindingRule,
assertContainsRule,
assertCaretValueRule,
assertObeysRule,
assertInsertRule,
assertAddElementRule
} from '../testhelpers/asserts';
import {
FshCanonical,
FshCode,
FshQuantity,
FshRatio,
FshReference,
ParamRuleSet
} from '../../src/fshtypes';
import { loggerSpy } from '../testhelpers/loggerSpy';
import { stats } from '../../src/utils/FSHLogger';
import { importSingleText } from '../testhelpers/importSingleText';
import { FSHImporter, RawFSH } from '../../src/import';
import { EOL } from 'os';
import { leftAlign } from '../utils/leftAlign';
describe('FSHImporter', () => {
beforeEach(() => loggerSpy.reset());
describe('SD Rules', () => {
// These rules are shared across all StructureDefinition entities:
// Profile, Extension, Resource, Logical
// The intent is that the comprehensive testing of these common rules occurs here
// while in each StructureDefinition entity test suite, these rules will have simple
// smoke tests.
describe('#cardRule', () => {
it('should parse simple card rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..5
* value[x] 1..1
* component 2..*
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertCardRule(profile.rules[0], 'category', 1, 5);
assertCardRule(profile.rules[1], 'value[x]', 1, 1);
assertCardRule(profile.rules[2], 'component', 2, '*');
});
it('should parse card rule with only min', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertCardRule(profile.rules[0], 'category', 1, ''); // Unspecified max
});
it('should parse card rule with only max', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category ..5
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertCardRule(profile.rules[0], 'category', NaN, '5'); // Unspecified min
});
it('should log an error if neither side is specified', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category ..
`);
const result = importSingleText(input, 'BadCard.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1); // Rule is still set and element's current cardinalities will be used at export
expect(loggerSpy.getLastMessage('error')).toMatch(
/Neither side of the cardinality was specified on path \"category\". A min, max, or both need to be specified.\D*/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: BadCard\.fsh.*Line: 4\D*/s);
});
it('should parse card rules w/ flags', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..5 MS
* value[x] 1..1 ?!
* component 2..* SU
* interpretation 1..* TU
* note 0..11 N
* bodySite 1..1 D
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(12);
assertCardRule(profile.rules[0], 'category', 1, 5);
assertFlagRule(
profile.rules[1],
'category',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertCardRule(profile.rules[2], 'value[x]', 1, 1);
assertFlagRule(
profile.rules[3],
'value[x]',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertCardRule(profile.rules[4], 'component', 2, '*');
assertFlagRule(
profile.rules[5],
'component',
undefined,
true,
undefined,
undefined,
undefined,
undefined
);
assertCardRule(profile.rules[6], 'interpretation', 1, '*');
assertFlagRule(
profile.rules[7],
'interpretation',
undefined,
undefined,
undefined,
true,
undefined,
undefined
);
assertCardRule(profile.rules[8], 'note', 0, '11');
assertFlagRule(
profile.rules[9],
'note',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
assertCardRule(profile.rules[10], 'bodySite', 1, '1');
assertFlagRule(
profile.rules[11],
'bodySite',
undefined,
undefined,
undefined,
undefined,
undefined,
true
);
});
it('should parse card rules w/ multiple flags', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category 1..5 MS ?! TU
* value[x] 1..1 ?! SU N
* component 2..* SU MS D
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(6);
assertCardRule(profile.rules[0], 'category', 1, 5);
assertFlagRule(
profile.rules[1],
'category',
true,
undefined,
true,
true,
undefined,
undefined
);
assertCardRule(profile.rules[2], 'value[x]', 1, 1);
assertFlagRule(
profile.rules[3],
'value[x]',
undefined,
true,
true,
undefined,
true,
undefined
);
assertCardRule(profile.rules[4], 'component', 2, '*');
assertFlagRule(
profile.rules[5],
'component',
true,
true,
undefined,
undefined,
undefined,
true
);
});
});
describe('#flagRule', () => {
it('should parse single-path single-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category MS
* value[x] ?!
* component SU
* interpretation TU
* note N
* bodySite D
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(6);
assertFlagRule(
profile.rules[0],
'category',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[2],
'component',
undefined,
true,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[3],
'interpretation',
undefined,
undefined,
undefined,
true,
undefined,
undefined
);
assertFlagRule(
profile.rules[4],
'note',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[5],
'bodySite',
undefined,
undefined,
undefined,
undefined,
undefined,
true
);
});
it('should parse single-path multi-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category MS ?! N
* value[x] ?! SU D
* component MS SU ?! TU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertFlagRule(
profile.rules[0],
'category',
true,
undefined,
true,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
undefined,
true,
true,
undefined,
undefined,
true
);
assertFlagRule(profile.rules[2], 'component', true, true, true, true, undefined, undefined);
});
it('should parse multi-path single-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category and value[x] and component MS
* subject and focus ?!
* interpretation and note N
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(7);
assertFlagRule(
profile.rules[0],
'category',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[2],
'component',
true,
undefined,
undefined,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[3],
'subject',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[4],
'focus',
undefined,
undefined,
true,
undefined,
undefined,
undefined
);
assertFlagRule(
profile.rules[5],
'interpretation',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[6],
'note',
undefined,
undefined,
undefined,
undefined,
true,
undefined
);
});
it('should parse multi-path multi-value flag rules', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category and value[x] and component MS SU N
* subject and focus ?! SU TU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(5);
assertFlagRule(
profile.rules[0],
'category',
true,
true,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[1],
'value[x]',
true,
true,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[2],
'component',
true,
true,
undefined,
undefined,
true,
undefined
);
assertFlagRule(
profile.rules[3],
'subject',
undefined,
true,
true,
true,
undefined,
undefined
);
assertFlagRule(
profile.rules[4],
'focus',
undefined,
true,
true,
true,
undefined,
undefined
);
});
it('should log an error when paths are listed with commas', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category, value[x] , component MS SU N
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using ',' to list items is no longer supported/s
);
});
});
describe('#BindingRule', () => {
it('should parse value set rules w/ names and strengths', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from CategoryValueSet (required)
* code from CodeValueSet (extensible)
* valueCodeableConcept from ValueValueSet (preferred)
* component.code from ComponentCodeValueSet (example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(4);
assertBindingRule(profile.rules[0], 'category', 'CategoryValueSet', 'required');
assertBindingRule(profile.rules[1], 'code', 'CodeValueSet', 'extensible');
assertBindingRule(profile.rules[2], 'valueCodeableConcept', 'ValueValueSet', 'preferred');
assertBindingRule(profile.rules[3], 'component.code', 'ComponentCodeValueSet', 'example');
});
it('should parse value set rules w/ urls and strengths', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from http://example.org/fhir/ValueSet/CategoryValueSet (required)
* code from http://example.org/fhir/ValueSet/CodeValueSet (extensible)
* valueCodeableConcept from http://example.org/fhir/ValueSet/ValueValueSet (preferred)
* component.code from http://example.org/fhir/ValueSet/ComponentCodeValueSet (example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(4);
assertBindingRule(
profile.rules[0],
'category',
'http://example.org/fhir/ValueSet/CategoryValueSet',
'required'
);
assertBindingRule(
profile.rules[1],
'code',
'http://example.org/fhir/ValueSet/CodeValueSet',
'extensible'
);
assertBindingRule(
profile.rules[2],
'valueCodeableConcept',
'http://example.org/fhir/ValueSet/ValueValueSet',
'preferred'
);
assertBindingRule(
profile.rules[3],
'component.code',
'http://example.org/fhir/ValueSet/ComponentCodeValueSet',
'example'
);
});
it('should accept and translate aliases for value set URLs', () => {
const input = leftAlign(`
Alias: CAT = http://example.org/fhir/ValueSet/CategoryValueSet
Alias: CODE = http://example.org/fhir/ValueSet/CodeValueSet
Alias: VALUE = http://example.org/fhir/ValueSet/ValueValueSet
Alias: COMP = http://example.org/fhir/ValueSet/ComponentCodeValueSet
Profile: ObservationProfile
Parent: Observation
* category from CAT (required)
* code from CODE (extensible)
* valueCodeableConcept from VALUE (preferred)
* component.code from COMP (example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(4);
assertBindingRule(
profile.rules[0],
'category',
'http://example.org/fhir/ValueSet/CategoryValueSet',
'required'
);
assertBindingRule(
profile.rules[1],
'code',
'http://example.org/fhir/ValueSet/CodeValueSet',
'extensible'
);
assertBindingRule(
profile.rules[2],
'valueCodeableConcept',
'http://example.org/fhir/ValueSet/ValueValueSet',
'preferred'
);
assertBindingRule(
profile.rules[3],
'component.code',
'http://example.org/fhir/ValueSet/ComponentCodeValueSet',
'example'
);
});
it('should parse value set rules w/ numeric names', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from 123 (required)
* code from 456 (extensible)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertBindingRule(profile.rules[0], 'category', '123', 'required');
assertBindingRule(profile.rules[1], 'code', '456', 'extensible');
});
it('should parse value set rules w/ no strength and default to required', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category from CategoryValueSet
* code from http://example.org/fhir/ValueSet/CodeValueSet
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertBindingRule(profile.rules[0], 'category', 'CategoryValueSet', 'required');
assertBindingRule(
profile.rules[1],
'code',
'http://example.org/fhir/ValueSet/CodeValueSet',
'required'
);
});
it('should ignore the units keyword and log an error when parsing value set rules on Quantity', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity units from http://unitsofmeasure.org
`);
const result = importSingleText(input, 'UselessQuant.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'units' keyword is no longer supported.*File: UselessQuant\.fsh.*Line: 4\D*/s
);
});
});
describe('#assignmentRule', () => {
it('should parse assigned value boolean rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueBoolean = true
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueBoolean', true);
});
it('should parse assigned value boolean rule with (exactly) modifier', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueBoolean = true (exactly)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueBoolean', true, true);
});
it('should parse assigned value number (decimal) rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueDecimal = 1.23
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueDecimal', 1.23);
});
it('should parse assigned value number (integer) rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueInteger = 123
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueInteger', BigInt(123));
});
it('should parse assigned value string rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueString = "hello world"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueString', 'hello world');
});
it('should parse assigned value multi-line string rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueString = """
hello
world
"""
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'valueString', 'hello\nworld');
});
it('should parse assigned value date rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueDateTime = 2019-11-01T12:30:01.999Z
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// For now, treating dates like strings
assertAssignmentRule(profile.rules[0], 'valueDateTime', '2019-11-01T12:30:01.999Z');
});
it('should parse assigned value time rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueTime = 12:30:01.999-05:00
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// For now, treating dates like strings
assertAssignmentRule(profile.rules[0], 'valueTime', '12:30:01.999-05:00');
});
it('should parse assigned value code rule', () => {
const input = leftAlign(`
Alias: LOINC = http://loinc.org
Profile: ObservationProfile
Parent: Observation
* status = #final
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCode = new FshCode('final').withLocation([6, 12, 6, 17]).withFile('');
assertAssignmentRule(profile.rules[0], 'status', expectedCode);
});
it('should parse assigned value CodeableConcept rule', () => {
const input = leftAlign(`
Alias: LOINC = http://loinc.org
Profile: ObservationProfile
Parent: Observation
* valueCodeableConcept = LOINC#718-7 "Hemoglobin [Mass/volume] in Blood"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCode = new FshCode(
'718-7',
'http://loinc.org',
'Hemoglobin [Mass/volume] in Blood'
)
.withLocation([6, 26, 6, 72])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueCodeableConcept', expectedCode);
});
it('should parse assigned value CodeableConcept rule with (exactly) modifier', () => {
const input = leftAlign(`
Alias: LOINC = http://loinc.org
Profile: ObservationProfile
Parent: Observation
* valueCodeableConcept = LOINC#718-7 "Hemoglobin [Mass/volume] in Blood" (exactly)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCode = new FshCode(
'718-7',
'http://loinc.org',
'Hemoglobin [Mass/volume] in Blood'
)
.withLocation([6, 26, 6, 72])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueCodeableConcept', expectedCode, true);
});
it('should ignore the units keyword and log a warning when parsing an assigned value FSHCode rule with units on Quantity', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity units = http://unitsofmeasure.org#cGy
`);
const result = importSingleText(input, 'UselessUnits.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'units' keyword is no longer supported.*File: UselessUnits\.fsh.*Line: 4\D*/s
);
});
it('should parse assigned value Quantity rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity = 1.5 'mm'
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedQuantity = new FshQuantity(
1.5,
new FshCode('mm', 'http://unitsofmeasure.org').withLocation([5, 23, 5, 26]).withFile('')
)
.withLocation([5, 19, 5, 26])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueQuantity', expectedQuantity);
});
it('should parse assigned value Quantity rule with unit display', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueQuantity = 155.0 '[lb_av]' "lb"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedQuantity = new FshQuantity(
155.0,
new FshCode('[lb_av]', 'http://unitsofmeasure.org', 'lb')
.withLocation([5, 25, 5, 33])
.withFile('')
)
.withLocation([5, 19, 5, 38])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueQuantity', expectedQuantity);
});
it('should parse assigned value Ratio rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 'mg' : 1 'dL'
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(
130,
new FshCode('mg', 'http://unitsofmeasure.org').withLocation([5, 20, 5, 23]).withFile('')
)
.withLocation([5, 16, 5, 23])
.withFile(''),
new FshQuantity(
1,
new FshCode('dL', 'http://unitsofmeasure.org').withLocation([5, 29, 5, 32]).withFile('')
)
.withLocation([5, 27, 5, 32])
.withFile('')
)
.withLocation([5, 16, 5, 32])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Ratio rule w/ numeric numerator', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 : 1 'dL'
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(130).withLocation([5, 16, 5, 18]).withFile(''),
new FshQuantity(
1,
new FshCode('dL', 'http://unitsofmeasure.org').withLocation([5, 24, 5, 27]).withFile('')
)
.withLocation([5, 22, 5, 27])
.withFile('')
)
.withLocation([5, 16, 5, 27])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Ratio rule w/ numeric denominator', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 'mg' : 1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(
130,
new FshCode('mg', 'http://unitsofmeasure.org').withLocation([5, 20, 5, 23]).withFile('')
)
.withLocation([5, 16, 5, 23])
.withFile(''),
new FshQuantity(1).withLocation([5, 27, 5, 27]).withFile('')
)
.withLocation([5, 16, 5, 27])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Ratio rule w/ numeric numerator and denominator', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* valueRatio = 130 : 1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedRatio = new FshRatio(
new FshQuantity(130).withLocation([5, 16, 5, 18]).withFile(''),
new FshQuantity(1).withLocation([5, 22, 5, 22]).withFile('')
)
.withLocation([5, 16, 5, 22])
.withFile('');
assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio);
});
it('should parse assigned value Reference rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(fooProfile)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('fooProfile')
.withLocation([5, 13, 5, 33])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should parse assigned value Reference rules while allowing and translating aliases', () => {
const input = leftAlign(`
Alias: FOO = http://hl7.org/fhir/StructureDefinition/Foo
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(FOO) "bar"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference(
'http://hl7.org/fhir/StructureDefinition/Foo',
'bar'
)
.withLocation([6, 13, 6, 32])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should parse assigned value Reference rule with a display string', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(fooProfile) "bar"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('fooProfile', 'bar')
.withLocation([5, 13, 5, 39])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should parse assigned value Reference rule with whitespace', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference( fooProfile )
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('fooProfile')
.withLocation([5, 13, 5, 39])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
});
it('should log an error when an assigned value Reference rule has a choice of references', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* basedOn = Reference(cakeProfile or pieProfile)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedReference = new FshReference('cakeProfile')
.withLocation([5, 13, 5, 48])
.withFile('');
assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Multiple choices of references are not allowed when setting a value.*Line: 5\D*/s
);
});
it('should parse assigned value using Canonical', () => {
const input = leftAlign(`
CodeSystem: Example
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical(Example)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('Example')
.withLocation([8, 24, 8, 41])
.withFile('');
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned value using Canonical with spaces around entity name', () => {
const input = leftAlign(`
CodeSystem: SpaceyExample
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical( SpaceyExample )
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('SpaceyExample') // No spaces are included in the entityName
.withLocation([8, 24, 8, 51])
.withFile('');
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned value using Canonical with a version', () => {
const input = leftAlign(`
CodeSystem: Example
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical(Example|1.2.3)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('Example')
.withLocation([8, 24, 8, 47])
.withFile('');
expectedCanonical.version = '1.2.3';
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned value using Canonical with a version which contains a |', () => {
const input = leftAlign(`
CodeSystem: Example
* #first
* #second
Profile: ObservationProfile
Parent: Observation
* code.coding.system = Canonical( Example|1.2.3|aWeirdVersion )
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
const expectedCanonical = new FshCanonical('Example')
.withLocation([8, 24, 8, 65])
.withFile('');
expectedCanonical.version = '1.2.3|aWeirdVersion';
assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical);
});
it('should parse assigned values that are an alias', () => {
const input = leftAlign(`
Alias: EXAMPLE = http://example.org
Profile: PatientProfile
Parent: Patient
* identifier.system = EXAMPLE
`);
const result = importSingleText(input);
const profile = result.profiles.get('PatientProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'identifier.system', 'http://example.org');
});
it('should parse an assigned value Resource rule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* contained[0] = SomeInstance
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertAssignmentRule(profile.rules[0], 'contained[0]', 'SomeInstance', false, true);
});
});
describe('#onlyRule', () => {
it('should parse an only rule with one type', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only Quantity
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(profile.rules[0], 'value[x]', { type: 'Quantity' });
});
it('should parse an only rule with multiple types', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only Quantity or CodeableConcept or string
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'value[x]',
{ type: 'Quantity' },
{ type: 'CodeableConcept' },
{ type: 'string' }
);
});
it('should parse an only rule with one numeric type name', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only 123
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(profile.rules[0], 'value[x]', { type: '123' });
});
it('should parse an only rule with multiple numeric type names', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* value[x] only 123 or 456 or 789
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'value[x]',
{ type: '123' },
{ type: '456' },
{ type: '789' }
);
});
it('should parse an only rule with a reference to one type', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference(Practitioner)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(profile.rules[0], 'performer', { type: 'Practitioner', isReference: true });
});
it('should parse an only rule with a reference to multiple types', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference(Organization or CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'performer',
{ type: 'Organization', isReference: true },
{ type: 'CareTeam', isReference: true }
);
});
it('should parse an only rule with a reference to multiple types with whitespace', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference( Organization or CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'performer',
{ type: 'Organization', isReference: true },
{ type: 'CareTeam', isReference: true }
);
});
it('should allow and translate aliases for only types', () => {
const input = leftAlign(`
Alias: QUANTITY = http://hl7.org/fhir/StructureDefinition/Quantity
Alias: CODING = http://hl7.org/fhir/StructureDefinition/Coding
Profile: ObservationProfile
Parent: Observation
* value[x] only CodeableConcept or CODING or string or QUANTITY
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertOnlyRule(
profile.rules[0],
'value[x]',
{ type: 'CodeableConcept' },
{ type: 'http://hl7.org/fhir/StructureDefinition/Coding' },
{ type: 'string' },
{ type: 'http://hl7.org/fhir/StructureDefinition/Quantity' }
);
});
it('should log an error when references are listed with pipes', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference(Organization | CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// Following is correct expectation. Error prevents the proper resolution of multiple references
assertOnlyRule(profile.rules[0], 'performer', { type: 'Reference(Organization' });
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using '|' to list references is no longer supported\..*Line: 4\D*/s
);
});
it('should log an error when references are listed with pipes with whitespace', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* performer only Reference( Organization | CareTeam)
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
// Following is correct expectation. Error prevents the proper resolution of multiple references
assertOnlyRule(profile.rules[0], 'performer', { type: 'Reference(' });
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using '|' to list references is no longer supported\..*Line: 4\D*/s
);
});
});
describe('#containsRule', () => {
it('should parse contains rule with one item', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component contains SystolicBP 1..1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertContainsRule(profile.rules[0], 'component', 'SystolicBP');
assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1);
});
it('should parse contains rule with one item declaring an aliased type', () => {
const input = leftAlign(`
Alias: OffsetExtension = http://hl7.org/fhir/StructureDefinition/observation-timeOffset
Profile: ObservationProfile
Parent: Observation
* component.extension contains OffsetExtension named offset 0..1
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertContainsRule(profile.rules[0], 'component.extension', {
name: 'offset',
type: 'http://hl7.org/fhir/StructureDefinition/observation-timeOffset'
});
assertCardRule(profile.rules[1], 'component.extension[offset]', 0, 1);
});
it('should parse contains rule with one item declaring an FSH extension type', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component.extension contains ComponentExtension named compext 0..1
Extension: ComponentExtension
Id: component-extension
* value[x] only CodeableConcept
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(2);
assertContainsRule(profile.rules[0], 'component.extension', {
name: 'compext',
type: 'ComponentExtension'
});
assertCardRule(profile.rules[1], 'component.extension[compext]', 0, 1);
});
it('should parse contains rules with multiple items', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component contains SystolicBP 1..1 and DiastolicBP 2..*
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertContainsRule(profile.rules[0], 'component', 'SystolicBP', 'DiastolicBP');
assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1);
assertCardRule(profile.rules[2], 'component[DiastolicBP]', 2, '*');
});
it('should parse contains rule with mutliple items, some declaring types', () => {
const input = leftAlign(`
Alias: FocusCodeExtension = http://hl7.org/fhir/StructureDefinition/observation-focusCode
Alias: PreconditionExtension = http://hl7.org/fhir/StructureDefinition/observation-precondition
Profile: ObservationProfile
Parent: Observation
* extension contains
foo 0..1 and
FocusCodeExtension named focus 1..1 and
bar 0..* and
PreconditionExtension named pc 1..*
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(5);
assertContainsRule(
profile.rules[0],
'extension',
'foo',
{
name: 'focus',
type: 'http://hl7.org/fhir/StructureDefinition/observation-focusCode'
},
'bar',
{
name: 'pc',
type: 'http://hl7.org/fhir/StructureDefinition/observation-precondition'
}
);
assertCardRule(profile.rules[1], 'extension[foo]', 0, 1);
assertCardRule(profile.rules[2], 'extension[focus]', 1, 1);
assertCardRule(profile.rules[3], 'extension[bar]', 0, '*');
assertCardRule(profile.rules[4], 'extension[pc]', 1, '*');
});
it('should parse contains rules with flags', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* component contains SystolicBP 1..1 MS D and DiastolicBP 2..* MS SU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(5);
assertContainsRule(profile.rules[0], 'component', 'SystolicBP', 'DiastolicBP');
assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1);
assertFlagRule(
profile.rules[2],
'component[SystolicBP]',
true,
undefined,
undefined,
undefined,
undefined,
true
);
assertCardRule(profile.rules[3], 'component[DiastolicBP]', 2, '*');
assertFlagRule(
profile.rules[4],
'component[DiastolicBP]',
true,
true,
undefined,
undefined,
undefined,
undefined
);
});
it('should parse contains rule with item declaring a type and flags', () => {
const input = leftAlign(`
Alias: OffsetExtension = http://hl7.org/fhir/StructureDefinition/observation-timeOffset
Profile: ObservationProfile
Parent: Observation
* component.extension contains OffsetExtension named offset 0..1 MS TU
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertContainsRule(profile.rules[0], 'component.extension', {
name: 'offset',
type: 'http://hl7.org/fhir/StructureDefinition/observation-timeOffset'
});
assertCardRule(profile.rules[1], 'component.extension[offset]', 0, 1);
assertFlagRule(
profile.rules[2],
'component.extension[offset]',
true,
undefined,
undefined,
true,
undefined,
undefined
);
});
});
describe('#caretValueRule', () => {
it('should parse caret value rules with no path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* ^description = "foo"
* ^experimental = false
* ^keyword[0] = foo#bar "baz"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], '', 'description', 'foo', false);
assertCaretValueRule(profile.rules[1], '', 'experimental', false, false);
assertCaretValueRule(
profile.rules[2],
'',
'keyword[0]',
new FshCode('bar', 'foo', 'baz').withLocation([6, 17, 6, 29]).withFile(''),
false
);
});
it('should parse caret value rules with a path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* status ^short = "foo"
* status ^sliceIsConstraining = false
* status ^code[0] = foo#bar "baz"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], 'status', 'short', 'foo', false);
assertCaretValueRule(profile.rules[1], 'status', 'sliceIsConstraining', false, false);
assertCaretValueRule(
profile.rules[2],
'status',
'code[0]',
new FshCode('bar', 'foo', 'baz').withLocation([6, 21, 6, 33]).withFile(''),
false
);
});
it('should not include non-breaking spaces as part of the caret path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* status ^short\u00A0= "Non-breaking"
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], 'status', 'short', 'Non-breaking', false);
});
it('should add resources to the contained array using a CaretValueRule', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* ^contained = myResource
`);
const result = importSingleText(input);
const profile = result.profiles.get('ObservationProfile');
assertCaretValueRule(profile.rules[0], '', 'contained', 'myResource', true);
});
});
describe('#obeysRule', () => {
it('should parse an obeys rule with one invariant and no path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* obeys SomeInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertObeysRule(profile.rules[0], '', 'SomeInvariant');
});
it('should parse an obeys rule with one invariant and a path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category obeys SomeInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertObeysRule(profile.rules[0], 'category', 'SomeInvariant');
});
it('should parse an obeys rule with multiple invariants and no path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* obeys SomeInvariant and ThisInvariant and ThatInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertObeysRule(profile.rules[0], '', 'SomeInvariant');
assertObeysRule(profile.rules[1], '', 'ThisInvariant');
assertObeysRule(profile.rules[2], '', 'ThatInvariant');
});
it('should parse an obeys rule with multiple invariants and a path', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* category obeys SomeInvariant and ThisInvariant and ThatInvariant
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(3);
assertObeysRule(profile.rules[0], 'category', 'SomeInvariant');
assertObeysRule(profile.rules[1], 'category', 'ThisInvariant');
assertObeysRule(profile.rules[2], 'category', 'ThatInvariant');
});
it('should parse an obeys rule with a numeric invariant name', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* obeys 123
`);
const result = importSingleText(input, 'Obeys.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertObeysRule(profile.rules[0], '', '123');
});
});
describe('#insertRule', () => {
let importer: FSHImporter;
beforeEach(() => {
// To explain a bit about why stats are used here and not in other tests:
// When parsing generated documents, the logging level is temporarily raised
// in order to suppress console output. However, messages still go to the logger
// and therefore are detected by loggerSpy. However, the stats should provide an
// accurate reflection of the number of times that errors and warnings were logged
// while the logger is at the normal level.
loggerSpy.reset();
stats.reset();
importer = new FSHImporter();
// RuleSet: OneParamRuleSet (val)
// * status = {val}
const oneParamRuleSet = new ParamRuleSet('OneParamRuleSet')
.withFile('RuleSet.fsh')
.withLocation([1, 12, 2, 27]);
oneParamRuleSet.parameters = ['val'];
oneParamRuleSet.contents = '* status = {val}';
importer.paramRuleSets.set(oneParamRuleSet.name, oneParamRuleSet);
// RuleSet: MultiParamRuleSet (status, value, maxNote)
// * status = {status}
// * valueString = {value}
// * note 0..{maxNote}
const multiParamRuleSet = new ParamRuleSet('MultiParamRuleSet')
.withFile('RuleSet.fsh')
.withLocation([4, 12, 7, 30]);
multiParamRuleSet.parameters = ['status', 'value', 'maxNote'];
multiParamRuleSet.contents = [
'* status = {status}',
'* valueString = {value}',
'* note 0..{maxNote}'
].join(EOL);
importer.paramRuleSets.set(multiParamRuleSet.name, multiParamRuleSet);
// RuleSet: EntryRules (continuation)
// * insert {continuation}Rules (5)
const entryRules = new ParamRuleSet('EntryRules')
.withFile('RuleSet.fsh')
.withLocation([9, 12, 10, 43]);
entryRules.parameters = ['continuation'];
entryRules.contents = '* insert {continuation}Rules (5)';
importer.paramRuleSets.set(entryRules.name, entryRules);
// RuleSet: RecursiveRules (value)
// * interpretation 0..{value}
// * insert EntryRules (BaseCase)
const recursiveRules = new ParamRuleSet('RecursiveRules')
.withFile('RuleSet.fsh')
.withLocation([12, 12, 14, 41]);
recursiveRules.parameters = ['value'];
recursiveRules.contents = [
'* interpretation 0..{value}',
'* insert EntryRules (BaseCase)'
].join(EOL);
importer.paramRuleSets.set(recursiveRules.name, recursiveRules);
// RuleSet: BaseCaseRules (value)
// * note 0..{value}
const baseCaseRules = new ParamRuleSet('BaseCaseRules')
.withFile('RuleSet.fsh')
.withLocation([16, 12, 17, 28]);
baseCaseRules.parameters = ['value'];
baseCaseRules.contents = '* note 0..{value}';
importer.paramRuleSets.set(baseCaseRules.name, baseCaseRules);
// RuleSet: CardRuleSet (path, min, max)
// * {path} {min}..{max}
// * note {min}..{max}
const cardRuleSet = new ParamRuleSet('CardRuleSet')
.withFile('RuleSet.fsh')
.withLocation([19, 12, 21, 30]);
cardRuleSet.parameters = ['path', 'min', 'max'];
cardRuleSet.contents = ['* {path} {min}..{max}', '* note {min}..{max}'].join(EOL);
importer.paramRuleSets.set(cardRuleSet.name, cardRuleSet);
// RuleSet: FirstRiskyRuleSet (value)
// * note ={value}
// * insert SecondRiskyRuleSet({value})
const firstRiskyRuleSet = new ParamRuleSet('FirstRiskyRuleSet')
.withFile('RuleSet.fsh')
.withLocation([23, 12, 25, 47]);
firstRiskyRuleSet.parameters = ['value'];
firstRiskyRuleSet.contents = [
'* note ={value}',
'* insert SecondRiskyRuleSet({value})'
].join(EOL);
importer.paramRuleSets.set(firstRiskyRuleSet.name, firstRiskyRuleSet);
// RuleSet: SecondRiskyRuleSet(value)
// * status ={value}
const secondRiskyRuleSet = new ParamRuleSet('SecondRiskyRuleSet')
.withFile('RuleSet.fsh')
.withLocation([27, 12, 28, 28]);
secondRiskyRuleSet.parameters = ['value'];
secondRiskyRuleSet.contents = '* status ={value}';
importer.paramRuleSets.set(secondRiskyRuleSet.name, secondRiskyRuleSet);
// RuleSet: WarningRuleSet(value)
// * focus[0] only Reference(Patient | {value})
// * focus[1] only Reference(Group | {value})
const warningRuleSet = new ParamRuleSet('WarningRuleSet')
.withFile('RuleSet.fsh')
.withLocation([30, 12, 32, 53]);
warningRuleSet.parameters = ['value'];
warningRuleSet.contents = [
'* focus[0] only Reference(Patient | {value})',
'* focus[1] only Reference(Group | {value})'
].join(EOL);
importer.paramRuleSets.set(warningRuleSet.name, warningRuleSet);
});
it('should parse an insert rule with a single RuleSet', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MyRuleSet
`);
const result = importSingleText(input, 'Insert.fsh');
const profile = result.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MyRuleSet');
});
it('should parse an insert rule with a RuleSet with one parameter', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert OneParamRuleSet (#final)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'OneParamRuleSet', ['#final']);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['OneParamRuleSet', '#final'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 1,
startColumn: 12,
endLine: 2,
endColumn: 27
}
});
expect(appliedRuleSet.rules[0].sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 2,
startColumn: 1,
endLine: 2,
endColumn: 17
}
});
});
it('should parse an insert rule with a RuleSet with multiple parameters', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (#preliminary, "this is a string value\\, right?", 4)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#preliminary',
'"this is a string value, right?"',
'4'
]);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify([
'MultiParamRuleSet',
'#preliminary',
'"this is a string value, right?"',
'4'
])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 4,
startColumn: 12,
endLine: 7,
endColumn: 30
}
});
expect(appliedRuleSet.rules).toHaveLength(3);
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('preliminary').withFile('Insert.fsh').withLocation([2, 12, 2, 23]),
false,
false
);
expect(appliedRuleSet.rules[0].sourceInfo.file).toBe('RuleSet.fsh');
expect(appliedRuleSet.rules[0].sourceInfo.location.startLine).toBe(5);
expect(appliedRuleSet.rules[0].sourceInfo.location.endLine).toBe(5);
assertAssignmentRule(
appliedRuleSet.rules[1],
'valueString',
'this is a string value, right?',
false,
false
);
expect(appliedRuleSet.rules[1].sourceInfo.file).toBe('RuleSet.fsh');
expect(appliedRuleSet.rules[1].sourceInfo.location.startLine).toBe(6);
expect(appliedRuleSet.rules[1].sourceInfo.location.endLine).toBe(6);
assertCardRule(appliedRuleSet.rules[2], 'note', 0, '4');
expect(appliedRuleSet.rules[2].sourceInfo.file).toBe('RuleSet.fsh');
expect(appliedRuleSet.rules[2].sourceInfo.location.startLine).toBe(7);
expect(appliedRuleSet.rules[2].sourceInfo.location.endLine).toBe(7);
});
it('should parse an insert rule with a parameter that contains right parenthesis', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert OneParamRuleSet (#final "(Final\\)")
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'OneParamRuleSet', ['#final "(Final)"']);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['OneParamRuleSet', '#final "(Final)"'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.rules).toHaveLength(1);
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 1,
startColumn: 12,
endLine: 2,
endColumn: 27
}
});
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('final', undefined, '(Final)')
.withFile('Insert.fsh')
.withLocation([2, 12, 2, 27]),
false,
false
);
});
it('should parse an insert rule with parameters that contain newline, tab, or backslash characters', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (#final, "very\\nstrange\\rvalue\\\\\\tindeed", 1)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#final',
'"very\\nstrange\\rvalue\\\\\\tindeed"',
'1'
]);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify([
'MultiParamRuleSet',
'#final',
'"very\\nstrange\\rvalue\\\\\\tindeed"',
'1'
])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 4,
startColumn: 12,
endLine: 7,
endColumn: 30
}
});
expect(appliedRuleSet.rules).toHaveLength(3);
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('final').withFile('Insert.fsh').withLocation([2, 12, 2, 17]),
false,
false
);
assertAssignmentRule(
appliedRuleSet.rules[1],
'valueString',
'very\nstrange\rvalue\\\tindeed',
false,
false
);
assertCardRule(appliedRuleSet.rules[2], 'note', 0, '1');
});
it('should parse an insert rule that separates its parameters onto multiple lines', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (
#final,
"string value",
7
)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(1);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#final',
'"string value"',
'7'
]);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['MultiParamRuleSet', '#final', '"string value"', '7'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 4,
startColumn: 12,
endLine: 7,
endColumn: 30
}
});
expect(appliedRuleSet.rules).toHaveLength(3);
assertAssignmentRule(
appliedRuleSet.rules[0],
'status',
new FshCode('final').withFile('Insert.fsh').withLocation([2, 12, 2, 17]),
false,
false
);
assertAssignmentRule(appliedRuleSet.rules[1], 'valueString', 'string value', false, false);
assertCardRule(appliedRuleSet.rules[2], 'note', 0, '7');
});
it('should generate a RuleSet only once when inserted with the same parameters multiple times in the same document', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MultiParamRuleSet (#preliminary, "something", 3)
* insert MultiParamRuleSet (#preliminary, "something", 3)
`);
const visitDocSpy = jest.spyOn(importer, 'visitDoc');
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
expect(doc.appliedRuleSets.size).toBe(1);
// expect one call to visitDoc for the Profile, and one for the generated RuleSet
expect(visitDocSpy).toHaveBeenCalledTimes(2);
// ensure the insert rules are still there (once upon a time, a bug caused the repeated rules to be omitted)
const profile = doc.profiles.get('ObservationProfile');
expect(profile).toBeDefined();
expect(profile.rules).toHaveLength(2);
assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [
'#preliminary',
'"something"',
'3'
]);
assertInsertRule(profile.rules[1], '', 'MultiParamRuleSet', [
'#preliminary',
'"something"',
'3'
]);
});
it('should parse an insert rule with parameters that will use the same RuleSet more than once with different parameters each time', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert EntryRules (Recursive)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
expect(doc.appliedRuleSets.size).toBe(4);
const firstEntryRules = doc.appliedRuleSets.get(
JSON.stringify(['EntryRules', 'Recursive'])
);
expect(firstEntryRules).toBeDefined();
expect(firstEntryRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 9,
startColumn: 12,
endLine: 10,
endColumn: 43
}
});
expect(firstEntryRules.rules).toHaveLength(1);
assertInsertRule(firstEntryRules.rules[0], '', 'RecursiveRules', ['5']);
const recursiveRules = doc.appliedRuleSets.get(JSON.stringify(['RecursiveRules', '5']));
expect(recursiveRules).toBeDefined();
expect(recursiveRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 12,
startColumn: 12,
endLine: 14,
endColumn: 41
}
});
expect(recursiveRules.rules).toHaveLength(2);
assertCardRule(recursiveRules.rules[0], 'interpretation', 0, '5');
assertInsertRule(recursiveRules.rules[1], '', 'EntryRules', ['BaseCase']);
const secondEntryRules = doc.appliedRuleSets.get(
JSON.stringify(['EntryRules', 'BaseCase'])
);
expect(secondEntryRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 9,
startColumn: 12,
endLine: 10,
endColumn: 43
}
});
expect(secondEntryRules.rules).toHaveLength(1);
assertInsertRule(secondEntryRules.rules[0], '', 'BaseCaseRules', ['5']);
const baseCaseRules = doc.appliedRuleSets.get(JSON.stringify(['BaseCaseRules', '5']));
expect(baseCaseRules).toBeDefined();
expect(baseCaseRules.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 16,
startColumn: 12,
endLine: 17,
endColumn: 28
}
});
expect(baseCaseRules.rules).toHaveLength(1);
assertCardRule(baseCaseRules.rules[0], 'note', 0, '5');
});
it('should log an error and not add a rule when an insert rule has the wrong number of parameters', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert OneParamRuleSet (#final, "Final")
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Incorrect number of parameters applied to RuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
it('should log an error and not add a rule when an insert rule with parameters refers to an undefined parameterized RuleSet', () => {
const input = leftAlign(`
Profile: ObservationProfile
Parent: Observation
* insert MysteriousRuleSet ("mystery")
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
const doc = allDocs[0];
const profile = doc.profiles.get('ObservationProfile');
expect(profile.rules).toHaveLength(0);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Could not find parameterized RuleSet named MysteriousRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
it('should log an error when an insert rule with parameters results in a parser error in the generated RuleSet', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert CardRuleSet(path with spaces, 1, *)
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Error parsing insert rule with parameterized RuleSet CardRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
it('should log one error when nested insert rules with parameters result in multiple parser errors in the generated RuleSets', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* note 0..1
* insert FirstRiskyRuleSet("Observation.id")
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Error parsing insert rule with parameterized RuleSet FirstRiskyRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Assignment rules must include at least one space both before and after the '=' sign.*File: Insert\.fsh.*Line: 5/s
);
});
it('should not log an error when an insert rule with parameters results in rules that are syntactically correct but semantically invalid', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert CardRuleSet(nonExistentPath, 7, 4)
`);
const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(allDocs).toHaveLength(1);
const doc = allDocs[0];
expect(doc.appliedRuleSets.size).toBe(1);
const appliedRuleSet = doc.appliedRuleSets.get(
JSON.stringify(['CardRuleSet', 'nonExistentPath', '7', '4'])
);
expect(appliedRuleSet).toBeDefined();
expect(appliedRuleSet.sourceInfo).toEqual({
file: 'RuleSet.fsh',
location: {
startLine: 19,
startColumn: 12,
endLine: 21,
endColumn: 30
}
});
// This rule is nonsense, of course, but figuring that out is the job of the exporter, not the importer.
assertCardRule(appliedRuleSet.rules[0], 'nonExistentPath', 7, '4');
assertCardRule(appliedRuleSet.rules[1], 'note', 7, '4');
expect(loggerSpy.getAllMessages('error')).toHaveLength(0);
});
it('should log one error when an insert rule with parameters results in warnings', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert WarningRuleSet(Device)
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Error parsing insert rule with parameterized RuleSet WarningRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Using '|' to list references is no longer supported\. Use 'or' to list multiple references.*File: Insert\.fsh.*Line: 4/s
);
});
it('should log one error when an insert rule with parameters results in non-parser errors', () => {
const input = leftAlign(`
Profile: MyObservation
Parent: Observation
* insert CardRuleSet(nonExistentPath, , )
`);
importer.import([new RawFSH(input, 'Insert.fsh')]);
expect(stats.numError).toBe(1);
expect(loggerSpy.getLastMessage('error')).toMatch(
/Errors parsing insert rule with parameterized RuleSet CardRuleSet/s
);
expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s);
});
});
});
describe('LR Rules', () => {
// These rules are shared across these StructureDefinition entities:
// Resource, Logical
describe('#addElementRule', () => {
it('should parse basic addElement rules with defaulted definition', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "short boolean"
* stuff 0..* string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
* medication 0..1 Canonical(Medication) "short Canonical"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(5);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }],
defs: { short: 'short boolean', definition: 'short boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'short Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'short Reference', definition: 'short Reference' }
});
assertAddElementRule(resource.rules[4], 'medication', {
card: { min: 0, max: '1' },
types: [{ type: 'Medication', isCanonical: true }],
defs: { short: 'short Canonical', definition: 'short Canonical' }
});
});
it('should parse basic addElement rules with specified definition', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "short boolean" "definition boolean"
* stuff 0..* string "short string" "definition string"
* address 1..* Address "short Address" "definition Address"
* person 0..1 Reference(Patient) "short Reference" "definition Reference"
* medication 0..1 Canonical(Medication|4.0.1) "short Canonical" "definition Canonical"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(5);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }],
defs: { short: 'short boolean', definition: 'definition boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'definition string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'definition Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'short Reference', definition: 'definition Reference' }
});
assertAddElementRule(resource.rules[4], 'medication', {
card: { min: 0, max: '1' },
types: [{ type: 'Medication|4.0.1', isCanonical: true }],
defs: { short: 'short Canonical', definition: 'definition Canonical' }
});
});
it('should parse addElement rules with multiple targetTypes', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean or number "short boolean"
* stuff 0..* string or markdown "short string"
* address 1..* Address "short Address"
* person 0..1 HumanName or Reference(Patient or RelatedPerson) "short multi-type"
* medication 0..1 CodeableConcept or Canonical(Medication or Immunization) "short multi-type 2"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(5);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }, { type: 'number' }],
defs: { short: 'short boolean', definition: 'short boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }, { type: 'markdown' }],
defs: { short: 'short string', definition: 'short string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'short Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
types: [
{ type: 'HumanName', isReference: false },
{ type: 'Patient', isReference: true },
{ type: 'RelatedPerson', isReference: true }
],
defs: { short: 'short multi-type', definition: 'short multi-type' }
});
assertAddElementRule(resource.rules[4], 'medication', {
card: { min: 0, max: '1' },
types: [
{ type: 'CodeableConcept', isCanonical: false },
{ type: 'Medication', isCanonical: true },
{ type: 'Immunization', isCanonical: true }
],
defs: { short: 'short multi-type 2', definition: 'short multi-type 2' }
});
});
it('should parse addElement rules with flags', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS ?! boolean "short boolean"
* stuff 0..* MS SU string "short string"
* address 1..* N Address "short Address"
* person 0..1 D TU Reference(Patient) "short Reference"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
flags: { mustSupport: true, modifier: true },
types: [{ type: 'boolean' }],
defs: { short: 'short boolean', definition: 'short boolean' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
flags: { mustSupport: true, summary: true },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
flags: { normative: true },
types: [{ type: 'Address' }],
defs: { short: 'short Address', definition: 'short Address' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
flags: { draft: true, trialUse: true },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'short Reference', definition: 'short Reference' }
});
});
it('should parse addElement rules with docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff"
* address 1..* N Address "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input);
const resource = result.resources.get('TestResource');
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
flags: { mustSupport: true },
types: [{ type: 'boolean' }],
defs: { short: 'is it valid?', definition: 'is it valid?' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'just stuff', definition: 'a list of some stuff' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
flags: { normative: true },
types: [{ type: 'Address' }],
defs: { short: 'current addresses', definition: 'at least one address is required' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
flags: { trialUse: true, draft: true },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'an associated patient', definition: 'added for TRIAL USE' }
});
});
it('should log an error for missing path', () => {
const input = leftAlign(`
Resource: TestResource
* 1..1 boolean "short boolean"
* stuff 0..* string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
`);
const result = importSingleText(input, 'BadPath.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/no viable alternative at input.*File: BadPath\.fsh.*Line: 3\D*/s
);
// Error results in excluding the rule with the error, hence length of 3 rather than 4
expect(resource.rules).toHaveLength(3);
});
it('should log an error for missing cardinality', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "short boolean"
* stuff string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
`);
const result = importSingleText(input, 'BadCard.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input 'string' expecting {.*}.*File: BadCard\.fsh.*Line: 4\D*/s
);
// Error results in excluding the rule with the error and subsequent rules,
// hence length of 1 rather than 4
expect(resource.rules).toHaveLength(1);
});
it('should log an error when min cardinality is not specified', () => {
const input = leftAlign(`
Logical: LogicalModel
* isInValid ..* string "short string"
`);
const result = importSingleText(input, 'Invalid.fsh');
const logical = result.logicals.get('LogicalModel');
expect(logical.rules).toHaveLength(1);
assertAddElementRule(logical.rules[0], 'isInValid', {
card: { min: NaN, max: '*' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'min' cardinality attribute in AddElementRule/s
);
});
it('should log an error when max cardinality is not specified', () => {
const input = leftAlign(`
Logical: LogicalModel
* isInValid 0.. string "short string"
`);
const result = importSingleText(input, 'Invalid.fsh');
const logical = result.logicals.get('LogicalModel');
expect(logical.rules).toHaveLength(1);
assertAddElementRule(logical.rules[0], 'isInValid', {
card: { min: 0, max: '' },
types: [{ type: 'string' }],
defs: { short: 'short string', definition: 'short string' }
});
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'max' cardinality attribute in AddElementRule/s
);
});
it('should log an error for extra docs/strings', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff" "invalid additional string"
* address 1..* N Address "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadDocs.fsh)');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadDocs\.fsh.*Line: 4\D*/s
);
// Error results in excluding the following rules, hence length of 2 rather than 4
expect(resource.rules).toHaveLength(2);
});
it('should log an error for missing short', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean
* stuff 0..* string "short string"
* address 1..* Address "short Address"
* person 0..1 Reference(Patient) "short Reference"
`);
const result = importSingleText(input, 'BadDefs.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/The 'short' attribute in AddElementRule for path 'isValid' must be specified.*File: BadDefs\.fsh.*Line: 3\D*/s
);
// Error results in element not having defs defined
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }]
});
});
it('should log an error for missing targetType with docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff"
* address 1..* "current addresses" "at least one address is required"
* person 0..1 Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadType\.fsh.*Line: 5\D*/s
);
// Error results in excluding the following rules, hence length of 3 rather than 5
expect(resource.rules).toHaveLength(3);
});
it('should log a warning for missing targetType with flags and docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS ?! boolean "is it valid?"
* stuff 0..* MS SU string "just stuff" "a list of some stuff"
* address 1..* N TU "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('warn')).toMatch(
/appears to be a flag value.*File: BadType\.fsh.*Line: 5\D*/s
);
expect(resource.rules).toHaveLength(4);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
flags: { mustSupport: true, modifier: true },
types: [{ type: 'boolean' }],
defs: { short: 'is it valid?' }
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
flags: { mustSupport: true, summary: true },
types: [{ type: 'string' }],
defs: { short: 'just stuff', definition: 'a list of some stuff' }
});
assertAddElementRule(resource.rules[2], 'address', {
card: { min: 1, max: '*' },
flags: { normative: true },
types: [{ type: 'TU' }],
defs: { short: 'current addresses', definition: 'at least one address is required' }
});
assertAddElementRule(resource.rules[3], 'person', {
card: { min: 0, max: '1' },
flags: { trialUse: true, draft: true },
types: [{ type: 'Patient', isReference: true }],
defs: { short: 'an associated patient', definition: 'added for TRIAL USE' }
});
});
it('should log a error for missing targetType with modifier flag and docs', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 MS ?! boolean "is it valid?"
* stuff 0..* MS SU string "just stuff" "a list of some stuff"
* address 1..* N ?! "current addresses" "at least one address is required"
* person 0..1 D TU Reference(Patient) "an associated patient" "added for TRIAL USE"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadType\.fsh.*Line: 5\D*/s
);
// The 'address' rule results in a CardRule and a FlagRule rather tha an AddElementRule.
// Due to the error, the 'person' rule is not processed.
expect(resource.rules).toHaveLength(4);
});
it('should parse rules according to rule patterns for CardRule and AddElementRule', () => {
const input = leftAlign(`
Resource: TestResource
* isValid 1..1 boolean "is it valid?"
* stuff 0..* string "just stuff" "a list of some stuff"
* address 1..* "current addresses" "at least one address is required"
* person 0..1 Reference(Patient) "an associated patient"
`);
const result = importSingleText(input, 'BadType.fsh');
const resource = result.resources.get('TestResource');
expect(loggerSpy.getLastMessage('error')).toMatch(
/extraneous input.*File: BadType\.fsh.*Line: 5\D*/s
);
expect(resource.rules).toHaveLength(3);
assertAddElementRule(resource.rules[0], 'isValid', {
card: { min: 1, max: '1' },
types: [{ type: 'boolean' }]
});
assertAddElementRule(resource.rules[1], 'stuff', {
card: { min: 0, max: '*' },
types: [{ type: 'string' }]
});
// There is no way to distinguish between a valid CardRule
// and an invalid AddElementRule with a missing targetType,
// so the CardRule wins.
assertCardRule(resource.rules[2], 'address', 1, '*');
// Due to the error, the 'person' rule is not processed.
});
});
});
});
|
<filename>src/store/orbit/actions.tsx
import {
FETCH_ORBIT_DATA,
ORBIT_ERROR,
ORBIT_RETRY,
IApiError,
RESET_ORBIT_ERROR,
ORBIT_SAVING,
FETCH_ORBIT_DATA_COMPLETE,
} from './types';
import Coordinator from '@orbit/coordinator';
import Auth from '../../auth/Auth';
import { Sources } from '../../Sources';
import { Severity } from '../../utils';
import { OfflineProject, Plan, VProject } from '../../model';
export const orbitError = (ex: IApiError) => {
return ex.response.status !== Severity.retry
? {
type: ORBIT_ERROR,
payload: ex,
}
: {
type: ORBIT_RETRY,
payload: ex,
};
};
export const orbitComplete = () => (dispatch: any) => {
dispatch({
type: FETCH_ORBIT_DATA_COMPLETE,
});
};
export const doOrbitError = (ex: IApiError) => (dispatch: any) => {
dispatch(orbitError(ex));
};
export const resetOrbitError = () => {
return {
type: RESET_ORBIT_ERROR,
};
};
export const orbitSaving = (val: boolean) => {
return {
type: ORBIT_SAVING,
payload: val,
};
};
export const fetchOrbitData = (
coordinator: Coordinator,
auth: Auth,
fingerprint: string,
setUser: (id: string) => void,
setProjectsLoaded: (value: string[]) => void,
setOrbitRetries: (r: number) => void,
setLang: (locale: string) => void,
global: any,
getOfflineProject: (plan: Plan | VProject | string) => OfflineProject
) => (dispatch: any) => {
Sources(
coordinator,
auth,
fingerprint,
setUser,
setProjectsLoaded,
(ex: IApiError) => dispatch(orbitError(ex)),
setOrbitRetries,
setLang,
global,
getOfflineProject
).then((fr) => {
dispatch({ type: FETCH_ORBIT_DATA, payload: fr });
});
};
|
<filename>console/src/gl/ATBar.cpp
/*
* gl/ATBar.cpp
*
* Copyright (C) 2016 MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#ifdef HAS_ANTTWEAKBAR
#include "gl/ATBar.h"
megamol::console::gl::ATBar::ATBar(const char* name) : atb(), barName(name), bar(nullptr) {
atb = atbInst::Instance();
bar = ::TwNewBar(name);
}
megamol::console::gl::ATBar::~ATBar() {
if (bar != nullptr) {
::TwDeleteBar(bar);
bar = nullptr;
}
}
#endif
|
On the foundations of system identification
Summary form only given. One philosophically coherent position is to view system (or process) identification as the search for a theory (or model) in a given class that minimizes a (loss) function of (1) the cumulative prediction errors incurred using a particular model and (2) a measure of the complexity of the model (such as the McMillan degree of a linear predictor). The resulting identification method is referred to as a minimum-predictor-error (MPE) method. An alternative starting point taken in the minimum-description-length (MDL) theory due to Rissanen is to view a process or predictor model as an encoding device and to choose the model (in a given class) that minimizes the total number of bits needed to describe (1) the model plus (2) the number of bits required to describe the observations when encoded using the model. An extension of this idea is contained in Rissanen's stochastic complexity (SC) measure of a process. The author has related the MPE, MDL, SC and classical maximum-likelihood approaches to system identification.<<ETX>> |
//! The client portion of `tower-hyper`.
//!
//! The client module contains three main utiliteies client, connection
//! and connect. Connection and Connect are designed to be used together
//! where as Client is a thicker client designed to be used by itself. There
//! is less control over driving the inner service compared to Connection. The
//! other difference is that Connection is a lowerlevel connection, so there is no
//! connection pooling etc, that is the job of the services that wrap it.
mod connect;
mod connection;
pub use self::connect::{Connect, ConnectError};
pub use self::connection::Connection;
pub use hyper::client::conn::Builder;
use futures::{Async, Poll};
use http::{Request, Response};
use hyper::{
body::Payload, client::connect::Connect as HyperConnect, client::ResponseFuture, Body,
};
use tower_service::Service;
/// The client wrapp for `hyper::Client`
///
/// The generics `C` and `B` are 1-1 with the generic
/// types within `hyper::Client`.
#[derive(Debug)]
pub struct Client<C, B> {
inner: hyper::Client<C, B>,
}
impl<C, B> Client<C, B> {
/// Create a new client from a `hyper::Client`
pub fn new(inner: hyper::Client<C, B>) -> Self {
Self { inner }
}
}
impl<C, B> Service<Request<B>> for Client<C, B>
where
C: HyperConnect + Sync + 'static,
C::Transport: 'static,
C::Future: 'static,
B: Payload + Send + 'static,
B::Data: Send,
{
type Response = Response<Body>;
type Error = hyper::Error;
type Future = ResponseFuture;
/// Poll to see if the service is ready, since `hyper::Client`
/// already handles this internally this will always return ready
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
/// Send the sepcficied request to the inner `hyper::Client`
fn call(&mut self, req: Request<B>) -> Self::Future {
self.inner.request(req)
}
}
|
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.io.*;
public class AI extends MIDlet
{
Display display;
MainCanvas mc;
public AI(){
display=Display.getDisplay(this);
mc=new MainCanvas();
display.setCurrent(mc);
}
public void startApp(){
}
public void destroyApp(boolean unc){
}
public void pauseApp(){
}
}
class MainCanvas extends Canvas
{
Image currentImg,img,img1,img2,img3,img4,img5;
int x = 120;
int y = 100;
int l = 0;
public MainCanvas(){
try{
img = Image.createImage("/sayo10.png");
img1 = Image.createImage("/sayo12.png");
img2 = Image.createImage("/sayo14.png");
img3 = Image.createImage("/sayo16.png");
img4 = Image.createImage("/sayo02.png");
img5 = Image.createImage("/sayo22.png");
currentImg = img;
}
catch(IOException e){
e.printStackTrace();
}
}
public void paint(Graphics g){
g.setColor(0,0,0);
g.fillRect(0,0,getWidth(),getHeight());
g.drawImage(currentImg,x,y,0);
}
public void keyPressed(int keyCode){
int action = getGameAction(keyCode);
if(action == DOWN){
currentImg = img;
System.out.println("turn down");
y += 1;
repaint();
}
if(action == LEFT){
currentImg = img1;
System.out.println("turn left");
x -= 10;
if(l == 0){
currentImg = img4;
l=1;
}else if(l == 1){
currentImg = img5;
l=0;
}
repaint();
}
if(action == UP){
currentImg = img2;
System.out.println("turn up");
y -= 1;
repaint();
}
if(action == RIGHT){
currentImg = img3;
System.out.println("turn right");
x += 1;
repaint();
}
}
} |
Dry (without mortar) stone work in the hands of a skilled waller is an art form. An art form that will last multiple lifetimes and serves multiple functions. Using but one tool; the hammer, and much patience and strength, a skilled waller can lay yards of fence per day. Most modern wallers do not like to shape stones but instead prefer to locate the perfect nature shaped stone. As their eyes have developed an acute sense of space, an experienced waller most times will only pick up a stone once, before positioning it.
38 Amazing Stone Walls Around The World
1) Stone Wall In Chilmark
Stone wall with picket gate in Chilmark, Martha’s Vineyard by Jeffrey Bale. www.jeffreygardens.com
2) Old World Stone & Garden Wall
Stone wall by Matt Sevigny from Old World Stone & Garden. Completed in 1999, this picture was taken 12 years later.
3) Contemporary Stone Wall
Contemporary stone wall in West Tisbury, Martha’s Vineyard by Jeffrey Bale.
4) Irish Dry Stone Wall
Dry stone wall, Ireland. Local residents are encouraged to erect and maintain stone walls. There are hundreds of thousands of miles of dry stone walls in Great Britain and Ireland, some date back to 3,500 BC. © Paul McIlroy.
5) Stone Retaining Wall
These owners used dry stacking to create a retaining wall with traditional style.
6) Rock Boundary In Ireland
Dry stone wall in Ireland. Due to centuries of farming and lifting rocks from the soil just about every boundary in Ireland has a stone wall.
7) Kellyburn Park Stone Wall
Stone wall, Kellyburn Park, Dollar, UK. This type of vertical capstone is typical in Ireland. By stoneinspired.com.
8) Stone Wall Fence
Dry stone wall surrounds a replica of a traditional blackhouse built by the DSWAC in Ontario, Canada. If you build a wide, double stone wall, you can fill the top with a little bit of soil for shallow rooted plants. If you let roots go deep into a wall, those roots will destroy the wall. More about this property can be found on Thinking With My Hands.
9) Rock Wall And Walkway
Stone wall in California by Jeffrey Bale. The swirling designs compliment the variations in the wall.
10) Stone Wall Art In British Columbia
Stone wall, 80 feet long x 4 feet high, British Columbia, Canada. This stunning masterpiece is one of many by Ancient Art Of Stone.
11) Canadian Dry Stack Wall
Must be nice and warm here on a sunny afternoon. A design by Ancient Art Of Stone in Canada, the wave pattern brings the wall to life.
12) Rock Wall With Basalt Stone
The bright color of these stones add vibrancy to the garden.
13) Stone Patio
Stone patio by Lew French. Lew was born in a small farming town in Minnesota. He started to work with stone when he was nineteen years old. He moved to Martha’s Vineyard over twenty years ago and has worked on his own stone designs exclusively since. www.lewfrenchstone.com
Close up of one of Lew’s walls. “Grout lines do not exist—his compositions do not rely on mortar, which is only used for safety.”
14) Dry Stock Wall With Pillars
Stone wall by Lew French. The adaption of small columns into the design gives the wall a fence-like structure.
15) Large Rock Wall Using Boulders
Large rock wall by Lew French. The large boulders draw attention to the intricacy of the walls design.
16) Rock Wall Shower
Detail of a rock wall shower surround. By Lew French.
17) Stone Wall With Shingles
Rock and shingle wall. Door opens to a garden. Lew French has a new book forthcoming. His first book, Stone by Design can be purchased on Amazon.
18) Dry Stone Wall With A Circular Design
Slate wall by Andy Goldsworthy. The contrast in the flow of the rocks causes the circle to be distinct.
19) Slate And Stone Wall
Slate and rock wall by Andy Goldsworthy.
20) Poolhouse Garden Retaining Wall
The larger stones in this wall give the garden a rustic style.
21) Vertically Laid Dry Stack Wall
Wall by Andy Goldsworthy in Bedford, NY. A vertically laid wall holds up an enormous boulder.
22) Stone River
Stone River, 2001 by Andy Goldsworthy. The wall is discussed in an article by the Cantor Arts Center at Stanford University, California.
23) Storm King Wall
Storm King Wall in Mountainville, New York built in 1997. A 2,278 foot snaking wall plunges into a pond but reemerges on the other side.
By Andy Goldsworthy.
24) Flower Of Stone
Dry stone wallflower. Using alternating layers of slate to create the petals and detail in the leaf.
25) Wave Wall
Wave Wall in Aptos California by Michael Eckerman. There must be some mortar behind there.
26) Wall Made From River Rocks
River rock wall. Santa Cruz Mountains. By Michael Eckerman.
27) Customized Stone Wall With Audio System
These designers were creative, adding a place for their audio system.
28) Kerry Landman Memorial
Dry stone wall with tree built by Eric Landman in memeory of his wife Kerry. Kerry Landman Memorial, Island Lake Conservation Area, Mono, Ontario. The main wall is Limestone with local rounded granite fieldstones that were found on site to represent the leaves. A lot of them had green moss on them that added to the effect of the stones looking like foliage.
29) Fun Dry Wall In Cèvennes
Wall in Cèvennes, France by Roland Mousquès, one of the founders of the Association Artisans Bâtisseurs en Pierre Sèche, France’s drywall association. Workshops: www.facebook.com & www.pierreseche.fr
30) Inca Stone Wall
The Inca were masterful stone wallers. The fittings are so tight that a knife cannot penetrate the cracks between the stones.
31) Moongate Stone Wall
Dry stone wall with moongate. Built by Carl Wright in his Garden at Caher Bridge, Co Clare.
32) Sloped Stone Retaining Wall
The wall gently slopes toward the hill, preventing the wall from collapsing.
33) Rock Wall Furnace
Incorporate a fireplace into your stone wall. Canadian waller Stephen Niven won a prize in 2009 with this dry stone fireplace. wallswithoutmortar.blogspot.com
34) Raised Stone Garden Bed
Stone raised bed. This garden bed is part of a farm in New Hampshire.
35) Dry Wall With Planter
Dry stone wall with integrated pot. Water draining off a slope can seep through the rocks, instead of causing pressure on a cemented wall. westphoria.sunset.com
36) Slab Wall With A Face
Incorporate a face, by Jerry Boyle. He likes adding faces because they give dimension to the design.
37) Rock Dry Stack Wall
https://www.instagram.com/p/BOAs3aDBGsG/
A slightly different type of slab was used as the capstone in this retaining wall.
38) Dry Stack Dandelion
Dry stone wall in dandelion design by George Weaver. This is one of many designs exhibited on the wallswithoutmortar.blogspot.com website.
Dry Stack Stone Wall Composition
For added stability dry stone walls are built wider at the bottom and taper toward the top. Image: outofoblivion.org.uk
Resources For Building A Stone Wall
Stonexus Magazine: Very inspiring!!!
Walls of Stone: Learn how to build dry stone walls and fences
Dry Stone Walling Association: Discover the technical specifications for dry stone walls
Stone Inspired: For dry stone wall inspiration |
A Rapid Technique Using Handheld Instrument for Mapping Corrosion of Steel in Reinforced Concrete / Eine Schnellmethode zur Bestimmung der örtlichen Verteilung der Korrosion des Stahles in bewehrtem Beton mit Hilfe eines Handgerätes
This paper presents a rapid technique using a handheld instrument for mapping corrosion of steel in reinforced concrete structures. The technique involves a short time galvanostatic pulse measurement followed with the numerical calculation of the effective polarization current from the measured ohmic and polarized potential responses, so as to be able to estimate the true values of ohmic and polarization resistances related to the confined area. Owing to its rapidity (in a few seconds per measurement), this technique provides a useful tool for mapping electrochemical characteristics of reinforcement steel in concrete structures, including half-cell potential, ohmic resistivity and corrosion rate. These three corrosion-related parameters supply better information to an inspector for condition assessment of reinforced concrete structures. The results from comparative measurements on both small and large reinforced concrete slabs show that the corrosion rate measured by the new developed rapid technique is quite comparable with that measured by the Spanish Gecor instrument, which uses the modulated confinement technique. The technique has been used in a number of real concrete structures. The results show that the corrosion extent measured by the new rapid technique is in reasonably good agreement with those by the other techniques and visual observations. |
<reponame>mjsil/app_fera_fut
import React, { createContext, FC } from 'react';
import { useLeague, DataLeagueProps, DataSeasonProps } from './hooks/useLeague';
import { useClassification } from './hooks/useClassification';
import { TeamCardProps } from '../components/TeamCard'
import { useTeam, DataTeamProps } from './hooks/useTeam';
interface ContextInterface {
leagues: Array<DataLeagueProps>;
selectedLeague: DataLeagueProps;
setSelectedLeague: (selectedLeague: DataLeagueProps) => void;
selectedSeason: DataSeasonProps;
setSelectedSeason: (selectedSeason: DataSeasonProps) => void;
isLoadingLeague: boolean;
classification: Array<TeamCardProps>;
isLoadingClassification: boolean;
leagueStandings: (league: number, season: number) => void;
selectedTeam: TeamCardProps;
setSelectedTeam: (selectedTeam: TeamCardProps) => void;
team: DataTeamProps;
isLoadingTeam: boolean;
teamInformation: (team: number) => void;
}
export const HootContext = createContext<ContextInterface | null>(null);
export const HootProvider: FC = ({ children }) => {
const {
leagues,
selectedLeague, setSelectedLeague,
selectedSeason, setSelectedSeason,
isLoadingLeague
} = useLeague();
const {
classification,
isLoadingClassification,
leagueStandings,
selectedTeam, setSelectedTeam
} = useClassification();
const {
team,
isLoadingTeam,
teamInformation
} = useTeam();
return (
<HootContext.Provider value={{
leagues,
selectedLeague, setSelectedLeague,
selectedSeason, setSelectedSeason,
isLoadingLeague,
classification,
isLoadingClassification,
leagueStandings,
selectedTeam, setSelectedTeam,
team,
isLoadingTeam,
teamInformation
}}>
{children}
</HootContext.Provider>
);
};
|
Not to be confused with Rumination (psychology)
Rumination syndrome A postprandial manometry of a patient with rumination syndrome showing intra-abdominal pressure. The "spikes" are characteristic of the abdominal wall contractions responsible for the regurgitation in rumination. Specialty Psychiatry
Rumination syndrome, or Merycism, is an under-diagnosed chronic motility disorder characterized by effortless regurgitation of most meals following consumption, due to the involuntary contraction of the muscles around the abdomen.[1] There is no retching, nausea, heartburn, odour, or abdominal pain associated with the regurgitation, as there is with typical vomiting. The disorder has been historically documented as affecting only infants, young children, and people with cognitive disabilities (the prevalence is as high as 10% in institutionalized patients with various mental disabilities). Today it is being diagnosed in increasing numbers of otherwise healthy adolescents and adults, though there is a lack of awareness of the condition by doctors, patients and the general public.
Rumination syndrome presents itself in a variety of ways, with especially high contrast existing between the presentation of the typical adult sufferer without a mental disability and the presentation of an infant and/or mentally impaired sufferer. Like related gastrointestinal disorders, rumination can adversely affect normal functioning and the social lives of individuals. It has been linked with depression.
Little comprehensive data regarding rumination syndrome in otherwise healthy individuals exists because most sufferers are private about their illness and are often misdiagnosed due to the number of symptoms and the clinical similarities between rumination syndrome and other disorders of the stomach and esophagus, such as gastroparesis and bulimia nervosa. These symptoms include the acid-induced erosion of the esophagus and enamel, halitosis, malnutrition, severe weight loss and an unquenchable appetite. Individuals may begin regurgitating within a minute following ingestion, and the full cycle of ingestion and regurgitation can mimic the binging and purging of bulimia.
Diagnosis of rumination syndrome is non-invasive and based on a history of the individual. Treatment is promising, with upwards of 85% of individuals responding positively to treatment, including infants and the mentally handicapped.
Signs and symptoms [ edit ]
While the number and severity of symptoms varies among individuals, repetitive regurgitation of undigested food (known as rumination) after the start of a meal is always present.[2][3] In some individuals, the regurgitation is small, occurring over a long period of time following ingestion, and can be rechewed and swallowed. In others, the amount can be bilious and short lasting, and must be expelled. While some only experience symptoms following some meals, most experience episodes following any ingestion, from a single bite to a large meal.[4] However, some long-term patients will find a select couple of food or drink items that do not trigger a response.
Unlike typical vomiting, the regurgitation is typically described as effortless and unforced.[2] There is seldom nausea preceding the expulsion, and the undigested food lacks the bitter taste and odour of stomach acid and bile.[2]
Symptoms can begin to manifest at any point from the ingestion of the meal to 120 minutes thereafter.[3] However, the more common range is between 30 seconds to 1 hour after the completion of a meal.[4] Symptoms tend to cease when the ruminated contents become acidic.[2][4]
Abdominal pain (38.1%), lack of fecal production or constipation (21.1%), nausea (17.0%), diarrhea (8.2%), bloating (4.1%), and dental decay (3.4%) are also described as common symptoms in day-to-day life.[3] These symptoms are not necessarily prevalent during regurgitation episodes, and can happen at any time. Weight loss is often observed (42.2%) at an average loss of 9.6 kilograms, and is more common in cases where the disorder has gone undiagnosed for a longer period of time,[3] though this may be expected of the nutrition deficiencies that often accompany the disorder as a consequence of its symptoms.[3] Depression has also been linked with rumination syndrome,[5] though its effects on rumination syndrome are unknown.[2]
Acid erosion of the teeth can be a feature of rumination,[6] as can halitosis (bad breath).[7]
Causes [ edit ]
The cause of rumination syndrome is unknown. However, studies have drawn a correlation between hypothesized causes and the history of patients with the disorder. In infants and the cognitively impaired, the disease has normally been attributed to over-stimulation and under-stimulation from parents and caregivers, causing the individual to seek self-gratification and self-stimulus due to the lack or abundance of external stimuli. The disorder has also commonly been attributed to a bout of illness, a period of stress in the individual's recent past, and to changes in medication.[2]
In adults and adolescents, hypothesized causes generally fall into one of either category: habit-induced, and trauma-induced. Habit-induced individuals generally have a history of bulimia nervosa or of intentional regurgitation (magicians and professional regurgitators, for example), which though initially self-induced, forms a subconscious habit that can continue to manifest itself outside the control of the affected individual. Trauma-induced individuals describe an emotional or physical injury (such as recent surgery, psychological distress, concussions, deaths in the family, etc.), which preceded the onset of rumination, often by several months.[2][3]
Pathophysiology [ edit ]
Rumination syndrome is a poorly understood disorder, and a number of theories have speculated the mechanisms that cause the regurgitation,[3] which is a unique symptom to this disorder. While no theory has gained a consensus, some are more notable and widely published than others.[2]
The most widely documented mechanism is that the ingestion of food causes gastric distention, which is followed by abdominal compression and the simultaneous relaxation of the lower esophageal sphincter (LES). This creates a common cavity between the stomach and the oropharynx that allows the partially digested material to return to the mouth. There are several offered explanations for the sudden relaxation of the LES.[8] Among these explanations is that it is a learned voluntary relaxation, which is common in those with or having had bulimia. While this relaxation may be voluntary, the overall process of rumination is still generally involuntary. Relaxation due to intra-abdominal pressure is another proposed explanation, which would make abdominal compression the primary mechanism. The third is an adaptation of the belch reflex, which is the most commonly described mechanism. The swallowing of air immediately prior to regurgitation causes the activation of the belching reflex that triggers the relaxation of the LES. Patients often describe a feeling similar to the onset of a belch preceding rumination.[2]
Diagnosis [ edit ]
Rumination syndrome is diagnosed based on a complete history of the individual. Costly and invasive studies such as gastroduodenal manometry and esophageal Ph testing are unnecessary and will often aid in misdiagnosis.[2] Based on typical observed features, several criteria have been suggested for diagnosing rumination syndrome.[3] The primary symptom, the regurgitation of recently ingested food, must be consistent, occurring for at least six weeks of the past twelve months. The regurgitation must begin within 30 minutes of the completion of a meal. Patients may either chew the regurgitated matter or expel it. The symptoms must stop within 90 minutes, or when the regurgitated matter becomes acidic. The symptoms must not be the result of a mechanical obstruction, and should not respond to the standard treatment for gastroesophageal reflux disease.[2]
In adults, the diagnosis is supported by the absence of classical or structural diseases of the gastrointestinal system. Supportive criteria include a regurgitant that does not taste sour or acidic,[8] is generally odourless, is effortless,[4] or at most preceded by a belching sensation,[2] that there is no retching preceding the regurgitation,[2] and that the act is not associated with nausea or heartburn.[2]
Patients visit an average of five physicians over 2.75 years before being correctly diagnosed with rumination syndrome.[9]
Differential diagnosis [ edit ]
Rumination syndrome in adults is a complicated disorder whose symptoms can mimic those of several other gastroesophogeal disorders and diseases. Bulimia nervosa and gastroparesis are especially prevalent among the misdiagnoses of rumination.[2]
Bulimia nervosa, among adults and especially adolescents, is by far the most common misdiagnosis patients will hear during their experiences with rumination syndrome. This is due to the similarities in symptoms to an outside observer—"vomiting" following food intake—which, in long-term patients, may include ingesting copious amounts to offset malnutrition, and a lack of willingness to expose their condition and its symptoms. While it has been suggested that there is a connection between rumination and bulimia,[9][10] unlike bulimia, rumination is not self-inflicted. Adults and adolescents with rumination syndrome are generally well aware of their gradually increasing malnutrition, but are unable to control the reflex. In contrast, those with bulimia intentionally induce vomiting, and seldom re-swallow food.[2]
Gastroparesis is another common misdiagnosis.[2] Like rumination syndrome, patients with gastroparesis often bring up food following the ingestion of a meal. Unlike rumination, gastroparesis causes vomiting (in contrast to regurgitation) of food, which is not being digested further, from the stomach. This vomiting occurs several hours after a meal is ingested, preceded by nausea and retching, and has the bitter or sour taste typical of vomit.[4]
Classification [ edit ]
Rumination syndrome is a condition which affects the functioning of the stomach and esophagus, also known as a functional gastroduodenal disorder.[11] In patients that have a history of eating disorders, Rumination syndrome is grouped alongside eating disorders such as bulimia and pica, which are themselves grouped under non-psychotic mental disorder. In most healthy adolescents and adults who have no mental disability, Rumination syndrome is considered a motility disorder instead of an eating disorder, because the patients tend to have had no control over its occurrence and have had no history of eating disorders.[12][13]
Treatment and prognosis [ edit ]
There is presently no known cure for rumination. Proton pump inhibitors and other medications have been used to little or no effect.[14] Treatment is different for infants and the mentally handicapped than for adults and adolescents of normal intelligence. Among infants and the mentally handicapped, behavioral and mild aversion training has been shown to cause improvement in most cases.[15] Aversion training involves associating the ruminating behavior with negative results, and rewarding good behavior and eating. Placing a sour or bitter taste on the tongue when the individual begins the movements or breathing patterns typical of his or her ruminating behavior is the generally accepted method for aversion training,[15] although some older studies advocate the use of pinching.[citation needed] In patients of normal intelligence, rumination is not an intentional behavior and is habitually reversed using diaphragmatic breathing to counter the urge to regurgitate.[14] Alongside reassurance, explanation and habit reversal, patients are shown how to breathe using their diaphragms prior to and during the normal rumination period.[14][16] A similar breathing pattern can be used to prevent normal vomiting. Breathing in this method works by physically preventing the abdominal contractions required to expel stomach contents.
Supportive therapy and diaphragmatic breathing has shown to cause improvement in 56% of cases, and total cessation of symptoms in an additional 30% in one study of 54 adolescent patients who were followed up 10 months after initial treatments.[3] Patients who successfully use the technique often notice an immediate change in health for the better.[14] Individuals who have had bulimia or who intentionally induced vomiting in the past have a reduced chance for improvement due to the reinforced behavior.[9][14] The technique is not used with infants or young children due to the complex timing and concentration required for it to be successful. Most infants grow out of the disorder within a year or with aversive training.[17]
Epidemiology [ edit ]
[3] Age distribution at diagnosis
Rumination disorder was initially documented[17][18] as affecting newborns,[13] infants, children[12] and individuals with mental and functional disabilities (the cognitively handicapped).[18][19] It has since been recognized to occur in both males and females of all ages and cognitive abilities.[2][20]
Among the cognitively handicapped, it is described with almost equal prevalence among infants (6–10% of the population) and institutionalized adults (8–10%).[2] In infants, it typically occurs within the first 3–12 months of age.[17]
The occurrence of rumination syndrome within the general population has not been defined.[11] Rumination is sometimes described as rare,[2] but has also been described as not rare, but rather rarely recognized.[21] The disorder has a female predominance.[11] The typical age of adolescent onset is 12.9, give or take 0.4 years (±), with males affected sooner than females (11.0 ± 0.8 for males versus 13.8 ± 0.5 for females).[3]
There is little evidence concerning the impact of hereditary influence in rumination syndrome.[8] However, case reports involving entire families with rumination exist.[22]
History [ edit ]
The term rumination is derived from the Latin word ruminare, which means to chew the cud.[22] First described in ancient times, and mentioned in the writings of Aristotle, rumination syndrome was clinically documented in 1618 by Italian anatomist Fabricus ab Aquapendende, who wrote of the symptoms in a patient of his.[20][22]
Among the earliest cases of rumination was that of a physician in the nineteenth century, Charles-Édouard Brown-Séquard, who acquired the condition as the result of experiments upon himself. As a way of evaluating and testing the acid response of the stomach to various foods, the doctor would swallow sponges tied to a string, then intentionally regurgitate them to analyze the contents. As a result of these experiments, the doctor eventually regurgitated his meals habitually by reflex.[23]
Numerous case reports exist from before the twentieth century, but were influenced greatly by the methods and thinking used in that time. By the early twentieth century, it was becoming increasingly evident that rumination presented itself in a variety of ways in response to a variety of conditions.[20] Although still considered a disorder of infancy and cognitive disability at that time, the difference in presentation between infants and adults was well established.[22]
Studies of rumination in otherwise healthy adults became decreasingly rare starting in the 1900s, and the majority of published reports analyzing the syndrome in mentally healthy patients appeared thereafter. At first, adult rumination was described and treated as a benign condition. It is now described as otherwise.[24] While the base of patients to examine has gradually increased as more and more people come forward with their symptoms, awareness of the condition by the medical community and the general public is still limited.[2][21][25][26]
In other animals [ edit ]
The chewing of cud by animals such as cows, goats, and giraffes is considered normal behavior. These animals are known as ruminants.[8] Such behavior, though termed rumination, is not related to human rumination syndrome, but is ordinary. Involuntary rumination, similar to what is seen in humans, has been described in gorillas and other primates.[27] Macropods such as kangaroos also regurgitate, re-masticate, and re-swallow food, but these behaviors are not essential to their normal digestive process, are not observed as predictably as the ruminants', and hence were termed "merycism" in contrast with "true rumination".[28]
See also [ edit ]
References [ edit ] |
// Create a function from a javascript string. The function will be cached
// unless you pass `true` for nocache. Caching allows the browser to optimize
// frequently called functions, but every cached function stays in memory
// forever, so it is not appropriate for iifes.
func MakeFunction(code string, nocache ...bool) js.Value {
useCache := len(nocache) == 0 || !nocache[0]
if useCache {
if existing, ok := funcRegistry.Load(code); ok {
return existing.(js.Value)
}
}
wrapped := fmt.Sprintf("(%s)", code)
fnValue := js.Global().Call("eval", wrapped)
if useCache {
funcRegistry.Store(code, fnValue)
}
return fnValue
} |
<reponame>lukasz-kozik/formaccount
package account
import "fmt"
type AccountRequest struct {
Account *Account `json:"data"`
}
type Page struct {
size int
number int
}
func (p *Page) Size(s int) *Page {
if s > 0 {
p.size = s
}
return p
}
func (p *Page) Number(n int) *Page {
if n > 0 {
p.number = n
}
return p
}
func (p *Page) String() string {
return fmt.Sprintf("?page[number]=%d&page[size]=%d", p.number, p.size)
}
|
import { ResourceManager } from '@travetto/base';
import { RootRegistry } from '@travetto/registry';
import { DBConfig } from './dbconfig';
export async function main() {
Object.assign(process.env, Object.fromEntries(
(await ResourceManager.read('env.properties', 'utf8'))
.split(/\n/g)
.map(x => x.split(/\s*=\s*/))));
await RootRegistry.init();
const { ConfigManager } = await import('@travetto/config');
await ConfigManager.reset();
await ConfigManager.init();
await ConfigManager.install(DBConfig, new DBConfig(), 'database');
console.log('Config', ConfigManager.toJSON());
} |
<gh_stars>10-100
{% raw %}
export * from './no-content';
{% endraw %} |
<reponame>sanyaade-teachings/VoiceBridge<filename>VoiceBridge/TestDll/TestDll/stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <algorithm>
#include <regex>
#include <unordered_map>
#include <thread>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/range/numeric.hpp>
namespace fs = boost::filesystem;
using string_vec = std::vector<std::string>; |
<gh_stars>0
# -*- coding: utf-8 -*-
"""Asignment 2 - Secondary Elastic Net CV-Coordinate descent.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1o6PXiGmn3MCE20Ir3h2hhIZGwo0u2KeJ
# **Assignment 2 Manual (From Scratch)**
- **Programmers:**
- <NAME>
- <NAME>
- **Date:** 11-8-2021
- **Assignment:** 2
- **Prof:** M.DeGiorgio
<hr>
### **Overview: Secondary - Assignment 2**
We analyzed the credit card data from N=400 training observations that you examined in Programming Assignment 1 using a penalized (regularized) least squares fit of a linear model using elastic net, with model parameters obtained by coordinate descent.
Initially, we each worked independently, then we collaborated afterwards to finalize the assignment deliverables. This resulted in the completion of 2 methods for achieving the same goal, namely implementing ElastNet with coordinate descent. This is the second take on assignment 2. The aim was to display different methods of achieving the same abstraction.
## **Import data**
"""
# Commented out IPython magic to ensure Python compatibility.
#Math libs
from math import sqrt
from scipy import stats
import os
# Data Science libs
import numpy as np
import pandas as pd
# Graphics libs
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
#Timers
!pip install pytictoc
from pytictoc import TicToc
"""## **Import Data**"""
# Import Data
df = pd.read_csv('/content/Credit_N400_p9.csv')
# Validate data import
df.head(3)
"""## **Data Pre Proccessing**"""
# Assign dummy variables to catigorical feature attributes
df = df.replace({'Male': 0, 'Female':1, 'No': 0, 'Yes': 1})
df.head(3)
# separate the predictors from the response
X = df.to_numpy()[:, :-1]
Y = df.to_numpy()[:, -1]
print('Convert dataframe to numpy array:', X.shape, Y.shape)
"""## **Set Global Variables**"""
# Set local variables
# 9-Tuning Parms
λ = [1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6]
# 6 learning & convergence rate
α = [0, 0.2, 0.4, 0.6, 0.8, 1]
# K-folds
k = 5
#Iterations
n_iters = 1000 # itterations
#log base of lambda
λ_log = np.log10(λ)
# Set verbose to True
verbose = True
# Set n x m matrix variable
X_p = X
# Set n vector variable
Y_p = Y
"""## **Instantiate Data**"""
# Randomize N x M and N data
def randomize_data(X_p, Y_p):
matrix = np.concatenate((X_p, Y_p[:, None]), 1)
np.random.shuffle(matrix)
return matrix[:, :-1], matrix[:, -1]
# Initilize random sample data
x, y = randomize_data(X_p, Y_p)
# Set Global variable for samples and number of X = N X M features
X1 = x.shape[0]
X2 = x.shape[1]
# Create a 𝛽 matrix to store the predictors
𝛽 = np.zeros([k, len(λ), len(α), X2])
# Store 5 K-fold cross validation results
CV = np.zeros([k, len(λ), len(α)])
# Compute the number of validation test samples and indices based on k-folds
test_x = X1 // k
test_i = list(range(0, X1, test_x))
if True:
print('Implemnting {} training of {} test validation samples for each 5-k CV fold.'.format(
X1 - test_x, test_x)
)
"""## **Implment Functions**"""
# Standardize X
def standardize(x, mean_x, std_x):
return (x - mean_x) / std_x
# Center response variables
def centerResponses(y, mean):
return y - mean
# predicit x
def predict(x):
x = standardize(x, mean_x, std_x)
return np.matmul(x, 𝛽x)
# Calculate MSE score
def score(x_test, y_test, 𝛽x):
ŷ = np.matmul(x_test, 𝛽x)
mse = np.mean((y_test - ŷ) ** 2)
return mse
"""### **Coordinate Descent Algortihm**"""
# implement Coordinate Descent
def coordinateDescent(x, y, 𝛽x, sum_sq, lamb, alpha):
for k in range(X2):
# RSS minus the k coefficient
RSS = y - np.matmul(x, 𝛽x) + (x[:, k] * 𝛽x[k])[:, None]
# Calualte the RSS Loss function
a_k = np.matmul(x[:, k].T, RSS)[0]
# update B_k
𝛽k = np.absolute(a_k) - lamb * (1 - alpha) / 2
𝛽k = 𝛽k if 𝛽k >= 0 else 0
𝛽x[k, 0] = np.sign(a_k) * 𝛽k / (sum_sq[k] + lamb * alpha)
return 𝛽x
"""### **Elastic Net - Cross Validation Algorithm**"""
for i_lambda, lamb in enumerate(λ): # loop through λ lambda
for i_alpha, alpha in enumerate(α): # loop through α
for i_fold, i_test in zip(range(k), test_i): # loop through folds
# Validates and trains the CV iteration based on the validation and training sets.
x_test = x[i_test:i_test + test_x]
x_train = np.delete(x, np.arange(i_test, i_test + test_x), axis = 0)
y_test = y[i_test:i_test + test_x]
y_train = np.delete(y, np.arange(i_test, i_test + test_x), axis = 0)
# Standardize x and center y 5 K-fold trianing and test data
mean_x, std_x = np.mean(x_train, 0), np.std(x_train, 0)
mean_res = np.mean(y_train)
# X training and test
x_train = standardize(x_train, mean_x, std_x)
x_test = standardize(x_test, mean_x, std_x)
# Y training and test
y_train = centerResponses(y_train, mean_res)[:, None]
y_test = centerResponses(y_test, mean_res)[:, None]
# compute b_k given this fold
sum_sq = np.sum(x_train ** 2, 0)
# initialize random Beta for this lambda and fold
𝛽x = np.random.uniform(low = -1, high = 1, size = (X2, 1))
# Iterate 1000 times through the beta values in Elastic Net algorithm
for iter in range(n_iters):
𝛽x = coordinateDescent(x_train, y_train, 𝛽x, sum_sq, lamb, alpha)
# Calulate MSE score for the model --
# TODO: issue with MSE calualtion
mse_score = score(x_test, y_test, 𝛽x)
# store the score with the tuning param combinations
CV[i_fold, i_lambda, i_alpha] = mse_score
# Store the coefficient vector
𝛽[i_fold, i_lambda, i_alpha] = 𝛽x[:, 0]
# Print out the mean CV MSE for lambda and alpha
if verbose:
print('lambda:{}; alpha:{}; CV MSE:{}'.format(lamb, alpha, np.mean(CV[:, i_lambda, i_alpha])))
"""### **Test bench for parameters**"""
print(sum_sq)
print(𝛽x)
print(mse_score)
"""### **Retrain data with optimal lambda and alpha**"""
#Retrain using all data with optimum lambda and alpha
#Calculate CV mean
cv_mean = np.mean(CV, 0)
# find the best lambda and alpha
best_λ_ind, best_alpha_index = np.where(cv_mean == np.amin(cv_mean))
best_λ = λ[best_λ_ind[0]]
best_alpha = α[best_alpha_index[0]]
# standardize features of x and center responses
mean_x, std_x = np.mean(x, 0), np.std(x, 0)
x = standardize(x, mean_x, std_x)
y = centerResponses(y, np.mean(y))[:, None]
# Compute the sum of squares for each feature on the entire dataset
sum_sq = np.sum(x ** 2, 0)
# initialize 𝛽x coefficients
𝛽x = np.random.uniform(low = -1, high = 1, size = (X2, 1))
# Run coordent decent algorithm for best MSE
for iter in range(n_iters):
𝛽x = coordinateDescent(x, y, 𝛽x, sum_sq, best_λ, best_alpha)
# print('Beta values updated test:',𝛽x)
"""### **Test lambda and alpha**
- Best lambda shouild be 1.0
- Best alpha should be 1
"""
print('Best lambda:=', best_λ)
print('Best alpha:=', best_alpha)
"""### **Output for Deliverable 1**"""
# For each alpha, the coefficient values are plotted over the five folds as a function of lambda.
sns.set_theme()
sns.set_style("darkgrid", {"grid.color": ".5", "grid.linestyle": ":" })
𝛽μ = np.mean(𝛽,0)
ŷ = df.columns
count = 0 # set itterator
t = TicToc() # measure time of convergance
# create instance of class
for i_alpha, alpha in enumerate(α):
count += 1
end_time = t.toc()
plt.figure()
plt.figure(figsize=(16, 10), dpi=70)
print('Tuning parameter converged at = #{c} λ {} at alpha{α}\n'.format(np.log10(λ), c=count, α=alpha))
for i_beta in range(𝛽μ.shape[1]):
plt.plot( np.log10(λ), 𝛽μ[:, i_alpha, i_beta], label = ŷ[i_beta])
plt.legend(bbox_to_anchor = (1.05, 1), loc = 'upper right', title = 'Features')
plt.xlabel('λ Tuning Params')
plt.ylabel('Coefficient Values')
plt.title('Alpha Value: {}'.format(alpha))
plt.show()
"""### **Output for Deliverable 2**"""
# Observe the CV MSE over values of lambda and alpha
plt.figure()
plt.figure(figsize=(16, 10), dpi=70)
for i_alpha, alpha in enumerate(α):
std_error = np.std(CV[..., i_alpha], 0) / np.sqrt(k)
plt.errorbar( np.log10(λ), np.mean(CV[..., i_alpha], 0), yerr = std_error,xuplims=True,label = str(alpha))
plt.xlabel('Log base lambda')
plt.ylabel('Cross Validation MSE')
plt.legend(title = 'α')
plt.show()
"""### **Output for Deliverable 3**"""
# lambda and alpha with lowest cv mse
print('Best lambda: {}; Best alpha: {}'.format(best_λ, best_alpha))
"""### **Output for Deliverable 4.1**"""
# Lasso Implentation
# Plot the coefficient vectors for optimal lambda given alpha = 0
# MSE cross valiadtion for alpha = 0
alpha0 = np.mean(CV[..., 0], 0)
# Get the index of lambda with lowest CV MSE
index = np.argmin(alpha0)
λx = λ[index]
# CV 5 K-fold mean vector coefficient for lambda and alpha
𝛽μ = np.mean(𝛽[:, index, 0, :], 0)
# Calulate and plot optimal lambda and alpha values
plt.figure()
plt.figure(figsize=(16, 10), dpi=70)
plt.scatter(𝛽x, 𝛽μ)
plt.plot(np.arange(-300, 475), np.arange(-300, 475), '--', color = 'g')
plt.xlabel('Elastic Net (lambda = {}, alpha = {})'.format(best_λ, best_alpha))
plt.ylabel('|L2|:= (lambda = {})'.format(λx))
plt.show()
####### Test #######
# print(alpha0)
# print(λ_i)
# print(𝛽μ )
"""### **Output for Deliverable 4.2**"""
# Ridge Implentation
# Plot the coefficient vectors for optimal lambda given alpha = 0
# get cv mse given alpha = 1
alpha1 = np.mean(CV[..., -1], 0)
# Get the index of lambda with lowest CV MSE
λ_i = np.argmin(alpha1)
λx = λ[λ_i]
# CV 5 K-fold mean vector coefficient for lambda and alpha
𝛽μ = np.mean(𝛽[:, λ_i, -1, :], 0)
# Calulate and plot optimal lambda and alpha values
plt.figure()
plt.figure(figsize=(16, 10), dpi=70)
plt.scatter(𝛽x, 𝛽μ)
plt.plot(np.arange(-300, 475), np.arange(-300, 475), '--', color = 'b')
plt.xlabel('Elastic Net (lambda = {}, alpha = {})'.format(best_λ, best_alpha))
plt.ylabel('L2 (lambda = {})'.format(λx))
plt.show()
####### Test #######
# print(alpha1)
# print(λ_i)
# print(𝛽μ )
"""# **Assignment 2 with ML libaries**
<hr>
"""
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import ElasticNetCV
from sklearn.exceptions import ConvergenceWarning
#from sklearn.utils._testing import ignore_warnings
import warnings
warnings.filterwarnings('ignore', category=ConvergenceWarning) # To filter out the Convergence warning
warnings.filterwarnings('ignore', category=UserWarning)
from sklearn.model_selection import train_test_split, cross_val_score, KFold, StratifiedKFold
from sklearn.model_selection import GridSearchCV
# Scaling LibrariesL
from sklearn.preprocessing import StandardScaler
# Import packages for Measuring Model Perormance
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.metrics import make_scorer
from itertools import product
# Target:
y= df['Balance'].to_numpy()
# Convert the Pandas dataframe to numpy ndarray for computational improvement
X = df.iloc[:,:-1]
X = X.to_numpy()
# Define my tuning parameter values 𝜆:
learning_rates_λ = [1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6]
# Define my L1 Ratio:
l1_ratio = [0, 1/5, 2/5, 3/5, 4/5, 1]
# Define our tunning rates
tuning_params = list(product(l1_ratio, learning_rates_λ))
tuning_params[:2]
# Create Standarizing ObjectPackages:
standardization = StandardScaler()
# Strandardize
n_observations = len(df)
variables = df.columns
# Standardize the Predictors (X)
Xst = standardization.fit_transform(X)
# Add a constanct to the predictor matrix
#Xst = np.column_stack((np.ones(n_observations),Xst))
# Save the original M and Std of the original data. Used for unstandardize
original_means = standardization.mean_
# we chanced standardization.std_ to standardization.var_**.5
originanal_stds = standardization.var_**.5
print("observations :", n_observations)
print("variables :", variables[:2])
print('original_means :', original_means)
print('originanal_stds :', originanal_stds)
# Center y not using a library:
y_Mean = y.mean(axis = 0) # Original y mean
y_Centered = y-y_Mean
print('Original y: ',y[:3])
print("mean of y :", y_Mean, "Std of y :", y.std(axis = 0))
print('Centered y: ',y_Centered[:3])
print("mean of y centered :", y_Centered.mean(axis = 0), "Std of y centered :", y_Centered.std(axis = 0))
print(y_Centered.shape)
#let's first split it into train and test part
X_train, X_out_sample, y_train, y_out_sample = train_test_split(Xst, y_Centered, test_size=0.30, random_state=101) # Training and testing split
# Print Data size
print ("Train dataset sample size: {}".format(len(X_train)))
print ("Test dataset sample size: {}".format(len(X_out_sample)))
from sklearn.linear_model import ElasticNet
L𝛽_per_λ=[] # set empty list
# Evaluate tuning parameters with Elastic Net penalty
for tuning_param in tuning_params:
Library_ElasticNet=ElasticNet(alpha=tuning_param[1] , l1_ratio= tuning_param[0], max_iter=5000, tol=0.01)
Library_ElasticNet.fit(X_train, y_train)
c = np.array(Library_ElasticNet.coef_)
c = np.append(tuning_param[1],c)
c = np.append(tuning_param[0],c)
L𝛽_per_λ.append(c)
TunnedL𝛽_df=pd.DataFrame(L𝛽_per_λ)
TunnedL𝛽_df.columns=['Alpha', 'Lamba','Income', 'Limit', 'Rating', 'Cards', 'Age', 'Education', 'Gender', 'Student', 'Married']
TunnedL𝛽_df.head()
"""## **Deliverable 6.1** <a class="anchor" id="Deliverable_6.1"></a>
<h>
> Illustrate the effect of the tuning parameter on the inferred elastic net regression coefficients by generating six plots (one for each 𝛼 value) of nine lines (one for each of the 𝑝=9 features), with the 𝑦-axis as 𝛽̂
𝑗, 𝑗=1,2,…,9, and the 𝑥-axis the corresponding log-scaled tuning parameter value log10(𝜆) that generated the particular 𝛽̂
𝑗.
"""
plt.figure(figsize=(30,30))
plt.subplot(4, 2, 1)
plt.plot(TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0)].iloc[:,1:2],TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0)].iloc[:,2:])
plt.title('Effect of tunning on Coefficients alpha = 0')
plt.ylabel('Standardize Coefficients')
plt.xscale('log')
plt.legend(loc='best')
plt.legend(TunnedL𝛽_df.columns[2:])
plt.subplot(4, 2, 2)
plt.plot(TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.2)].iloc[:,1:2],TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.2)].iloc[:,2:])
plt.title('Effect of tunning on Coefficients alpha = 0.2')
plt.xscale('log')
plt.legend(loc='best')
plt.legend(TunnedL𝛽_df.columns[2:])
plt.subplot(4, 2, 3)
plt.plot(TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.4)].iloc[:,1:2],TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.4)].iloc[:,2:])
plt.title('Effect of tunning on Coefficients alpha = 0.4')
plt.ylabel('Standardize Coefficients')
plt.xscale('log')
plt.legend(loc='best')
plt.legend(TunnedL𝛽_df.columns[2:])
plt.subplot(4, 2, 4)
plt.plot(TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.6)].iloc[:,1:2],TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.6)].iloc[:,2:])
plt.title('Effect of tunning on Coefficients alpha = 0.6')
plt.xscale('log')
plt.legend(loc='best')
plt.legend(TunnedL𝛽_df.columns[2:])
plt.subplot(4, 2, 5)
plt.plot(TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.8)].iloc[:,1:2],TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(0.8)].iloc[:,2:])
plt.title('Effect of tunning on Coefficients alpha = 0.8')
plt.xlabel('Learning Rates λ')
plt.ylabel('Standardize Coefficients')
plt.xscale('log')
plt.legend(loc='best')
plt.legend(TunnedL𝛽_df.columns[2:])
plt.subplot(4, 2, 6)
plt.plot(TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(1)].iloc[:,1:2],TunnedL𝛽_df[TunnedL𝛽_df.Alpha.eq(1)].iloc[:,2:])
plt.title('Effect of tunning on Coefficients alpha = 1')
plt.xlabel('Learning Rates λ')
plt.xscale('log')
plt.legend(loc='best')
plt.legend(TunnedL𝛽_df.columns[2:])
"""# **Deliverable 6.2** <a class="anchor" id="Deliverable_6.2"></a>
Illustrate the effect of the tuning parameters on the cross validation error by generating a plot of six lines (one for each l1_ratio value) with the y-axis as
CV(5) error, and the x-axis the corresponding log-scaled tuning parameter value log10(λ) that generated the particular CV(5) error
"""
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import ElasticNet
#Define the model
Library_ElasticNet = ElasticNet()
# Create the Kfold:
cv_iterator = KFold(n_splits = 5, shuffle=True, random_state=101)
cv_score = cross_val_score(Library_ElasticNet, Xst, y_Centered, cv=cv_iterator, scoring='neg_mean_squared_error', n_jobs=1)
#print (cv_score)
#print ('Cv score: mean %0.3f std %0.3f' % (np.mean(np.abs(cv_score)), np.std(cv_score)))
# define grid
Parm_grid = dict()
Parm_grid['alpha'] = learning_rates_λ
Parm_grid['l1_ratio'] = l1_ratio
# Lets define search
GsearchCV = GridSearchCV(estimator = Library_ElasticNet, param_grid = Parm_grid, scoring = 'neg_mean_absolute_error', n_jobs=1, refit=True, cv=cv_iterator)
GsearchCV.fit(Xst, y_Centered)
GCV_df = pd.concat([pd.DataFrame(GsearchCV.cv_results_["params"]),pd.DataFrame(GsearchCV.cv_results_["mean_test_score"], columns=["mean_test_score"])],axis=1)
#GCV_df.index=GCV_df['alpha']
GCV_df[:3]
plt.figure(figsize=(25/2.54,15/2.54))
plt.plot( GCV_df[GCV_df.l1_ratio.eq(0)]["alpha"] , np.absolute( GCV_df[GCV_df.l1_ratio.eq(0)]["mean_test_score"] ), label='Avg_MSE_T alpha = 0')
plt.plot( GCV_df[GCV_df.l1_ratio.eq(0.2)]["alpha"] , np.absolute( GCV_df[GCV_df.l1_ratio.eq(0.2)]["mean_test_score"]), label='Avg_MSE_T alpha = 0.2')
plt.plot( GCV_df[GCV_df.l1_ratio.eq(0.4)]["alpha"] , np.absolute( GCV_df[GCV_df.l1_ratio.eq(0.4)]["mean_test_score"]), label='Avg_MSE_T alpha = 0.4')
plt.plot( GCV_df[GCV_df.l1_ratio.eq(0.6)]["alpha"] , np.absolute( GCV_df[GCV_df.l1_ratio.eq(0.6)]["mean_test_score"]), label='Avg_MSE_T alpha = 0.6')
plt.plot( GCV_df[GCV_df.l1_ratio.eq(0.8)]["alpha"] , np.absolute( GCV_df[GCV_df.l1_ratio.eq(0.8)]["mean_test_score"]), label='Avg_MSE_T alpha = 0.8')
plt.plot( GCV_df[GCV_df.l1_ratio.eq(1)]["alpha"] , np.absolute( GCV_df[GCV_df.l1_ratio.eq(1)]["mean_test_score"]), label='Avg_MSE_T alpha = 1')
plt.title('Effect of tunning on Coefficients')
plt.xlabel('Learning Rates λ')
plt.ylabel('Cross Validation MSE')
plt.xscale('log')
plt.legend(loc=0)
plt.show()
"""# **Deliverable 6.3** <a class="anchor" id="Deliverable_6.3"></a>
Indicate the value of 𝜆 that generated the smallest CV(5) error
**Smallest CV with Library**
"""
print ('Best: ',GsearchCV.best_params_)
print ('Best CV mean squared error: %0.3f' % np.abs(GsearchCV.best_score_))
GCV_df.sort_values(by=['mean_test_score'], ascending=False)[:1]
# Alternative: sklearn.linear_model.ElasticNetCV
from sklearn.linear_model import ElasticNetCV
auto_EN = ElasticNetCV(alphas=learning_rates_λ, l1_ratio = l1_ratio, normalize=False, n_jobs=1, cv=cv_iterator)
auto_EN.fit(Xst, y_Centered)
print ('Best alpha: %0.5f' % auto_EN.alpha_)
print ('Best L1 ratio: %0.5f' % auto_EN.l1_ratio_)
"""# **Deliverable 6.4** <a class="anchor" id="Deliverable_6.4"></a>
Given the optimal 𝜆, retrain your model on the entire dataset of 𝑁=400 observations and provide the estimates of the 𝑝=9 best-fit model parameters.
**Tunned with best alpha with Library**
"""
Library_ElasticNet_best=ElasticNet(alpha=GsearchCV.best_params_['alpha'] , l1_ratio= GsearchCV.best_params_['l1_ratio'], max_iter=1000, tol=0.1)
Library_ElasticNet_best.fit( Xst, y_Centered )
y_predM_best = Library_ElasticNet_best.predict(X_out_sample)
print ("Betas= ", Library_ElasticNet_best.coef_)
print("MSE = ",mean_squared_error(y_out_sample, y_predM_best))
print('R^2 Test', r2_score(y_out_sample, y_predM_best))
"""**lasso (𝛼=0 under optimal 𝜆 for 𝛼 =0)**"""
Library_ElasticNet_best=ElasticNet(alpha=GsearchCV.best_params_['alpha'] , l1_ratio= 0, max_iter=1000, tol=0.1)
Library_ElasticNet_best.fit( Xst, y_Centered )
y_predM_best = Library_ElasticNet_best.predict(X_out_sample)
print ("Betas= ", Library_ElasticNet_best.coef_)
print("MSE = ",mean_squared_error(y_out_sample, y_predM_best))
print('R^2 Test', r2_score(y_out_sample, y_predM_best))
"""**ridge regression (𝛼=1 under optimal 𝜆 for 𝛼=1)**"""
Library_ElasticNet_best=ElasticNet(alpha=GsearchCV.best_params_['alpha'] , l1_ratio= 1, max_iter=1000, tol=0.1)
Library_ElasticNet_best.fit( Xst, y_Centered )
y_predM_best = Library_ElasticNet_best.predict(X_out_sample)
print ("Betas= ", Library_ElasticNet_best.coef_)
print("MSE = ",mean_squared_error(y_out_sample, y_predM_best))
print('R^2 Test', r2_score(y_out_sample, y_predM_best))
"""Comapring the modeles with the optimal alpha (λ) and replacing the l1ratio (α) between 0 (lasso) and 1 (ridge) we are able to see that our model is more of a ridge model. Which is validated by the best_score_ (l1 ratio) from our CV Gridserach. The coefficient that is highly optimize is the Rating feature. Which is telling as balance, risk, and credit is highly correlated to this feature."""
|
WASHINGTON — A scientist with the Interior Department says he was reassigned to an unrelated accounting position because of his work on climate change — part of the Trump administration’s efforts to silence such efforts.
In an op-ed Wednesday in the Washington Post, Joel Clement wrote that he went from director of the department’s Office of Policy Analysis — where, among other responsibilities, he detailed the effects of global warming on Alaska’s native communities — to a senior adviser at an office that, as he describes it, “collects royalty checks from fossil fuel companies.”
“I am a scientist, a policy expert, a civil servant and a worried citizen,” the seven-year Interior employee wrote. “Reluctantly, as of today, I am also a whistleblower on an administration that chooses silence over science.”
Last month, Clement and dozens of other senior staff at Interior were reassigned as part of a sweeping reorganization. At the time, an Interior spokesperson told the Washington Post the moves would “better serve the taxpayer and the department’s operations.”
Questioned about the reassignments at a June 21 budget hearing, department secretary Ryan Zinke said they were “far from unprecedented” and involved “shifting people to either the area where their skills are better suited or getting people out of headquarters” and into “the field.”
Clement, however, says the administration “sidelined” him in hopes he would quit.
“I believe I was retaliated against for speaking out publicly about the dangers that climate change poses to Alaska Native communities,” he wrote in his op-ed. “During the months preceding my reassignment, I raised the issue with White House officials, senior Interior officials and the international community, most recently at a U.N. conference in June. It is clear to me that the administration was so uncomfortable with this work, and my disclosures, that I was reassigned with the intent to coerce me into leaving the federal government.”
In 2013, Clement co-authored a lengthy report for former President Barack Obama detailing the “rapid, sustained” changes happening in the Arctic.
“The effects of continued climate change are seen throughout the U.S. Arctic,” the report said. “Scientific observations and traditional knowledge suggest that this region is moving toward conditions never before witnessed.”
He has stacked his Cabinet with industry lobbyists and climate change skeptics, vowed to revive America’s dying coal industry, increase oil and gas production, and open up now-protected areas of the Arctic and Atlantic oceans to drilling. He also has proposed sweeping cuts to scientific agencies.
Trump’s 2018 budget request would slash funding at the Interior Department by $1.6 billion — to $11.7 billion — and support just shy of 60,000 full-time staff, a reduction of roughly 4,000.
Clement has filed a complaint with the U.S. Office of Special Counsel about his job switch, he said in his article. By reassigning him and leaving his former position vacant, the administration will “exacerbate the already significant threat to the health and the safety of certain Alaska Native communities,” he wrote.
“Removing a civil servant from his area of expertise and putting him in a job where he’s not needed and his experience is not relevant is a colossal waste of taxpayer dollars. Much more distressing, though, is what this charade means for American livelihoods,” he wrote.
“Putting citizens in harm’s way isn’t the president’s right. Silencing civil servants, stifling science, squandering taxpayer money and spurning communities in the face of imminent danger have never made America great.”
The Interior Department did not respond to HuffPost’s request for comment.
Clement’s op-ed comes a few months after an EPA scientist in Cincinnati wrote to the New York Times about how he felt working under Washington-based Administrator Scott Pruitt.
Saying Pruitt’s “role it is to dismantle the agency that he leads, Michael Kravitz wrote, “I walk among my colleagues like a zombie in a bad dream; they also seem dazed.” |
/**
* @internal
* Check if an IPv4 address is valid
*
* Defined in Profinet 2.4, section 4.3.1.4.21.2
*
* @param netmask In: Netmask
* @param netmask In: IP address
* @return 0 if the IP address is valid
* -1 if the IP address is invalid
*/
bool pf_cmina_is_ipaddress_valid (os_ipaddr_t netmask, os_ipaddr_t ip)
{
uint32_t host_part = ip & ~netmask;
if ((netmask == 0) && (ip == 0))
{
return true;
}
if (!pf_cmina_is_netmask_valid (netmask))
{
return false;
}
if ((host_part == 0) || (host_part == ~netmask))
{
return false;
}
if (ip <= OS_MAKEU32 (0, 255, 255, 255))
{
return false;
}
else if (
(ip >= OS_MAKEU32 (127, 0, 0, 0)) &&
(ip <= OS_MAKEU32 (127, 255, 255, 255)))
{
return false;
}
else if (
(ip >= OS_MAKEU32 (224, 0, 0, 0)) &&
(ip <= OS_MAKEU32 (239, 255, 255, 255)))
{
return false;
}
else if (
(ip >= OS_MAKEU32 (240, 0, 0, 0)) &&
(ip <= OS_MAKEU32 (255, 255, 255, 255)))
{
return false;
}
return true;
} |
Lea Michele issued a statement via her reps Tuesday after the coroner announced her boyfriend Cory Monteith died of a mixture of heroin and alcohol.
“Lea is deeply grateful for all the love and support she s received from family, friends, and fans. Since Cory s passing, Lea has been grieving alongside his family and making appropriate arrangements with them,” reads the statement, obtained by PEOPLE exclusively.
“They are supporting each other as they endure this profound loss together. We continue to ask the media to respect the privacy of Lea and Cory s family.
Monteith, 31, whose body was found in a Vancouver hotel room over the weekend, died in what the coroner called a “most-tragic accident.”
The two stars of Glee dated for more than a year, and Michele, 26, stood by his side when he voluntarily entered a month-long treatment program for substance addiction. They reunited after he was released.
PHOTOS: Cory & Lea: Their Love Story
RELATED: Lea Michele Seeks Privacy at This Time
RELATED: A Shocked Hollywood Reacts to Cory Monteith’s Death
EARLIER: Cory Monteith, 31, Found Dead in Hotel Room
FLASHBACK: Watch His Glee Audition Tape
Cory Monteith’s 11 Best Glee Performances |
#include"lp/Token.h"
using namespace lp;
Token::Token(const std::string& str): str(str)
{
type = checkTokenType(str);
}
Token::Token(const std::string& str, TokenType type): str(str), type(type){}
static bool isDigits(const std::string& str)
{
for(int i = 0; i < str.size(); i++)
{
char c = str[i];
if(!('0' <= c && c <= '9'))
return false;
}
}
static bool isNumerical(const std::string& str)
{
if(str.size() == 0)
return 0;
return isDigits(str) || (str[0] == '-' && str.size() > 1 && isDigits(str.substr(2, -1)));
}
TokenType Token::checkTokenType(const std::string& str)
{
if(str == ";")
return SEMICOLON;
else if(isNumerical(str))
return CONST;
else if(str[0] == '\"')
return STRING_LITERAL;
else if(str == "if" || str == "while" || str == "return")
return CONTROL;
else if(str == "(" || str == "{" || str == "[")
return BRACKET;
else if(str == ")" || str == "}" || str == "]")
return BRACKET_CLOSE;
else if(str == "=" || str == "+" || str == "-" || str == "*" || str == "/" || str == "&" || str == "|" || str == "&&" || str == "||" || str == "==" || str == "!=")
return OPERATOR;
else return VALIABLE;
}
std::ostream& operator <<(std::ostream& ost, lp::Token const & tok)
{
return ost << tok.Str();
} |
<gh_stars>0
/*
* _ __ _
* | |/ /__ __ __ _ _ __ | |_ _ _ _ __ ___
* | ' / \ \ / // _` || '_ \ | __|| | | || '_ ` _ \
* | . \ \ V /| (_| || | | || |_ | |_| || | | | | |
* |_|\_\ \_/ \__,_||_| |_| \__| \__,_||_| |_| |_|
*
* Copyright (C) 2018 IntellectualSites
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.kvantum.server.api.core;
import lombok.NonNull;
import xyz.kvantum.server.api.exceptions.KvantumException;
/**
* Use this class to manage the {@link Kvantum} instances
*/
public final class ServerImplementation
{
private static Kvantum intellectualServer;
/**
* Register the server implementation used in the application instance Cannot be used if the instance is already
* registered, use {@link #getImplementation()} to check for null.
*
* @param intellectualServer Server instance
* @throws KvantumException if the instance is already set
*/
public static void registerServerImplementation(@NonNull final Kvantum intellectualServer)
{
if ( ServerImplementation.intellectualServer != null )
{
throw new KvantumException( "Trying to replace server implementation" );
}
ServerImplementation.intellectualServer = intellectualServer;
}
/**
* Get the registered implementation
*
* @return Implementation or mull
*/
public static Kvantum getImplementation()
{
return intellectualServer;
}
/**
* Check if an implementation has been registered
*
* @return True if an implementation has been registered
*/
public static boolean hasImplementation()
{
return getImplementation() != null;
}
}
|
<reponame>Magic-Services-Account/github1s
/**
* @file github authentication page
* @author netcon
*/
import { Barrier } from '@/helpers/async';
import { getExtensionContext } from '@/helpers/context';
import * as vscode from 'vscode';
import { GitHubTokenManager } from './token';
import { createPageHtml, getWebviewOptions } from '@/helpers/page';
import { messageApiMap } from './settings';
export class GitHub1sAuthenticationView {
private static instance: GitHub1sAuthenticationView | null = null;
public static viewType = 'github1s.views.github1s-authentication';
private webviewPanel: vscode.WebviewPanel | null = null;
// using for waiting token
private tokenBarrier: Barrier | null = null;
// using for displaying open page reason
private notice: string = '';
private constructor() {}
public static getInstance(): GitHub1sAuthenticationView {
if (GitHub1sAuthenticationView.instance) {
return GitHub1sAuthenticationView.instance;
}
return (GitHub1sAuthenticationView.instance = new GitHub1sAuthenticationView());
}
private registerListeners() {
if (!this.webviewPanel) {
throw new Error('webview is not inited yet');
}
const tokenManager = GitHubTokenManager.getInstance();
this.webviewPanel.webview.onDidReceiveMessage((message) => {
const commonResponse = { id: message.id, type: message.type };
const postMessage = (data?: unknown) => this.webviewPanel!.webview.postMessage({ ...commonResponse, data });
switch (message.type) {
case 'get-notice':
postMessage(this.notice);
break;
case 'get-token':
postMessage(tokenManager.getToken());
break;
case 'set-token':
message.data && (this.notice = '');
tokenManager.setToken(message.data || '').then(() => postMessage());
break;
case 'validate-token':
tokenManager.validateToken(message.data).then((tokenStatus) => postMessage(tokenStatus));
break;
case 'connect-to-github':
vscode.commands.executeCommand('github1s.commands.vscode.connectToGitHub').then((data: any) => {
if (data && data.error_description) {
vscode.window.showErrorMessage(data.error_description);
} else if (data && data.access_token) {
tokenManager.setToken(data.access_token || '').then(() => postMessage());
}
postMessage();
});
break;
case 'call-vscode-message-api':
const messageApi = messageApiMap[message.data?.level];
messageApi && messageApi(...message.data?.args).then((response) => postMessage(response));
break;
}
});
tokenManager.onDidChangeToken((token) => {
this.tokenBarrier && this.tokenBarrier.open();
this.tokenBarrier && (this.tokenBarrier = null);
this.webviewPanel?.webview.postMessage({ type: 'token-changed', token });
});
}
public open(notice: string = '', withBarriar = false) {
const extensionContext = getExtensionContext();
this.notice = notice;
withBarriar && !this.tokenBarrier && (this.tokenBarrier = new Barrier(600 * 1000));
if (!this.webviewPanel) {
this.webviewPanel = vscode.window.createWebviewPanel(
GitHub1sAuthenticationView.viewType,
'Authenticating to GitHub',
vscode.ViewColumn.One,
getWebviewOptions(extensionContext.extensionUri)
);
this.registerListeners();
this.webviewPanel.onDidDispose(() => (this.webviewPanel = null));
}
const styles = [
vscode.Uri.joinPath(extensionContext.extensionUri, 'assets/pages/components.css').toString(),
vscode.Uri.joinPath(extensionContext.extensionUri, 'assets/pages/github1s-authentication.css').toString(),
];
const scripts = [
vscode.Uri.joinPath(extensionContext.extensionUri, 'assets/pages/github1s-authentication.js').toString(),
];
const webview = this.webviewPanel.webview;
webview.html = createPageHtml('Authenticating To GitHub', styles, scripts);
return withBarriar ? this.tokenBarrier!.wait() : Promise.resolve();
}
}
|
/// Tests that shutting down a stream restores flow control for unsent data.
fn stream_shutdown_write_unsent_tx_cap() {
let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
config
.load_cert_chain_from_pem_file("examples/cert.crt")
.unwrap();
config
.load_priv_key_from_pem_file("examples/cert.key")
.unwrap();
config
.set_application_protos(b"\x06proto1\x06proto2")
.unwrap();
config.set_initial_max_data(15);
config.set_initial_max_stream_data_bidi_local(30);
config.set_initial_max_stream_data_bidi_remote(30);
config.set_initial_max_stream_data_uni(30);
config.set_initial_max_streams_bidi(3);
config.set_initial_max_streams_uni(0);
config.verify_peer(false);
let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
assert_eq!(pipe.handshake(), Ok(()));
// Client sends some data.
assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
assert_eq!(pipe.advance(), Ok(()));
let mut r = pipe.server.readable();
assert_eq!(r.next(), Some(4));
assert_eq!(r.next(), None);
let mut b = [0; 15];
assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
// Server sends some data.
assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
assert_eq!(pipe.advance(), Ok(()));
// Server buffers some data, until send capacity limit reached.
assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
assert_eq!(
pipe.server.stream_send(4, b"hello", false),
Err(Error::Done)
);
assert_eq!(
pipe.server.stream_send(8, b"hello", false),
Err(Error::Done)
);
// Client shouldn't update flow control.
assert_eq!(pipe.client.should_update_max_data(), false);
// Server shuts down stream.
assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Write, 42), Ok(()));
assert_eq!(pipe.advance(), Ok(()));
// Server can now send more data (on a different stream).
assert_eq!(pipe.client.stream_send(8, b"hello", true), Ok(5));
assert_eq!(pipe.advance(), Ok(()));
assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
assert_eq!(
pipe.server.stream_send(8, b"hello", false),
Err(Error::Done)
);
assert_eq!(pipe.advance(), Ok(()));
} |
<filename>src/interfaces/BlogPost.ts
export interface BlogPost {
url: string;
coverImageUrl: string;
title: string;
description: string;
dateAdded?: Date;
dateEdited?: Date;
tags: string[];
}
|
// This class represents a // directed graph using adjacency list // representation
class Graph_Problem_05 {
// No. of vertices
private final int V;
// Adjacency List Representation
private final LinkedList<Integer>[] adj;
// Constructor
Graph_Problem_05(int v) {
V = v;
adj = new LinkedList[v];
for(int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v,int w) {
adj[v].add(w);
adj[w].add(v);
}
// A recursive function that uses visited[] and parent to detect cycle in subgraph reachable from vertex v.
Boolean isCyclicUtil(int v, Boolean[] visited, int parent) {
// Mark the current node as visited
visited[v] = true;
Integer i;
// Recur for all the vertices adjacent to this vertex
for (Integer integer : adj[v]) {
i = integer;
// If an adjacent is not visited, then recur for that adjacent
if (!visited[i]) {
if (isCyclicUtil(i, visited, v))
return true;
}
// If an adjacent is visited and not parent of current vertex, then there is a cycle.
else if (i != parent)
return true;
}
return false;
}
// Returns true if the graph contains a cycle, else false.
Boolean isCyclic() {
// Mark all the vertices as not visited and not part of recursion stack
Boolean[] visited = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Call the recursive helper function to detect cycle in different DFS trees
for (int u = 0; u < V; u++) {
// Don't recur for u if already visited
if (!visited[u])
if (isCyclicUtil(u, visited, -1))
return true;
}
return false;
}
// Driver method to test above methods
public static void main(String[] args) {
// Create a graph given in the above diagram
Graph_Problem_05 g1 = new Graph_Problem_05(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 1);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
if (g1.isCyclic())
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
Graph_Problem_05 g2 = new Graph_Problem_05(3);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
if (g2.isCyclic())
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
}
} |
d1,d2,d3=map(int,input().split())
first_pass=int((2*d1)+(2*d2))
second_pass=int(d1+d3+d2)
third_pass=int(2*d1+2*d3)
fourth_pass=int(2*d2+2*d3)
print(min(first_pass,second_pass,third_pass,fourth_pass)) |
import argparse
import os
from lista_stop3.common.consts import NONLINEARITIES
cmd_opt = argparse.ArgumentParser(description='LISTA-stop')
cmd_opt.add_argument('-gpu', type=int, default=-1, help='-1: cpu; 0 - ?: specific gpu index')
cmd_opt.add_argument('-save_dir', type=str, default='./scratch', help='save folder')
cmd_opt.add_argument('-num_test', type=int, default=3000, help='number of test samples')
cmd_opt.add_argument('-num_val', type=int, default=3000, help='number of validation samples')
cmd_opt.add_argument('-num_val_policy', type=int, default=10000, help='number of validation samples for policy network')
cmd_opt.add_argument('-seed', type=int, default=19260817, help='seed')
cmd_opt.add_argument('-phase', type=str, default='train', help='training or testing phase')
# hyperparameters for training
cmd_opt.add_argument('-loss_type', type=str, default='mle', help='type of loss function')
cmd_opt.add_argument('-loss_weight', type=float, default=0.5)
cmd_opt.add_argument('-batch_size', type=int, default=128, help='batch size')
cmd_opt.add_argument('-learning_rate', type=float, default=1e-4, help='learning rate')
cmd_opt.add_argument('-weight_decay', type=float, default=1e-5)
cmd_opt.add_argument('-learning_rate2', type=float, default=1e-3, help='learning rate for policy during joint training')
cmd_opt.add_argument('-num_epochs', type=int, default=100, help='num epochs')
cmd_opt.add_argument('-start_epoch', type=int, default=0, help='start epoch')
cmd_opt.add_argument('-net', type=str, default=0, help='choose network')
cmd_opt.add_argument('-ws', type=int, default=100, help='windowsize')
cmd_opt.add_argument('-col', type=int, default=500, help='column size')
cmd_opt.add_argument('-iters_per_eval', type=int, default=100, help='iterations per evaluation')
cmd_opt.add_argument('-iters_per_epoch', type=int, default=100, help='iterations per epoch')
cmd_opt.add_argument('-loss_temp', type=float, default=1, help='temperature for softmin in loss')
cmd_opt.add_argument('-min_temp', type=float, default=0, help='minimal temperature for softmin in loss')
cmd_opt.add_argument('-max_temp', type=float, default=0, help='maximal temperature for softmin in loss')
cmd_opt.add_argument('-init_model_dump', type=str, default=None, help='model initilization dump')
cmd_opt.add_argument('-val_model_dump', type=str, default=None, help='best validation model dump')
cmd_opt.add_argument('-var', type=float, default=1, help='variance of Gaussian distribution')
# hyperparameters for policy
cmd_opt.add_argument('-share', type=eval, default=True, help='pi_t for different t, share parameters or not')
cmd_opt.add_argument('-post_dim', type=int, default=8, help='position embedding dimension')
cmd_opt.add_argument('-entropy-coef', type=float, default=0.1, help='probability of non-zero')
cmd_opt.add_argument('-policy_type', type=str, default='sequential', help='choose from sequential and multiclass')
cmd_opt.add_argument('-val_policy_dump', type=str, default=None, help='best validation policy dump')
cmd_opt.add_argument('-policy_hidden_dims', type=str, default='512-256-128-64-1', help='policy MLP hidden sizes')
cmd_opt.add_argument('-policy_multiclass_dims', type=str, default='64-64', help='classification output layers')
cmd_opt.add_argument('-nonlinearity', type=str, default='relu', choices=NONLINEARITIES)
cmd_opt.add_argument('-stochastic', type=eval, default=True, help='stopping rule is stochastic or not')
cmd_opt.add_argument('-kl_type', type=str, default='forward', help='forward kl or backward kl')
# hyperparameters for ISTA
cmd_opt.add_argument('-num_algo_itr', type=int, default=50, help='number of iterations in the algorithm')
cmd_opt.add_argument('-L', type=float, default=0, help='inverse of step size')
# hyperparameters for LISTA model
cmd_opt.add_argument('-T_max', type=int, default=50, help='max number of layers')
cmd_opt.add_argument('-num_output', type=int, default=10, help='num outputs')
# LASSO Problem configuration
# A: m * n matrix
# x: n vector
cmd_opt.add_argument('-m', type=int, default=250, help='dim1 of A')
cmd_opt.add_argument('-n', type=int, default=500, help='dim2 of A')
cmd_opt.add_argument('-rho', type=float, default=0.2, help='sparsity coefficient')
cmd_opt.add_argument('-pnz', type=float, default=0.1, help='probability of non-zero')
cmd_opt.add_argument('-snr', type=float, default=40, help='signal noise ratio')
cmd_opt.add_argument('-snr_mix', type=str, default=None, help='mix signal noise ratio. eg: 20-30-40')
cmd_opt.add_argument('-test_snr', type=str, default=None, help='set test mix signal noise ratio. eg: 5-10')
cmd_opt.add_argument('-con_num', type=float, default=5, help='condition number of matrix A')
cmd_opt.add_argument('-temp', type=float, default=5, help='temperature for soft sign')
cmd_args = cmd_opt.parse_args()
if cmd_args.save_dir is not None:
if not os.path.isdir(cmd_args.save_dir):
os.makedirs(cmd_args.save_dir)
# print(cmd_args)
|
<filename>stories/WheelPickerItem.stories.tsx<gh_stars>1-10
import * as React from "react";
import Component from "../src/components/WheelPickerItem";
export default {
title: "WheelPickerItem"
};
export const normal: React.FC = () => (
<Component
id="0"
activeID="1"
value="0"
height={30}
color="black"
activeColor="black"
fontSize={16}
/>
);
export const active: React.FC = () => (
<Component
id="0"
activeID="0"
value="0"
height={30}
color="black"
activeColor="black"
fontSize={16}
/>
);
|
/**
* perform action for player (human and AI), used bidirectional
* @author normenhansen
*/
@Serializable()
public class ActionMessage extends PhysicsSyncMessage {
public final static int NULL_ACTION = 0;
public final static int JUMP_ACTION = 1;
public final static int ENTER_ACTION = 2;
public final static int SHOOT_ACTION = 3;
public int action;
public boolean pressed;
public ActionMessage() {
}
public ActionMessage(long id, int action, boolean pressed) {
this.syncId = id;
this.action = action;
this.pressed = pressed;
}
@Override
public void applyData(Object object) {
((Spatial)object).getControl(NetworkActionEnabled.class).doPerformAction(action, pressed);
}
} |
Heterotypic binding between neuronal membrane vesicles and glial cells is mediated by a specific cell adhesion molecule.
By means of a multistage quantitative assay, we have identified a new kind of cell adhesion molecule (CAM) on neuronal cells of the chick embryo that is involved in their adhesion to glial cells. The assay used to identify the binding component (which we name neuron-glia CAM or Ng-CAM) was designed to distinguish between homotypic binding (e.g., neuron to neuron) and heterotypic binding (e.g., neuron to glia). This distinction was essential because a single neuron might simultaneously carry different CAMs separately mediating each of these interactions. The adhesion of neuronal cells to glial cells in vitro was previously found to be inhibited by Fab' fragments prepared from antisera against neuronal membranes but not by Fab' fragments against N-CAM, the neural cell adhesion molecule. This suggested that neuron-glia adhesion is mediated by specific cell surface molecules different from previously isolated CAMs . To verify that this was the case, neuronal membrane vesicles were labeled internally with 6-carboxyfluorescein and externally with 125I-labeled antibodies to N-CAM to block their homotypic binding. Labeled vesicles bound to glial cells but not to fibroblasts during a 30-min incubation period. The specific binding of the neuronal vesicles to glial cells was measured by fluorescence microscopy and gamma spectroscopy of the 125I label. Binding increased with increasing concentrations of both glial cells and neuronal vesicles. Fab' fragments prepared from anti-neuronal membrane sera that inhibited binding between neurons and glial cells were also found to inhibit neuronal vesicle binding to glial cells. The inhibitory activity of the Fab' fragments was depleted by preincubation with neuronal cells but not with glial cells. Trypsin treatment of neuronal membrane vesicles released material that neutralized Fab' fragment inhibition; after chromatography, neutralizing activity was enriched 50- fold. This fraction was injected into mice to produce monoclonal antibodies; an antibody was obtained that interacted with neurons, inhibited binding of neuronal membrane vesicles to glial cells, and recognized an Mr = 135,000 band in immunoblots of embryonic chick brain membranes. These results suggest that this molecule is present on the surfaces of neurons and that it directly or indirectly mediates adhesion between neurons and glial cells. Because the monoclonal antibody as well as the original polyspecific antibodies that were active in the assay did not bind to glial cells, we infer that neuron- glial interaction is heterophilic, i.e., it occurs between Ng-CAM on neurons and an as yet unidentified CAM present on glial cells.
of neuronal and glial cells both in the adult and during development (3). The molecular nature of the binding interaction between these cells remains to be determined but the close apposition of neurons to radial glial cells during development raises the possibility that specific adhesion between these cells is the mechanism that ensures directed migration of neurons through many layers of cells. In tissue culture systems, neurons in suspension have been found to bind both to neurons (see reference 4 for review) as well as to monolayers ofglial cells (5,6); the binding to glial cells was inhibited by Fab' fragments prepared from antibodies against neuronal cell surface determinants (6) . Antibodies to the neural cell adhesion molecule, N-CAM (4),t which inhibit interactions between neurons, do not inhibit adhesion of neurons to glial cells (6) . It is therefore likely that the adhesion between neuronal and glial cells is mediated by specific cell surface molecules other than N-CAM .
To test this hypothesis and to isolate these molecules, a quantitative assay suitable for determining adhesion between different cell types (heterotypic adhesion) is required . In this paper, we describe such an assay and apply it to the identification of a new cell adhesion molecule on neuronal cells of chick embryos . The basic characteristics of the assay are (a) the use of doubly labeled membrane vesicles from neurons, (b) the binding of these vesicles to intact glial cells, (c) the addition of Fab' fragments of anti-(N-CAM) in sufficient amounts to suppress homotypic vesicle aggregation, (d) the use of Fab' fragments from antibodies against other neuronal determinants to inhibit the binding of neuronal vesicles to glial cells, and (e) neutralization of this inhibition by extracts of neuronal membranes that contain the putative neuron-glia CAM, Ng-CAM . To identify antigens related to a putative Ng-CAM, cell surface antigens that had neutralizing activity were released from neuronal membrane vesicles in a soluble form by trypsin treatment and were fractionated by gel filtration and lentil lectin affinity chromatography . A monoclonal antibody obtained after injection of an enriched neutralizing fraction was found to inhibit binding of neuronal membrane vesicles to glial cells. Immunoblots of extracts prepared from chick brains with this antibody showed reactivity to material in a band of M, = 135,000. Neuronal cells but not glial cells depleted the inhibitory antibody activity from solution, suggesting that this protein is present on neurons but not on glia. The antigenic and chemical properties of this protein suggest that it constitutes part of a specific adhesion system mediating heterotypic cell binding. MATERIALS BSA, bovine serum albumin ; PBS, phosphate-buffered saline ; DNase, Deoxyribonuclease 1 ; CMF, calcium-magnesium-free medium ; DME, Dulbecco's modified Eagle's medium ; MEM, Eagle's minimal essential medium ; N-CAM, neural CAM ; Ng-CAM, neuron-glia CAM .
Chemicals Ltd. (Poole, England), Bio-Beads SM-2 were from Bio-Rad Laboratories (Richmond, CA), trasylol was from Mobay Chemical Corp. (Pittsburgh, PA), and Na "'I was from New England Nuclear (Cambridge, MA). PBS contained 8 .0 g NaCl, 0 .2 g KCI, 0.2 g KH2PO4 , and 1 .15 g Na2HPO per liter . Calcium-magnesium-free medium (CMF) contained 8 .0 g NaCl, 0.3 g KCI, 0 .0575 g NaH2 PO4 -H2O, 0.025 g KH 2PO4 , 1 .0 g NaHCO3, 2 .0 g D-glucose, 20 mg DNase, and 10 mg phenol red per liter. Collagen was prepared by extraction of rat tail tendons with 0.1 % acetic acid for 48 h at 4°C. Preparation of Fluorescent Brain Vesicles: Brains from three 14-d chick embryos were homogenized with a Dounce homogenizer (A pestle) in 30 ml PBS containing 100 Ag/ml DNase and 5 mg/m16-carboxyfluorescein. The homogenate was spun at 10,000 g for 10 min and the pellet was resuspended in 3 ml PBS containing 100 Ag/ml DNase. This suspension was mixed with 30 ml of PBS containing 2.25 M sucrose and overlayed in a centrifuge tube with 20 ml of PBS containing 0.8 M sucrose. The discontinuous sucrose gradient was centrifuged at 100,000 g for 45 min and the fluorescent vesicles that migrated to the interface were collected and washed three times by centrifugation (10,000 g for 10 min) with PBS . The final pellet was resuspended in MEM to yield a -10% vesicle suspension. All procedures were performed at 4°C .
Preparation of Glial Cells : Neural tissues were dissected from white Leghorn chick embryos . Forebrain, hindbrain, or retina from embryos (10 or 14 d) were dissected under sterile conditions in CMF (brains were prepared free of meninges) . The tissue was gently teased into fragments of " 2 mm and incubated at 37°C in CMF containing 0.1 % trypsin and 1 mM EDTA for 45 min with shaking at 70 rpm. The suspension was centrifuged in a clinical centrifuge at 2,000 rpm for 3 min, the pellet was resuspended in DME containing 10% fetal calf serum, and triturated 20 times with a Pasteur pipette . The cell suspension was layered on a solution of PBS containing 3.5% BSA and centrifuged at 2,000 rpm for 3 min, and after dispersion, cells from the pellet were washed twice in the same medium . The pellet was resuspended at 106 cells/ml in DME supplemented with 10% fetal calf serum, 5 g/liter Dglucose, and 25% conditioned medium (see below) and cultured on tissue culture dishes that were coated with collagen . To prepare these dishes, the tissue culture surfaces were covered with a solution of collagen at 0.5 mg/ml which was removed and the surfaces were air-dried under ultra-violet irradiation for 2 h. To obtain monolayer cultures of glial cells, the cell suspension was incubated (75 ml per roller bottle) at 37°C . The bottles were rotated at 30 rph which allowed neurons to aggregate in suspension, while the glia adhered to and spread on the collagen-coated substrate . After 24-36 h the medium was removed and the bottles were gently washed twice with PBS . The medium was centrifuged to remove cells, passed through a 0.8-1Lm filter, and reapplied to the roller bottles. After 2-3 d in culture, the medium was removed (conditioned medium) and then replaced with fresh medium (DME containing 10% fetal calf serum and 5 g/liter D-glucose) . After 5-7 d in culture, the flat cells grew to confluence and any residual neurons were removed by vigorously washing the monolayer with PBS.
Several considerations indicated that these cells were glial cells. The cultured cells bound a monoclonal antibody that stained cells resembling glia in sections of central and peripheral neural tissues; this monoclonal antibody did not bind to neurons or fibroblasts in culture (J.-P . Thiery, M . Grumet, and G . M . Edelman, unpublished results). In addition, these cells had morphologies and patterns of monoclonal antibody staining similar to flat glial cells that were isolated from 10-14-d chick embryo brains by the procedures of Partlow and co-workers (7,8) and Adler et al. (9) . Finally, the flat cells from brain obtained in our procedure did not stain with anti-(N-CAM); antibodies to N-CAM specifically stain the surfaces of neuronal cells in tissue sections and in culture (10, 11), but do not stain chick glial cells in tissue sections and in culture (11,12). Based on their method of isolation, morphology in culture, and surface determinants, it is likely that these cells are related to astroglia (5)(6)(7)(8)(9), and in this report we will refer to them as glial cells . It should be noted that a completely adequate set of specific criteria distinguishing chick neuronal and glial cells at the tissue culture level remains to be established.
Preparation of Neuronal and Other Cells : Neuronal cells were prepared in suspension by trypsinization of tissue from brain and retina in calcium-free medium as described (13,14) . Suspensions of cells were prepared from embryonic livers by trypsinization in the presence of calcium (15) . Fibroblasts were prepared from the skin of 10-12-d chick embryos by trypsinization as described above for brain tissue and cultured on collagen-coated tissue culture surfaces in DME supplemented with 10% fetal calf serum and 5 g/liter D-glucose. Meninges were dissected from 10-d chick embryo brains, trypsinized, and cultured similarly. All these cultures were free of neurons and had cells with a fibroblast-like morphology (for an example, see reference 6).
Antibodies : Antibodies to purified N-CAM were prepared as described (16) . Monovalent Fab' fragments were prepared from the IgG fraction of rabbit serum (17). Polyspecific antibodies (anti-brain membrane) were obtained by intramuscular, intraperitoneal, and subcutaneous injections of rabbits with 1 ml of membranes (50% suspension in PBS) from 10or 14-d chick embryo brains. The first injection was in complete Freund's adjuvant, the second (2 wk later) was in incomplete Freund's adjuvant, and subsequent injections at 2 wk intervals were without adjuvant. Rabbits were bled weekly after the third injection .
Anti-(N-CAM) Fab' was labeled (18) with "'I for use in the vesicle-to-cell binding assay . 18 ml of anti-(N-CAM) Fab' fragments (5 mg/ml) was incubated with 2 ml chloramine T (I mg/ml) and 2 ml Na '"1 (5 mCi/ml) in PBS at 4°C for 10 min, and then 5 mg of sodium metabisulfite was added to quench the reaction. Unbound "'I was removed by dialysis for 4 h at 4°C in PBS containing 20 mM KI, followed by successive dialyses in PBS. BSA was labeled with Na "'I using the same procedure .
All protein concentrations were measured by the method of Lowry et al. (l9) .
Vesicle-to-Cell-Binding Assay : This multistage assay measures the binding of neuronal membrane vesicles to cells in suspension and was employed in three experimental contexts: (a) to compare the adhesion of the vesicles to different types of cells ; (b) to measure the ability of specific Fab' fragments to inhibit vesicle binding to cells by blocking cell surface adhesion molecules; and (c) to test antigens obtained from embryonic brain membranes for their ability to neutralize inhibition of vesicle binding by the Fab' fragments; we define this as Ng-CAM neutralizing activity.
Glial cells were obtained in suspension from monolayers that were grown to confluence on roller bottles (850 cm', Corning Glass Works, Coming, NY) as described above, washed two times with PBS, and treated with 8 ml of 0 .25% trypsin containing 1 .5 mg/ml collagenase, 0 .02% EDTA, and 100 kg/ml DNase. After enzyme treatment for 45 min at 37°C, 2 vol of DIME containing 10% fetal calf serum and trasylol (100 U/ml) were added and the cells were gently triturated with a Pasteur pipette. The cell suspension was diluted to approximately 106 cells/ml with the same medium and incubated in a spinner bottle (Bellco Glass, Inc., Vineland, NJ) with gentle stirring (100 rpm) for 16-20 h at 37°C under 10% C02. The bottles were then placed in an ice bath for 10 min with gentle stirring. The cells were sedimented by centrifugation for 3 min at 2,000 rpm, resuspended in cold MEM containing 20 ag/ml DNase, centrifuged, and resuspended in 5 ml of MEM . This procedure yielded single cell with only a few aggregates . The number of cells was determined using a Cytograf (Bio/ Physics Systems, Westwood, MA); 2-3 x 108 cells were obtained from 30 forebrains from 14-d embryos after 1 wk in culture on five roller bottles . In culture, these cells had a flat appearance and did not contain any neurons (detected as small, round, process-bearing cells) as judged by light microscopy. Cell viability was 85 ± 10% as judged by trypan blue exclusion .
The vesicles used in the assay were obtained from homogenates ofembryonic brains as described above . Following centrifugation, the fluorescent membrane pellets were resuspended in 3 ml of PBS containing iodinated rabbit anti-(N-CAM) Fab' (4 mg/ml with -10 8 cpm/ml) and 100 tug/ml DNase, incubated overnight at 4°C, and fractionated on discontinuous sucrose gradients as described . The vesicles, which were labeled internally with 6-carboxyfluorescein and externally with`l-(anti- Fab'), were collected by centrifugation, washed three times with PBS, and resuspended in MEM as a 10% suspension. Aggregates of vesicles were removed by centrifugation at 2,000 rpm for 75 s and the supernatant fraction was used in the binding assay. Aliquots of vesicles (0.1 ml containing " 200,000 cpm) were added to 0 .2-0 .5 ml of cold PBS containing Fab' fragments, or to a mixture of Fab' fragments and brain antigens that had been preincubated together for 15 min at 4°C. After 15 min at 4°C, the volume was adjusted to 1 .2 ml by addition of cold MEM containing 20 ,2g/ ml DNase . Equal aliquots of cells (2-5 x 106) were added, the samples were transferred to glass scintillation vials (28 x 61 mm, Wheaton Scientific, Millville, NJ), and rotated at 70 rpm in a New Brunswick environmental incubator shaker at 37°C . After 30 min, the samples were transferred to 12 x 75 mm borosilicate glass tubes (Fisher Scientific Co., Pittsburgh, PA) and centrifuged at 2,000 rpm for 75 s. The supernatant fraction was removed with an aspirator and the pellets were resuspended in I ml MEM, layered onto 3.5 ml of PBS containing 3 .5% BSA, and centrifuged at 2,000 rpm for 75 s. The supernatant fraction was removed with an aspirator and the pellets were counted in a gamma spectrometer . These conditions were selected to minimize the cosedimentation of unbound vesicles with cells containing bound vesicles. The final pellets were gently resuspended in medium and, as determined by fluorescence microscopy, were essentially free of vesicles that were not bound to cells.
Preparation of Detergent Extracts of Membranes from Chick Embryo Brains : Extracts were prepared as described previously (20).
Briefly, brains were removed from 14-d chick embryos and homogenized in a Dounce homogenizer containing CMF supplemented with 200 U/ml trasylol. The homogenate was centrifuged for 10 min at 18,000 rpm in a Sorvall SS34 rotor (E . I . DuPont de Nemours & Co ., Inc ., Sorvall Instruments Div ., Newton, CT) and the pellets were resuspended in 2 .25 M sucrose and fractionated on discontinuous sucrose gradients. The membranes that migrated to the interface 748 THE JOURNAL OF CELL BIOLOGY " VOLUME 98, 1984 were collected, washed twice with PBS as described above, extracted in PBS/ 0.5% Nonidet P-40/1 mM EDTA, and centrifuged for 40 min at 100,000 g. The clear supernatant was removed and mixed with one-third volume of Bio-Beads SM-2 for 2 h with vigorous shaking, and the unbound fraction was dialyzed against PBS. For gel filtration chromatography, 2 .5 ml of a 50% suspension of membranes was extracted in 5 ml of 10 mM Tris, 1 mM EDTA, and 0 .5% sodium deoxycholate, pH 8 .2, and centrifuged at 100,000 g for I h. The supernatant fraction was chromatographed on a Sephacryl S-300 column (1 .8 x 100 cm) in the same buffer and the eluted fractions (4 ml) were dialyzed extensively against MEM before being tested for Ng-CAM neutralizing activity . All procedures were performed at 4°C.
Fractionation of Neutralizing Activity from Trypsin-released Extracts of Chick Embryo Brain Membranes : Membranes (35 ml of a 50% suspension in PBS) were prepared from 14-d chick embryo brains (20) and incubated with 3 .5 mg trypsin for 75 min at 37°C. The enzyme was inactivated by addition of 6.3 mg of soybean trypsin inhibitor, and the membranes were pelleted by centrifugation at 100,000 g for 45 min . The supernatant fraction, the trypsin-released extract, was passed over an anti-(N-CAM) No . 1 affinity column (20) to deplete the extract of N-CAM antigenic determinants. The ionic strength of the unbound fraction was raised to 0 .3 M salt by adding concentrated KCI and the extract was then passed over a 25-ml column of DEAF-cellulose which was equilibrated in 10 mM HEPES/0 . Preparation of Monoclonal Antibodies to Ng-CAM : Mice were injected intraperitoneally at 2-wk intervals with partially purified trypsinreleased extract (100 gg protein) prepared as described above and emulsified with Freund's adjuvant. 3 d after the third injection (without adjuvant), spleens were taken from the mice; the fusion, screening of hybridomas, and production of monoclonal antibodies were performed as described (21) . Hybridoma culture supernatants were screened for binding to 96-well polyvinyl plates coated with 0.5 ag/well of the immunogen and select hybridomas were recloned twice by limiting dilution in 96-well dishes. Recloned hybridomas were injected into mice ; ascites fluid was collected, partially purified by precipitation with 45% ammonium sulfate and dialyzed in PBS. Monoclonal antibody 10176 obtained from culture supernatants reacted with rabbit antisera specific for subtype IgG, .
Binding of Fluorescent Vesicles to Cells
Fluorescein-labeled chick brain membrane vesicles in suspension bound to glial cells in monolayers or in suspension during a 30-min incubation period, and little or no binding occurred with fibroblasts or cells from the meninges . When nonfluorescent membrane vesicles were incubated with glial cells, indirect immunofluorescence with anti-(N-CAM) IgG showed that the bound vesicles were brightly stained by anti-(N-CAM) but the glial cells were not stained (data not shown) . Because N-CAM is a neuron-specific marker in chick brain tissue (10,11), these results indicate that the vesicles that bound to glial cells in these experiments are mainly of neuronal origin .
When anti-(N-CAM) Fab' was absent during vesicle to cell binding, there was extensive homotypic aggregation of the neuronal membrane vesicles (Fig. l, A and B) . Earlier studies showed that the aggregation of artificial vesicles reconstituted from lipid and N-CAM is inhibited by anti-(N-CAM) antibodies (24,25). Therefore, to eliminate binding involving N-CAM and, in particular, any possible aggregation of neuronal membrane vesicles by the N-CAM mechanism, experiments were performed in the presence of anti-(N-CAM) Fab' fragments . Under these conditions, the vesicles were either unaggregated or formed only small aggregates (-3 jm, Fig. 1 C) allowing quantitative and reproducible measurements of vesicle binding to cells .
The binding of vesicles to neuronal, glial, and fibroblastic cells that had been incubated in suspension culture for >16 h was quantified by scoring the percentage of cells that bound fluorescent vesicles after a 30-min incubation period. In pre-vious studies (10), it was shown that neural retinal cells bound retinal membrane vesicles in the presence of preimmune rabbit Fab' fragments and that anti-(N-CAM) Fab' fragments inhibited neuronal vesicle binding ; these results were confirmed here for cells and membrane vesicles that were prepared from 10-d chick embryo brains . In contrast, in the presence of Fab' fragments derived from either preimmune Ig or from anti-(N-CAM) Ig, the binding of neuronal membrane vesicles to glial cells was still clearly detected and, under similar conditions, few if any vesicles bound to fibroblasts ( Fig. 2 and Table I). Most important, vesicle binding to glial cells was inhibited by the Fab' fragments prepared from antibodies against embryonic chick brain membranes (Fig. 3, Table I) .
These results are consistent with the interpretation that 750 THE JOURNAL OF CELL BIOLOGY " VOLUME 98, 1984 neuronal membrane vesicle aggregation is mediated primarily by N-CAM (24,25) and that neuronal membrane vesicle binding to glial cells cells is not mediated by N-CAM but by some other mechanism . Although the binding of brain vesicles to glial cells in suspension could be detected qualitatively with ease and measured quantitatively with these methods (Table I), scoring of the fluorescence was slow and somewhat subjective, making routine use of this form of the assay cumbersome. We therefore used radioactively labeled vesicles to facilitate the simultaneous quantification of binding in many samples.
Binding of ' 251-Vesicles to Cells
To accommodate many samples in a single binding experiment, the neuronal vesicles were radioactively labeled with iodinated proteins that were either incorporated in the intravesicular space or bound to the vesicle surface . To ensure that the characteristics of binding were not changed by the radioactive labeling procedure, vesicles that contained both 6carboxyfluorescein and "'I were prepared . The double label allowed independent measurements of vesicle binding by both fluorescence and radioactivity . In preliminary experiments, the vesicles were prepared from embryonic chick brains by homogenization in the presence of 6-carboxyfluorescein and "'I-BSA . After purification on discontinuous sucrose gradients, vesicles were obtained that were internally labeled by both the dye and the radioactive protein . Binding of these vesicles to glial cells was then measured by both fluorescence microscopy and gamma spectroscopy . It was necessary to include anti-(N-CAM) Fab' fragments in these experiments in order to obtain correlative quantitative binding data on individual samples by both methods; in the absence of Fab' fragments, large aggregates of vesicles co-sedimented with the glial cells in a fashion similar to the result shown in Fig. 1 B. Although this combined procedure allowed quantitative measurement of vesicle binding in individual samples by following both fluorescence and radioactivity, labeling of vesicles with`1 was subsequently found to be even more efficient when the vesicles were incubated with "'I-Fab' fragments from antibodies directed against N-CAM. This procedure served both to label the vesicles radioactively by binding of "l-(anti-(N-CAM) Fab') to N-CAM on the surface of neuronal membrane vesicles, and simultaneously to block most of the homotypic vesicle aggregation mediated by N-CAM . The neuronal membrane vesicles that had been preincubated with "l-(anti-(N-CAM) Fab') still aggregated to a minor extent, however, and for this reason, the assay was performed in the presence of additional unlabeled anti-(N-CAM) Fab', which limited vesicle aggregation to the level shown in Fig. 1 C. The results obtained when vesicle binding to cells was measured in identical samples by either fluorescence or radioactivity were similar . In the same experiment, anti-brain membrane Fab' significantly inhibited vesicle binding to glial cells compared with the control level of binding in the presence of anti-(N-CAM) ( Table 1). Significantly less binding occurred when vesicles were incubated with an equivalent number of fïbroblasts or liver cells (Table I) . The data indicated that comparable results could be obtained with either the radioactive or the fluorescence method. Because radioactive tracing allowed rapid measurement of as many as 40-50 samples at the same time and was less subjective in its scoring, it was chosen for routine use .
For the development of this assay, procedures were established for isolation of both neuronal membrane vesicles and glial cells from 14-d chick embryo brains because at this time in chick neural development the glia are proliferating and interacting with neurons. Glial cells that were isolated from 10-d embryo brains showed similar binding characteristics, although fewer cells could be isolated from an equivalent mass of 10-d brain tissue. Vesicles that were isolated from 10d embryo brains bound to glial cells, but the level of binding was 30-40% less than with 14-d vesicles. Both cells and vesicles were therefore routinely prepared from 14-d chick embryo brains .
Characteristics of Vesicle-to-Cell Binding
The extent of vesicle-to-cell binding was measured over a wide range of vesicle and cell concentrations (Fig. 4). Increasing both the number of vesicles (up to 200 Etl) and the number of cells (up to approximately 7 .5 x 106 ) in the 1 .2-ml assay volume resulted in linear increases in binding (Fig. 4, a and b). At higher concentrations of either cells or vesicles, saturation of binding began . To simplify quantitative interpretation of the assay, vesicle and cell concentrations were subsequently maintained in the linear portions of the binding curves .
At a constant level of cells and vesicles, the rate of binding and the effect of temperature on binding were tested . In routine assays, binding was measured after a 30-min incubation period at 37°C following a preincubation of the vesicles with antibodies at 4°C . The extent of binding after incubation at 37°C for different intervals of time is shown in Fig. 4c. A significant level of binding was measured after 10 min and the level of binding increased with longer incubation periods. The level of vesicle binding to glial cells in samples that had been maintained on ice for 30 min rather than at 37°C was also measured (Fig. 4c, zero time point) . In several experiments, this value ranged between 15-35% of the control level of binding and probably reflects the magnitude of nonspecific vesicle binding in the assay . Vesicles that were incubated without glial cells for 30 min at 37°C had a small amount of radioactivity in the final pellet (open circle, Fig . 4c) which ranged between 10-20% of the control level of binding to glial cells.
Previous observations (6) indicated that the binding of neuronal cells to glial cells is not dependent on the presence of calcium . In accordance with these results, the calciumchelator EDTA (up to 3 mM) had no effect on vesicle-to-cell binding. Moreover, it was found that the metabolic inhibitor sodium azide had no significant effect on binding (<5% inhibition of control) at final concentrations ranging from 0.1 to 3 .0 mM .
Specific Antibodies Inhibit Binding and Membrane Antigens Neutralize This Inhibition
Fab' fragments of Igs against brain membranes block adhesion of neuronal cells to glial cells (6) and, as the present studies show, they also inhibit binding of neuronal membrane vesicles to glial cells ( Fig. 3 and Table 1). Quantitative measurements of this inhibition are shown in Fig . 5 a. The inhibition increased with the antibody concentration and eventually reached a plateau level that in different experiments varied between 65-85% of the control level . Inhibition of >50% of the specific binding was found with 0 .5 mg of Fab' fragments that were prepared from each of eight rabbits that had been immunized with membranes from 10-or 14-d embryonic chick brains. The portion of the binding that was not inhibited by saturating amounts of Fab' (15-35%) was similar in magnitude to the fraction of the binding that was nonspecific (compare Figs. 4c and 5a) . This binding was attributed to nonspecific effects such as binding to dead cells or glass, cosedimentation of vesicles that were nonspecifically bound to cells, background radiation, and nonspecific transfer of noncovalently bound ' 25 I from Fab' to cells. The level of binding to fibroblasts and liver cells (Table 1) is approximately one-fourth the level of that to glial cells, and probably represents nonspecific binding of a similar kind.
After demonstration that specific antibodies inhibited binding of neuronal membranes to glial cells, it was possible to search for molecules containing antigenic determinants involved in the binding . The detection of such molecules depends on their ability to bind to Fab' fragments prepared from anti-brain membrane antisera, thereby neutralizing the inhibitory activity of the Fab' and permitting vesicle to cell binding to occur. To test initially for the presence of neutralizing material, anti-brain membrane Fab' fragments were incubated with 14-d embryonic chick brain membranes and the mixture was centrifuged to remove the membranes; the supernatant fraction was then tested for its ability to inhibit vesicle-to-cell binding in the presence of control antibody (0.5 mg/ml anti-(N-CAM) Fab' fragments) . All of the inhibitory activity of the antibodies was depleted by incubation with the membranes. Neuronal cells in suspension effectively removed the inhibitor activity of anti-brain membrane Fab' fragments, but glial cells in suspension were ineffective . These results suggest that one or more antigens specifically involved in neuronal cell-to-glial cell adhesion are present on neuronal and not glial cell surfaces.
The antigens were solubilized by extraction of 14-d chick brain membranes with the nonionic detergent Nonidet P-40. The detergent was removed and the fraction that remained soluble after high speed (100,000 g) centrifugation neutralized the inhibitory activity of anti-brain membrane Fab' fragments in a concentration-dependent manner (Fig. 5 b). The extract was capable of completely neutralizing the inhibition by anti-brain membrane Fab' indicating that practically all the inhibitory antibodies were neutralized by antigenic determinants in the extract.
An important feature of the assay necessary for quantitative measurements of vesicle-to-cell binding was inhibition of Properties of the binding of "'I-neuronal membrane vesicles from 14d chick embryos to glial cells in suspension . The level of binding was measured as a function of (a) the volume of radiolabeled vesicles (10% suspension) added to 5 x 10 6 Inhibition of vesicle binding to glial cells by anti-brain membrane Fab' fragments and neutralization of this inhibition with detergent extracts of membranes . (a) . . . I-neuronal membrane vesicles (0 .1 ml) were preincubated for 15 min on ice in 0 .4 ml PBS containing a mixture of Fab' fragments from anti-(N-CAM) Ig and anti-brain membrane Ig in different ratios so that the anti-(N-CAM) titer was maintained constant while the anti-brain membrane Fab' was increased in the 1 .2-ml assay volume . The titer of anti-(N-CAM) from each antiserum was measured in an assay involving aggregation of retinal neural cells as described previously (26) . In contrast to the concentration-dependent inhibition of binding found with anti-brain membrane Fab', anti-(N-CAM) Fab' at concentrations as high as 2 mg/ml did not affect the control level of binding or the inhibition by anti-brain membrane Fab' . (b) A mixture of anti-brain membrane Fab' fragments (0 .4 mg) and anti-(N-CAM) Fab' fragments (1 mg) was preincubated with different amounts of membrane detergent extract in 0 .4 ml PBS for 15 min on ice and binding of "'I-neuronal membrane vesicles (0 .1 ml) to 5 x 106 glial cells was measured . The mean values of binding of duplicate samples are shown, and the mean deviation was <10% . The control level of binding (-) and the level of binding with 0 .4 mg anti-brain membrane Fab' fragments (---) are shown in the figure .
Fractionation of Neutralizing Activity and Isolation of a Monoclonal Antibody That Inhibits Adhesion
To purify cell surface molecules involved in cell adhesion they must be solubilized . As a first step for the purification and characterization of the neutralizing activity, deoxycholate extracts of membranes were fractionated on Sephacryl S-300 (Fig. 6). Comparison with the profile of absorbance at 280 nm indicated that the neutralizing activity was enriched in the higher molecular weight fractions (Mr -150,000) .
Attempts to further purify the neutralizing activity from detergent extracts of membranes were unsuccessful . We therefore attempted to release a soluble form of the neutralizing activity from neuronal membrane vesicles with proteolytic enzymes . Most of the neutralizing activity on neuronal mem-brane vesicles was depleted from the membranes after treatment with trypsin and was recovered in a high speed supernatant (100,000 g) fraction. The trypsin-released material remained soluble in the absence of detergent, and survived several purification steps (Table II) . The trypsin-released extract also contained N-CAM antigenic determinants which were detected with a neutralization assay for N-CAM (26); the extract was therefore passed over a column of anti-(N-CAM) monoclonal antibody coupled to Sepharose CL-2B to remove most of these determinants (20). Nucleic acids and some protein were then removed by passing the extract over a column of DEAF-cellulose in 0 .3 M KCI . The unretarded fraction, containing most of the neutralizing activity (Table II), was then filtered on a column of Sephacryl S-300 (Fig. 7). High molecular weight fractions (Mr -100,000) from the column neutralized inhibition by anti-brain membrane Fab' of binding of neuronal vesicles to glial cells (Ng-CAM neutralizing activity) . Residual N-CAM neutralizing activity (26) eluted in the lower molecular weight fractions, and was separated from the peak of Ng-CAM neutralizing activity. The Fractionation of a detergent extract of membranes by gel filtration and Ng-CAM neutralizing activity of fractions . A soluble extract of membranes (5 ml) was applied to a Sephacryl S-300 column and the fractions that were eluted were assayed for absorbance at 280 mm (-) . Fractions (0 .5 ml) were dialyzed and were tested for neutralization activity (0---e) as described in the legend to Fig . 5b . One unit of Ng-CAM neutralizing activity is defined as the amount required to reduce by 50% the inhibition of binding of neuronal membrane vesicles to glial cells in the standard assay (see Materials and Methods) . FIGURE 7 Fractionation of a trypsin-released extract of membranes and determination of Ng-CAM activity of fractions . The fraction that passed through a DEAE-cellulose column (Table II) was concentrated and 2 .6 ml was applied to a Sephacryl S-300 column that was equilibrated and eluted in PBS. Fractions (50 Isl) were tested for protein (19) and neutralizing activity from the Sephacryl S-300 fractions was purified further by affinity chromatography on lentil lectin-Sepharose CL-4B, (Table II). This material was enriched approximately 50-fold in neutralizing activity, but it still contained many polypeptides as estimated by SDS PAGE data not shown) . To obviate this difficulty, this material was injected into mice to produce monoclonal antibodies which were then used to specifically identify the neutralizing molecules .
Monoclonal antibodies that bound to the partially purified trypsin-released material were tested for their ability to inhibit binding of neuronal membrane vesicles to glial cells. One clone, IOF6, was found to secrete an antibody that inhibited binding of neuronal membrane vesicles to glial cells to the same extent as polyclonal anti-brain membrane Fab' (Table III). Detergent extracts of embryonic chick brain membranes were immunoblotted using monoclonal antibody 1OF6 ; a polypeptide of M, = 135,000 was specifically recognized (Fig. 8) and relatively lower levels of reactivity were detected at M, = 200,000 (12). In addition to these bands, SDS PAGE of immunoprecipitates from detergent extracts of membranes using this antibody showed small amounts of a diffuse band of M, = 80,000 (12). Monoclonal antibody l OF6 did not recognize N-CAM in immunoblots ofboth detergent extracts of membranes (Fig. 8) and purified N-CAM (12) . Furthermore, a monoclonal antibody to N-CAM that inhibits the aggregation of vesicles reconstituted with N-CAM (25) did not inhibit binding (Table III) . These results suggest that the antigens specifically recognized by monoclonal antibody l OF6 are involved in neuron to glial cell adhesion and that these antigens are immunologically distinguishable from N-CAM .
DISCUSSION
The results presented here indicate that Ng-CAM is present on neuronal cells of the chick embryo and that it is responsible for the interaction of neuronal cells with glial cells. This molecule is distinct from the previously described N-CAM . Moreover, since Ng-CAM is not detected on glial cells, neuron-glial interaction, unlike neuron-neuron and neuron-myotube adhesion, appears to be between different molecules, one of which is Ng-CAM and the other remains to be identified. GRUMET Monoclonal 20 ug of ammonium sulfate precipitate of ascites fluid was used . Anti-(N-CAM) No . 1 was obtained as described (20) . ' Binding was measured as described in Table I . In examining cell-cell adhesions, both the cellular mode of binding, e .g., homotypic vs. heterotypic, and the molecular nature of the binding that mediates the adhesion, e.g., homophilic vs. heterophilic, must be distinguished. These mechanisms are schematically represented in Fig. 9, and for simplicity they are considered only in terms of binding between two partners . Homotypic adhesion (cell type A to cell type A) can occur in two different molecular modes; either one CAM binds to itself (Fig. 9, panel I) or one CAM binds to a complementary and different CAM (Fig. 9, panel 11) . Previous studies on the molecular bases of homotypic cell-cell adhesion employed cell aggregation assays (4,27,28). These assays were based on the inhibition of the aggregation of a particular cell type by monovalent antibody fragments raised against cell surface determinants and on the reversal of this inhibition by neutralization of the antibody with cell surface molecules . The use of such neutralization assays facilitated the identification and purification of molecules from the cell surface of vertebrate neuronal cells (20,26,29), liver cells (15,30), and embryonal carcinoma cells (31,32) ; the involvement of these molecules in homotypic cell-cell adhesion has been amply demonstrated in vitro (reviewed in reference 4).
1754
THE JOURNAL OF CELL BIOLOGY -VOLUME 98,1984 Heterotypic adhesion (cell type A to cell type B) can occur in the same two molecular modes (Fig. 9, panels III and IV) . The adhesion between neurons and myotubes, for example, appears to be mediated by a homophilic mechanism in which N-CAM on the neuron binds to N-CAM on the myotube (13,16,24), whereas the interaction between neurons and glial cells described here appears to be heterophilic . However, use of the neutralization approach with specific heterotypic adhesion presented several problems .
The major problem posed by heterotypic adhesion is that each of two different cell types can potentially bind homotypically, i .e ., to itself, as well as to the other cell type . This required that a number of conditions be met in order to detect the molecules responsible for the heterotypic interaction . First, it was necessary to unequivocally identify cells or membrane vesicles derived from particular tissue types . In this study, the identity of the different cell types was established by a combination of behavior in culture, morphology, and surface determinants . A major (but not the only) criterion was the difference between the two chicken cell types in their ability to bind two different specific monoclonal antibodies, the first against N-CAM (for neurons) and the other against an as yet unidentified glial surface antigen (reference 6 and J .-P . Thiery, M . Grumet, and G . M. Edelman, unpublished observations).
It was also necessary to develop a quantitative system for evaluating the adhesiveness between vesicles and cells, each of different origin . Previous studies (13,16,24,25,33,34) support the idea that the adhesive specificity is maintained when vesicles are substituted for cells in adhesion assays . The large difference in size between the vesicles and the cells allowed distinct recognition of the specific adhesion between neuronal and glial membranes. In the present assay, the interaction was followed quantitatively by using doubly labeled neuronal vesicles. Microscopic observation indicated that the fluorescent vesicles only bound to the surface of -50% of the glial cells. This result may indicate heterogeneity in the glial cell population and more detailed cell identification and fractionation are necessary to resolve this issue . "'I-Fab' fragments from anti-(N-CAM) antibodies were particularly useful as a label for vesicles because the abundance of N-CAM on the surface of neuronal membrane vesicles allows sufficient radioactive labeling. In addition, the antibody Molecular Mode blocks the bulk of homotypic vesicle aggregation (a necessary condition for the quantitation of heterotypic binding), and acts as a convenient marker for neuronal membranes in this system . It should be stressed that this unique label for neuronal vesicles does not limit the generality of the assay inasmuch as both native vesicles from a variety of cell types and reconstituted vesicles can be internally labeled with "'I-BSA and fluorescent dyes . Furthermore, neuronal membrane vesicles have been directly labeled with 1z'I by the lactoperoxidase method (described in detail in reference 16) and specific binding of such "'I-neuronal membrane vesicles to glial cells has been measured (unpublished observations). Nevertheless, the use of a specific and abundant surface label such as N-CAM is to be preferred when available .
With these conditions met, the immunological approach to cell-cell adhesion previously developed for homotypic adhesion (4) could be applied in a compound assay . Under the conditions used, the adhesion of neuronal membranes was specific for glia. Because only the vesicles were labeled, their adhesion to cells could be unequivocally determined after the cells were separated from the unbound vesicles by differential centrifugation . Fab' fragments prepared from antisera raised against neuronal membranes inhibited the binding of neuronal membrane vesicles to glial cells. The finding that extracts of brain membranes neutralized the inhibition by these Fab' fragments completed the requirements necessary for a quantitative assay to measure neutralizing activity during purification .
Use of thisassay allowed isolation ofa monoclonal antibody that strongly inhibited the binding of neuronal vesicles to glial cells. The CAM (Ng-CAM) that was specifically recognized by the antibody is different both chemically and functionally from N-CAM. Whereas embryonic N-CAM migrates on SDS PAGE in a broad region, M r = 200,000-250,000 (20), the major component of Ng-CAM migrated as a discrete band at Mr = 135,000. Furthermore, after gel filtration of a deoxycholate extract of membranes, a peak of Ng-CAM neutralizing activity was detected at Mr = 150,000, implying that Ng-CAM is not aggregated in this detergent. Cell adhesion assays indicated that monoclonal antibodies to Ng-CAM (1 OF6) and N-CAM (anti-(N-CAM) No. 1) specifically inhibit neuronglia adhesion and neuron-neuron adhesion, respectively (Table III and reference 25). Other monoclonal antibodies to neuronal antigens, however, have recently been obtained that recognize both Ng-CAM and N-CAM; this cross-reactivity is considered in detail elsewhere (12).
Several results suggested that the adhesion between neurons and glial cells is heterophilic. The finding that neurons, but not glia, could deplete the inhibiting antibodies suggested that Ng-CAM is present on neurons but not on glia . In indirect immunofluorescence experiments, monoclonal antibody I OF6 has been found to stain neurons but not glial cells (12); these results further indicated that the adhesion between neuronal cells and glial cells is heterophilic . The behavior of Ng-CAM neutralizing activity on gel filtration columns suggested that it was not self-aggregated, consistent with the idea that Ng-CAM binds to a complementary heterophilic CAM on glial cells and not to itself (Fig. 9, panel IV) . With an appropriate anti-glial cell antibody, the present assay can be applied to test for CAMS present on glial cells that are involved in binding to Ng-CAM on neurons .
As with any in vitro phenomenon, the direct relevance of heterotypic vesicle adhesion to physiological mechanisms in vivo must be established by separate criteria. The new assay developed in the present studies was used mainly as a tool to help identify Ng-CAM by means of a specific monoclonal antibody. It is now possible to test additional effects of specific antibodies to Ng-CAM on adhesion of neurons to glial cells (6) as well as on more complex in vitro and in vivo systems. We are also in a position to search for protein components in addition to the major neuronal protein of Mr = 135,000 that may take part in making up the heterophilic system ; until all such components are identified and the role of the molecules of Mr = 200,000 and 80,000 is fully determined (12), the characterization of Ng-CAM must be considered incomplete .
Further pursuit of such studies may reveal the role of both Ng-CAM and its putative ligand on glial cells in forming connections between migrating neurons and glial fibers during development, and in the organization and the maintenance of mature neural tissues . |
Novel Glucosensor for Hypoglycemic Detection Localized to the Portal Vein
In this investigation, we sought to constrain the locus of essential portohepatic glucosensors and test the hypothesis that they reside strictly in the portal vein and not the liver. Male Wistar rats were chronically cannulated in the carotid artery (sampling), jugular vein (infusion), and portal vein, either adjacent to (PORADJ, 0.6 ± 0.1 cm, n = 6) or upstream from (PORUPS, 2.7 ± 0.1 cm, n = 8) the liver. Animals were exposed to one of three protocols distinguished by the site of glucose infusion: PORUPS, PORADJ, or peripheral (PER). Systemic hypoglycemia (2.4 ± 0.1 mmol/1) was induced via jugular vein insulin infusion (50 mU · kg−1 · min−1). Arterial plasma catecholamines were assessed at basal (−30 and 0 min) and during sustained hypoglycemia (60, 75, 90, 105 min). By design, hepatic glucose was significantly elevated during PORUPS and PORADJ versus PER (4.3 ± 0.1 vs. 2.4 ± 0.1 mmol/l, respectively; P < 0.05). There were no significant differences between protocols in arterial glucose or insulin concentrations (9,372 ± 1,798 pmol/l). When liver and systemic glucose concentrations were allowed to fall concomitantly (PER), epinephrine was elevated 16-fold above basal levels (3.0 ± 0.6 vs. 46.4 ± 4.3 nmol/l, P < 0.001). When portohepatic normoglycemia was maintained during PORUPS, a 67% suppression in the epinephrine response versus that during PER was observed (P < 0.001). However, when the cannula was advanced adjacent to the liver, by comparison with PER, there was no suppression in the sympathoadrenal response (P = 0.73). While both PORUPS and PORADJ yielded elevated liver glycemia in the face of systemic hypoglycemia, only POR(UPS yielded an elevated portal vein glucose concentration. That only PORUPS resulted in a significant suppression of the sympathoadrenal response is consistent with the localization of the glucosensors to the portal vein. |
def protocol_with(name, fs, channels):
return supported_protocols[name](fs, channels) |
import { Component, Output, EventEmitter, Input, OnInit } from '@angular/core';
import { ARTEMIS_DEFAULT_COLOR } from 'app/app.constants';
export interface Coordinates {
left: number;
top: number;
}
const DEFAULT_COLORS = [ARTEMIS_DEFAULT_COLOR, '#9dca53', '#94a11c', '#691b0b', '#ad5658', '#1b97ca', '#0d3cc2', '#0ab84f'];
@Component({
selector: 'jhi-color-selector',
templateUrl: './color-selector.component.html',
styleUrls: ['./color-selector.scss'],
})
export class ColorSelectorComponent implements OnInit {
colorSelectorPosition: Coordinates;
showColorSelector = false;
@Input() tagColors: string[] = DEFAULT_COLORS;
@Output() selectedColor = new EventEmitter<string>();
ngOnInit(): void {
this.colorSelectorPosition = { left: 0, top: 0 };
}
openColorSelector(event: MouseEvent) {
const parentElement = (event.target as Element).closest('.ng-trigger') as HTMLElement;
this.colorSelectorPosition.left = parentElement ? parentElement.offsetLeft : 0;
this.colorSelectorPosition.top = 65;
this.showColorSelector = true;
}
selectColorForTag(selectedColor: string) {
this.selectedColor.emit(selectedColor);
this.showColorSelector = false;
}
cancelColorSelector() {
this.showColorSelector = false;
}
}
|
def convert_vv(self, xvv, yvv, zvv=None):
xvvin = yvvin = zvvin = None
if not xvv.is_float64:
xvvin = xvv
xvv = gxvv.GXvv(xvv, dtype=np.float64)
if not yvv.is_float64:
yvvin = yvv
yvv = gxvv.GXvv(yvv, dtype=np.float64)
if zvv and not zvv.is_float64:
zvvin = zvv
zvv = gxvv.GXvv(zvv, dtype=np.float64)
if zvv:
self._pj.convert_vv3(xvv.gxvv, yvv.gxvv, zvv.gxvv)
else:
self._pj.convert_vv(xvv.gxvv, yvv.gxvv)
if xvvin:
xvvin.set_data(xvv)
if yvvin:
yvvin.set_data(yvv)
if zvvin:
zvvin.set_data(zvv) |
// NewHttpServer creates a HTTP server
func NewHttpServer(c *conf.Config, svc *service.Service) *http.Server {
router := routers.NewRouter()
var opts []http.ServerOption
if c.Http.Addr != "" {
opts = append(opts, http.Address(c.Http.Addr))
}
srv := http.NewServer(opts...)
srv.Handler = router
return srv
} |
/**
* Exemplo de um Adapter customizado, exibindo imagens
*
* @author ricardo
*
*/
public class ExemploSmileAdapter extends ListActivity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
ArrayList<Smile> list = new ArrayList<Smile>();
list.add(new Smile("Feliz", Smile.FELIZ));
list.add(new Smile("Triste", Smile.TRISTE));
list.add(new Smile("Louco", Smile.LOUCO));
// Adaptador de lista customizado para cada linha
setListAdapter(new SmileAdapter(this, list));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Pega o Smile naquela posi��o
Smile smile = (Smile) this.getListAdapter().getItem(position);
// Exibe um alerta
Toast.makeText(this, "Voce selecionou o Smile: " + smile.nome, Toast.LENGTH_SHORT).show();
}
} |
// AddTemplate used to add template.
func (wx *Weixin) AddTemplate(shortid string) (string, error) {
var request struct {
Shortid string `json:"template_id_short,omitempty"`
}
request.Shortid = shortid
data, err := marshal(request)
if err != nil {
return "", err
}
reply, err := wx.postRequest(weixinTemplate+"/api_set_industry?access_token=", data)
if err != nil {
return "", err
}
var templateID struct {
ID string `json:"template_id,omitempty"`
}
if err := json.Unmarshal(reply, &templateID); err != nil {
return "", err
}
return templateID.ID, nil
} |
Prevalence of intestinal parasitic infections and associated risk factors among children attending a tertiary care hospital
hospital-based prospective study to estimate the prevalence rates of IPIs and to assess the risk factors associated with in (cid:976)ive analysed for IPIs and associated risk 2019. Information on the associated risk factors obtained from a questionnaire Microscopic examination of was by direct slide and after the formol-ether technique. overall prevalence of IPIs was dual analysis from an open well, a of IPIs Multivariate logistic regression of with years) and
Intestinal parasitic infections (IPIs) are one of the major causes of morbidity in the developing world. This hospital-based prospective study was undertaken to estimate the prevalence rates of IPIs and to assess the risk factors associated with these infections in children attending a paediatric hospital. Seven hundred and ive patients were analysed for IPIs and associated risk factors from April 2018 to March 2019. Information on the associated risk factors was obtained from a structured questionnaire protocol. Microscopic examination of stool samples was done by direct slide smear and after the formolether concentration technique. The overall prevalence of IPIs was 20.9%. In the age group, 5-9 years, the prevalence of parasitic infection (27.4%) was high. Among the intestinal parasites detected helminths and protozoans were 60.8% and 39.1% respectively. Among the helminths, Ascaris lumbricoides (20.5%) was most prevalent followed by Trichuris trichiura (18.1%) while among the protozoa Giardia intestinalis (18.7%) was most prevalent, followed by Entamoeba spp. (8.4%). Among the positive samples, the single parasite was detected in 87.8% while dual parasites were detected in 12.2% stool samples. Univariate analysis showed age, drinking water from an open well, a habit of open defecation, illiteracy and living in a rural area to be associated with a high risk of IPIs (P<0.05). Multivariate logistic regression revealed a signi icant association of intestinal parasitic infections with age (0-5years) and (10-14 years) and drinking water from an open well. Identifying and rectifying risk factors by creating awareness are needed to prevent community spread. Periodic deworming programmes should be implemented successfully in the community.
INTRODUCTION
Intestinal parasitic infections (IPIs) are a major public health problem in developing countries. According to the World Health Organization, worldwide, more than 1.5 billion people are infected with soiltransmitted helminthic (STH) infections. More than 267 million preschool-age children and 568 million school-age children (SAC) live in areas where parasites are intensively transmitted and are in need of treatment and preventive interventions (WHO, 2020). India accounts for almost one quarter of the world's ascariasis and hookworm cases (Hotez and Damania, 2018). Most of these infections are trans-mitted by ova present in human faeces that in turn contaminate soil in areas where sanitation is poor. Factors contributing to the spread of these infections are scarcity of potable drinking water, lack of awareness, failure to practice proper handwashing after defecation, the practice of open defecation and low standard of personal hygiene. Also, increasing population, poor socioeconomic conditions, continuous urbanization, industrialization and climatic changes may contribute to the emergence of previously unrecognized diseases. Infection with STH cause iron de iciency anemia and protein-energy malnutrition. Severe infections may lead to intestinal obstructions and gangrene. (Parija et al., 2017) They are responsible for morbidity, particularly in young children, including growth and cognitive stunting (Weatherhead et al., 2017). In India the prevalence rates of intestinal parasitic infections differ from region to region, Several studies (Barda et al., 2014;Greenland et al., 2015) have been undertaken in different parts of India, but there are only a few studies reported from Rajasthan (Choubisa et al., 2012;Saurabh et al., 2017).
This study was undertaken to ind out the prevalence rates of IPIs and to assess the risk factors associated with these infections in children attending a pediatric hospital.
Study participants and data collection
This prospective study was carried out in the Microbiology laboratory of a paediatric hospital attached to a Medical College between April 2018 and March 2019. All children clinically suspected to have parasitic infections were included in the study. Children who had taken anti-parasitic treatment in the last 1 month and those whose parents/guardians did not give consent were excluded from the study. Demographic details as well as information on risk factors, were collected by interviewing each child's parents/guardians on a structured questionnaire. This included information such as age, sex, education of mother (literacy status) (illiterate, below or above 10th class), source of drinking water (tap or well water), defecation site (open or modern sanitary toilet) and handwashing habit after defecation. While illing the form inger nails of patients were also inspected. Informed consent was taken from all parents/guardians before data collection.
Stool sample collection and processing
After proper instructions, children/parents were given labelled containers and applicator sticks. On receipt, each stool sample was examined macro-scopically for color, consistency, presence or absence of mucus, blood, body segments of parasites and adult worms. Saline and iodine wet mount preparations were made from each sample before and after formal-ether concentration technique. These samples were observed under 100 X and 400 X magni ications to detect cysts, trophozoites, eggs and larvae (Chatterjee and Parasitology, 2017).
Ethical clearance
Ethical clearance was obtained from the institutional review board.
Statistical analysis
Categorical variables were expressed as proportions (%). Prevalence rates were calculated using standard formulae. Chi-square test was used for univariate analysis of categorical variables to ind out associated risk factors. Signi icantly associated determining factors found in univariate analysis were put in the multivariate logistic regression analysis model. Method of entry used was stepwise. Probability of retaining in the model was kept 0.05 while that of exclusion was 0.10.
ROC curve analysis was done to ind determining power of model and area under the curve (AUC) was calculated. P-value < 0.05 was considered as significant. All statistical calculations were done by Medcalc software version 16.4.
Socio-demographic characteristics
The study included a total of 705 cases. The prevalence of IPIs was 20.9%. In males, the prevalence rate was 20.7%, and in females 21.3%. The prevalence of parasitic infection was highest (27.4%) in the age group of 5-9 years.
Prevalence of Intestinal Parasites
Nine species of intestinal parasites were identiied out of which 6 species were identi ied as helminths, and the other 3 species were protozoans. Among the intestinal parasites detected 60.8% were helminths and 39.1% were protozoans. Among the helminthes 20.5% were identi ied as Ascaris lumbricoides, Trichuris trichiura 18.1%, hookworm 17.8%, Hymenolepis nana 6.6%, Taenia spp.6.6%, and Enterobius vermicularis 1.2%. Among the protozoa, 18.7% were identi ied as Giardia intestinalis and 6.0% as Entamoeba spp. Table 1. Among the non-pathogenic cysts, Entamoeba coli was detected in 12.0 % of stool samples. Single and dual parasitic infection was detected in 87.8% and 12.2% of stool samples, respectively. The most common combination observed was Entamoeba spp. + G. intestinalis IPIs are a major public health problem in developing countries like India. They are the main cause of morbidity in SAC who have a high burden of parasitic infections. In the present study, out of 705 stool samples examined, 20.9% were harboring one or more intestinal parasites. This is in concordance with indings of other studies 25.5% in Delhi, (Mahajan et al., 1993) and 20.3% in Jodhpur, (Saurabh et al., 2017) but lower as compared with reports of other similar studies 38.0 % in Ghaziabad, (Bisht et al., 2011) 51.5% in South India, (Fatima and Shubha, 2011) and 71.5% in Kashmir (Wani et al., 2007). These variations in prevalence might be due to differences in environmental sanitation, socioeconomic status and educational status of parents and study subjects. The detection of parasites was almost similar in males (20.7%) and females (21.3%), which are in concordance with another study (Saurabh et al., 2017). This may be attributed to the equal involvement of females in outdoor activities. Some studies have reported a male preponderance, (Bisht et al., 2011;Fatima and Shubha, 2011) while in some females were found to have a predominant infection (Kotian et al., 2014). The isolation of helminths was higher (60.8%) as compared to protozoa (39.1%). Fatima and Shubha (2011) also reported a higher rate of helminths in their study. However, Bisht et al. (2011); Ashok et al. (2013) reported higher rates of protozoa in their studies. These differences in prevalence rates may be due to diversity in geographic regions, age groups, educational status and personal hygienic practices being followed by the study subjects. STH infections are one of the major health problems in tropical and sub-tropical countries affecting the physical growth and cognitive development in SAC. Among the positive samples, the single parasite was detected in ( with practices of open defecation, poor personal sanitation, lack of footwear wearing habit and poor socio-economic status. In addition contamination of soil by human faeces in combination with a high degree of overcrowding and a low-income level increases the susceptibility to helmithiasis (Wani et al., 2007). G. intestinalis is usually associated with poor sanitary surroundings and insuf icient water treatment. Nutritional de iciency is common in children infected with G. intestinalis.
Our study assessed the possible association of intestinal parasitic infection with potential risk factors. As compared to children in 0-4 years age group, children of age group 5-9 years and 10-14 years had a signi icantly higher risk of acquiring infection (aOR:1.99,95%CI:1.31-3.02, P=0.0012 and aOR:2.25,95%CI:1.33-3.81, P=0.0024 respectively). This inding may be partially explained due to outdoor activities seen at a higher age group. Also, at a higher age, these infected children may have more exposure to the soil during growing vegetables and eating raw, unwashed vegetables. A high prevalence in the age group 5-9 years has been reported in other studies (Bisht et al., 2011;Fatima and Shubha, 2011).
In the present study, the prevalence among rural children was signi icantly higher than among urban children (OR: 2.05, 95% CI: 1.42-2.96, P= <0.001). Similar results have been reported by Bisht et al. (2011);Tenali et al. (2018). This may be due to poor personal hygiene and literacy rates prevailing in rural areas.
There were signi icantly more infected children in whose mothers were illiterate as compared to those who were educated (OR: 2.02, 95% CI: 1.12-3.65, P= 0.014). A high percentage of these illiterate mothers are likely to be ignorant about proper hygienic practices. Tenali et al. (2018) also reported a higher prevalence of parasitic infections among children of uneducated mothers. Mothers should be provided information on the transmission of IPIs and adoption of preventive measures in order to be actively involved to reduce infections among their children.
Open ield defecation was found to have a signi icant risk for acquiring parasitic infection (OR: 1.71, 95% CI: 1.17-2.50, P=0.007). This practise is common where sanitation infrastructure is not available. The most common reason for this practice is poverty which makes it a challenge to build toilets. The 'Swachh Bharat Abhiyan' is a government-led programme which provides funds for villages to construct toilets and thus prevent open defecation.
Children drinking water from an open well were found to have a higher prevalence of infection than those who had access to tap water (OR: 2.46, 95% CI: 1.67-3.62, P= <0.0001). This pattern of prevalence of infection has been reported in different studies (Wani et al., 2007;Bisht et al., 2011;Awasthi et al., 2008). Lack of clean drinking water, poor hygiene and improper waste disposal are important factors contributing to intestinal parasitism. Therefore, improvement in environmental sanitation, i.e. safe water supply and effective human and animal waste disposal are needed to lower parasitic infections. Children washing hands with soap and water after defecation showed a signi icantly lower prevalence of parasitic infection (OR: 0.573, 95% CI: 0.392-0.836, P=0.0041). Bisht et al. (2011);Awasthi et al. (2008); Tenali et al. (2018) also reported lower infection rates in children using soap and water. Health education on personal hygiene, such as the promotion of washing hands should be part of the educational curriculum in primary schools. No other variables were signi icantly associated with intestinal parasitosis.
Limitations of this study
Optimal laboratory diagnosis of intestinal parasitic infections requires the examination of three stool samples over several days. In our study, only one stool sample was examined for the detection of intestinal parasites which could have underesti-mated the prevalence. As our study was a hospitalbased study, it may not be a true representative of the general population. Due to lack of molecular techniques Entamoeba spp. could not be differentiated.
The strength of our study is that this is the irst study on prevalence and risk factors of IPIs among children from this region.
CONCLUSIONS
The indings of this study will help the health care professionals to get sensitized about the burden of IPIs and associated risk factors. Identifying and rectifying risk factors by creating awareness are needed to prevent the spread of IPIs. Health awareness programmes about personal hygiene, hand washing, education for behavioural change and use of sanitary toilets would be crucial for effective control of IPIs. Periodic de-worming programmes should be implemented successfully in the community.
Con lict of Interest
The authors declare that they have no con lict of interest for this study.
Funding Support
The author declare that they have no funding support for this study. |
/** Converts a {@link PlaybackStateCompat} to {@link Player.State} */
@Player.State
public static int convertToPlaybackState(
@Nullable PlaybackStateCompat playbackStateCompat,
@Nullable MediaMetadataCompat currentMediaMetadata,
long timeDiffMs) {
if (playbackStateCompat == null) {
return Player.STATE_IDLE;
}
switch (playbackStateCompat.getState()) {
case PlaybackStateCompat.STATE_CONNECTING:
case PlaybackStateCompat.STATE_ERROR:
case PlaybackStateCompat.STATE_NONE:
case PlaybackStateCompat.STATE_STOPPED:
return Player.STATE_IDLE;
case PlaybackStateCompat.STATE_BUFFERING:
case PlaybackStateCompat.STATE_FAST_FORWARDING:
case PlaybackStateCompat.STATE_REWINDING:
case PlaybackStateCompat.STATE_SKIPPING_TO_NEXT:
case PlaybackStateCompat.STATE_SKIPPING_TO_PREVIOUS:
case PlaybackStateCompat.STATE_SKIPPING_TO_QUEUE_ITEM:
return Player.STATE_BUFFERING;
case PlaybackStateCompat.STATE_PLAYING:
return Player.STATE_READY;
case PlaybackStateCompat.STATE_PAUSED:
long duration = convertToDurationMs(currentMediaMetadata);
if (duration == C.TIME_UNSET) {
return Player.STATE_READY;
}
long currentPosition =
convertToCurrentPositionMs(playbackStateCompat, currentMediaMetadata, timeDiffMs);
return (currentPosition < duration) ? Player.STATE_READY : Player.STATE_ENDED;
default:
throw new IllegalStateException(
"Unrecognized PlaybackStateCompat: " + playbackStateCompat.getState());
}
} |
/**
* The default implementation simply modifies the Context {@link ClassLoader}
*
* @param callable the callable to be executed "within" the context of this process application.
* @return the result of the callback
* @throws Exception
*/
public <T> T execute(Callable<T> callable) throws ProcessApplicationExecutionException {
ClassLoader originalClassloader = ClassLoaderUtil.getContextClassloader();
ClassLoader processApplicationClassloader = getProcessApplicationClassloader();
try {
ClassLoaderUtil.setContextClassloader(processApplicationClassloader);
return callable.call();
} catch(Exception e) {
throw new ProcessApplicationExecutionException(e);
} finally {
ClassLoaderUtil.setContextClassloader(originalClassloader);
}
} |
import PrependBackground from './PrependBackground';
import Profile from './Profile';
import Eye from './Eye';
import EyeDisabled from './EyeDisabled';
import Check from './Check';
import Search from './Search';
import Close from './Close';
import CloseOutline from './CloseOutline';
import DownArrow from './DownArrow';
import Download from './Download';
import File from './File';
import Delete from './Delete';
import TagClose from './TagClose';
import Hamburger from './Hamburger';
import Plus from './Plus';
export { DownArrow, Download, Close, Check, CloseOutline, Search, Eye, EyeDisabled, File, PrependBackground, Profile, Delete, TagClose, Plus, Hamburger, };
|
<gh_stars>1-10
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_SHELL_LAYOUT_TEST_CONTROLLER_H_
#define CONTENT_SHELL_LAYOUT_TEST_CONTROLLER_H_
#include "content/public/renderer/render_view_observer.h"
namespace content {
// This is the renderer side of the layout test controller.
class LayoutTestController : public RenderViewObserver {
public:
explicit LayoutTestController(RenderView* render_view);
virtual ~LayoutTestController();
// RenderViewObserver implementation.
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
virtual void DidClearWindowObject(WebKit::WebFrame* frame) OVERRIDE;
virtual void DidFinishLoad(WebKit::WebFrame* frame) OVERRIDE;
private:
// Message handlers.
void OnCaptureTextDump(bool as_text, bool printing, bool recursive);
void OnCaptureImageDump(const std::string& expected_pixel_hash);
DISALLOW_COPY_AND_ASSIGN(LayoutTestController);
};
} // namespace content
#endif // CONTENT_SHELL_LAYOUT_TEST_CONTROLLER_H_
|
package swagger
import (
"github.com/go-openapi/spec"
types "github.com/Soontao/go-mysql-api/types"
)
func GenSwaggerFromDBMetadata(dbMetadata *types.DataBaseMetadata) (s *spec.Swagger) {
s = &spec.Swagger{}
s.SwaggerProps = spec.SwaggerProps{}
s.Swagger = "2.0"
s.Schemes = []string{"http"}
s.Tags = GetTagsFromDBMetadata(dbMetadata)
s.Info = NewSwaggerInfo(dbMetadata, "version 1")
s.Definitions = SwaggerDefinationsFromDabaseMetadata(dbMetadata)
s.Paths = &spec.Paths{Paths: SwaggerPathsFromDatabaseMetadata(dbMetadata)}
return
}
|
Diabetes Link: Platform for Self-Control and Monitoring People with Diabetes
Diabetes Mellitus (DM) is a chronic disease characterized by an increase in blood glucose (sugar) above normal levels and it appears when human body is not able to produce enough insulin to cover the peripheral tissue demand. Nowadays, DM affects the 8.5% of the world's population and, even though no cure for it has been found, an adequate monitoring and treatment allow patients to have an almost normal life. This paper introduces Diabetes Link, a comprehensive platform for control and monitoring people with DM. Diabetes Link allows recording various parameters relevant for the treatment and calculating different statistical charts using them. In addition, it allows connecting with other users (supervisors) so they can monitor the controls. Even more, the extensive comparative study carried out reflects that Diabetes Link presents distinctive and superior features against other proposals. We conclude that Diabetes Link represents a broad and accessible tool that can help make day-to-day control easier and optimize the efficacy in DM control and treatment.
Introduction
According to the American Institute of Medical Sciences & Education, the term mobile health (mHealth) is used to refer to mobile technology focused on health care and medical information. There are currently more than 100,000 mobile applications associated with the health field. In the United States, 80% of medical professionals use mobile phones and medical applications, 25% of which are used for patient care .
Diabetes Mellitus (DM) is a chronic disease characterized by an increase in blood glucose (sugar) above normal levels . Affected people need ongoing and long-term treatment, as well as periodic self-monitoring of blood glucose (SMBG) mainly, but also of other clinical and metabolic parameters, such as body weight, food intake (measured mainly in carbohydrates), blood pressure, medications used, insulin dose and physical activity performed. Failure to adequately control the disease or comply with the prescribed treatments can not only have irreparable consequences on overall health, but it can also affect the quality of life of people with diabetes (namely, chronic complications affecting the eyes, kidneys and heart, among other organs; as well as psychological and mental damage). At the same time, it also affects patients from and economic and social perspective, due to the high costs of treatment and the impact on work discrimination .
Globally, according to the latest figures presented by the World Health Organization (WHO) in October 2018, the number of people with diabetes has increased significantly . In 1980, it affected 4.7% of the world's population, and this increased to 8.5% by 2014, with a total of 422 million people affected. Among people with diabetes, those with type 1 diabetes (T1D) and some with type 2 diabetes (T2D) receive daily insulin injections and perform SMBG to define the insulin dose they need to inject and optimize blood sugar control. This process is required to reduce the development and progression of the chronic complications of the disease and its negative impact in quality of life.
In this paper, we present Diabetes Link, a comprehensive platform to simplify the control and monitoring of people with DM. Diabetes Link combines a mobile application and a web portal, making the best of each platform. It allows recording various parameters relevant for the appropiate treatment and calculating different statistical charts using them. Also, it allows connecting with other users (supervisors) so they can monitor the controls. In addition, Diabetes Link offers all its functionality for free, and it is available on multiple platforms. Through an extensive comparative analysis, we show the distinctive and superior features of Diabetes Link against other available tools.
The remaining sections of this article are organized as follows: Section 2 describes the recommended treatment for people with DM. Section 3 introduces Diabetes Link, and Section 4 presents a comparative analysis with other available options. Finally, Section 5 summarizes the conclusions and and possible future lines of work.
Treatment for Diabetes Mellitus
So far, no cure for DM has been found, but sustained control and adequate treatment allow patients to lead an almost normal life. In addition, an active participation of the patients in the control and treatment of their disease is required to achieve this goal.
Treatment is based on four pillars -education, healthy meal plan, regular practice of physical activity, and various medications (oral antidiabetic drugs and insulin if required). It is very important that people with diabetes keep their condition under continuous and tight control and adhere to their prescribed treatment throughout their lives. In addition, depending on patient and disease severity, different clinical and metabolic parameters should be monitored, such as body weight, blood glucose, blood pressure, the amount of ingested carbohydrates, and physical activity performed. All these parameters have an impact on the long-term level of control and the simultaneous monitoring prevents the development/progression of the chronic complications that deteriorate quality of life and increase their costs of care .
Recording the various parameters associated with the treatment allows physicians to monitor patient evolution over time and to adjust the treatment accordingly in order to optimize results. In that sense, the ultimate goal is that the patient can maintain certain degree of stability.
The lack of an adequate control of the disease, together with non-adherence to prescribed treatments, leads to the development and progression of the chronic complications of the disease. They affect various organs such as the retina, kidneys, and cardiovascular system, decreasing their quality of life and their psychophysical ability as well as increasing their costs of care. Equally important, the decrease in psychophysical capacity also affects the ability to work, with the consequent socio-economic impact.
Work Methodology
To analyze the potential of the proposal and subsequently define its scope, clinical researchers from the CENEXA (UNLP-CONICET-CeAs CICPBA) 4 were contacted, due to their long career devoted to diabetes epidemiology, care programmes and derived costs. Their advice allowed us to learn about basic concepts of the disease and multiple aspects of its treatment. In addition, they emphasized the importance of keeping an adequate record of relevant data to achieve a good metabolic control.
Two physicians specialized in DM (with experience in therapeutic education of people with diabetes and co-authors of a manual oriented to the complementation of this activity ) were also interviewed. They provided useful information related to the statistical indicators that specialists frequently analyze when assessing the status of a patient and adjusting their treatment.
Finally, this development phase was complemented with a state-of-the-art study of mobile applications oriented to diabetes, which allowed us to discover possible uncovered needs in the area. It is important to remark that this study was repeated once again after the platform was released to carry out the comparative analysis of Section 4.
Requirements Analysis and Design
For the first release of Diabetes Link, a set of functional and non-functional requirements of the platform was agreed among all the participants. Requirements analysis and design modelling were required phases in the plataform development to guarantee the quality of the final product. Table 1 shows the functional requirements of Diabetes Link in a simplified manner. Fig. 1 shows the use cases model of Diabetes Link. It is important to note that as these functional requirements are fine-grained, it was possible to translate each one into a particular use case. Table 2 shows the non-functional requirements of Diabetes Link.
Fig. 1: Use cases
Architecture The platform can be accessed through a mobile application (available now for Android 5 and soon for iOS), and/or a web application 6 . Figure 2 shows a general model of service-oriented architecture. Record of relevant information for metabolic control: blood glucose measurements, carbohydrates intake and injected insulin. For each variable, the time of day (before/after breakfast/lunch/snack/dinner) must be included, and additional comments can be added to help understand the information entered FR06 Record of medications FR07 Record of physical activity (detailing intensity and duration) FR08 Record of body weight FR09 Record of blood pressure FR10 Analysis of the evolution of blood glucose FR11 Analysis of the evolution of body weight and BMI FR12 Analysis of the evolution of blood pressure FR13 Weekly summary of daily records detailing, for each day and meal, physical activity, carbohydrates intake, and blood glucose and injected insulin measurements before and after each intake FR14 Supervisor search FR15 Association/Dissociation of supervisors FR16 List of supervisor users FR17 Access to supervised user profile FR18 Access to the FAQs section about DM. There, patients can read about the disease, including its causes, consequences, and specifications about treatment goals. FR19 Setting target values for blood glucose and blood pressure to customize the statistical analysis FR20 Support for different units of measurement: User can choose their preferred units of measure for blood glucose (mg/dL or mmol/L) and weight (kg or lbs) FR21 Support for different languages The mobile application is used for both supervised and supervisor users. It was developed using web technologies (HTML5, CSS3 and Javascript) and the frameworks Angular 6 7 and Ionic v3 8 . The latter, on its behalf, uses Apache Cordova 9 for packaging web solutions in modules that can be later installed in mobile devices. It is for that reason that the mobile application of Diabetes Link can be categorized as a multi-platform, hybrid one . Non-functional Requirement NFR01 Security. The system must ensure all information of the registered end users are secured and not accessible by other party. NFR02 Security. The system should back up its data every 12 hours and the copies must be stored in a secure off-site location NFR03 Usability. The system should provide a systematic, simple and user-friendly interfaces. NFR04 Usability. The system should provide internationalization support (at least, English and Spanish). NFR05 Platforms Constraint. The mobile application should work under Android and iOS platforms. Also, a web application is needed for supervisors access. NFR06 The system must have a "Terms & conditions" section. Nowadays, Android and iOS are the main mobile operating systems. The mobile application of Diabetes Link is ready to work on both of them due to its multi-platform, hybrid feature. In that sense, the Android version was released first allowing Diabetes Link to cover more than 70% of the market share . On its behalf, the iOS version will be released next.
Most of the mobile application code could be reused for the development of a web application, which is now only available for supervisor users. However, supervised users will be able to access to it in the near future.
Both mobile and web applications communicate through the HTTP protocol using an API developed with Node.js 10 and the framework Express 11 . Finally, the data is managed using a MySQL database 12 . Fig. 3-6 show the implementation of several functional requirements, that were described in Table 1.
Comparative Analysis of Mobile Applications for Diabetes Monitoring
In this section, the criteria used to survey mobile applications for DM are described, and the results found are analyzed.
Search and Selection Criteria
The application search and selection process for our comparative analysis was carried out following guidelines proposed in similar studies . The study focused just on the Android operating system due to two reasons: first, Android is currently the most popular option, having more than 70% of the market share ; second, even though the mobile application of Diabetes Link will be soon available in iOS, now it is just present in Android. Today, Google Play does not offer filters to apply to search results. In addition, search terms are matched against app title and/or description, which usually leads to false hits, sometimes caused by spam techniques. To ensure that our analysis is representative, the search on Google Play was carried out on a specific date (Feb. 18, 2020), and all apps found were recorded. The phrase "diabetes control" was used since it is sufficiently general to ensure that every relevant app is detected. As a result, 246 applications were listed (incognito mode on). To be included in the analysis, an application must meet the following characteristics: -It must offer functionality that facilitates self-monitoring and control by people with diabetes; -It must allow blood glucose registration as a minimum requirement; -It must offer Spanish or English language interfaces.
After filtering out those apps that did not meet these requirements, 75 applications remained 13 . In order to evaluate these applications, the first 10 were selected according to three criteria: (1) greater popularity (order of appearance on results list); (2) higher score; and (3) greater number of downloads. The 3 partial listings were combined to obtain a single final one. In total, 22 applications were reviewed (30% of the total).
Comparative Analysis
After selecting the applications for the comparative analysis, their primary features were surveyed and analyzed. We have considered previous similar studies to determine the feature selection criteria. This comparison allows to quickly and easily see their strengths and weaknesses. Table 3 presents the main features of each app regarding Google Play information (order of appearence (#), number of downloads, score and version), web access support, its adquisition cost, its communication features, and if it offers diabetes information. First of all, it can be noted that just 32% of the apps offers web access. As described in Section 3, Diabetes Link is cross-platform and both mobile and web accesses are supported. The former becomes more significant at the time of analizying the information and statistical graphics, since its more user-friendly view.
In relation to adquisition costs, 78% of the applications studied require paying a monthly or annual fee to access advanced features (for instance, calculating statistics based on the information entered, adjusting target values, exporting reports or sending them by e-mail, supporting connectivity, among others). As regards connectivity, just four applications (18%) offer this star feature but only one does it for free. Other four applications do not offer any feature for communication support while the rest (14 apps) rely on generating PDF/XLS reports or sending them by e-mail. Diabetes Link, on its behalf, supports connectivity and offers all features for free. Table 4 summarizes the funcionality features of each application regarding data register and statistical analysis. Each app was surveyed to determine if it supports recording blood glucose, insulin, carbo-hydrates, body weight, blood pressure, medication, and physical activity. Additionally, wether the application analyzes blood glucose, body weight, and blood pressure data or not. Last, if it offers a tabular summary of registered data or not.
Between 59% and 82% of the selected applications allow recording measurements for blood glucose, insulin, carbohydrate intake, physical activity, food and medications intake. In addition, 77% allow recording body weight, and less than 73% allow recording blood pressure. As for the ability of adding labels or notes to the records, all applications offer this feature. Diabetes Link, on the other hand, allows recording of all of these measurements.
All of the applications that were reviewed offer statistical charts/tables for blood glucose measurements. As regards the other parameters, the percentages of applications that analyze them are 59% and 41%, they correspond to body weight and blood pressure, respectively. Furthermore, only 27% are capable of generating summary tables to report all recorded values. In contrast, Diabetes Link generates statistics for all these parameters, as well as a weekly summary tables for blood glucose, insulin and carbohydrate intake measurements, as well as physical activity done. It should be noted that the idea of adding these weekly summaries was suggested by the physicians during their interviews. They stated that they usually ask their patients to provide written records (diary) with this information to analyze patient status and adjust treatment accordingly. From Tables 3 and 4, it can be observed that none of the applications provides information about diabetes, statistics and connection with monitors simultaneously for free. In that context, Diabetes Link sets itself apart by providing all these features at no charge.
Finally, Table 5 shows the customization features of each application considering user language, target values and units of measurement. First, 22% of the applications does not include multi-language support. Having this feature allows Diabetes Link to offer an expanded reach, which means more people can use it. Both target values and units of measurement can be configured in most applications; in particular, 86% for the former and 82% for the latter. Diabetes Link support these two configuration options allowing users to customize their level of control and preferred units of measurement.
Limitations
Due to the great number of existing diabetes apps and the large amount of work required to revise them, some limitation of the comparative analysis were imposed. First, the review study just considered the Android OS. Although Android has more than 70% of the market share , currently available mobile applications for other OS's (especially iOS) were not considered.
In addition, the comparative analysis carried out only gathered the presence or absence of a given feature, as a way of simplifying the large collection task. In that sense, neither the quality of functions nor their effectiveness were evaluated. However, useful information could still be extracted.
Conclusions and Future Work
Adequate diabetes control is fundamental to improve the quality of life of people who suffer from this disease. This paper presented Diabetes Link, a comprehensive platform to simplify the control and monitoring of people with DM. The exhaustive comparative analysis carried out shows that Diabetes Link presents distinctive and superior features against other current proposals. In particular, we can highlight it is cross-platform, it supports connectivity, and it allows users to record/analyze various parameters relevant for the appropiate treatment (all for free). It is for that reason that Diabetes Link is expected to help make dayto-day control easier and optimize the efficacy in DM control and treatment.
Future work focuses on the extension of the comparative analysis to include two aspects: first, considering advanced features like IoT integration; second, considering mobile applications from iOS, especially when the iOS version of Diabetes Link is available. |
// only care about string,int,float
func (v *rsVal) UnmarshalJSON(b []byte) error {
if bytes.Equal(b, []byte("null")) {
return nil
}
if b[0] == '"' {
v.typ = "string"
} else if bytes.Contains(b, []byte(".")) {
v.typ = "float32"
} else {
v.typ = "int"
}
return nil
} |
.
Fluorescence characteristics of DNA-specific dyes of bis-benzimidazole type in a wide range of pH and r = C/P were investigated. Fluorescence spectra of DNA complexes with bis-benzimidazoles have elements of a structure, which may result from a superposition of the spectra of dye molecules in different protonization group states that form different types of complexes with DNA. Experimental data do not contradict the idea of bis-benzimidazole dye binding into the minor groove of DNA. Bis-benzimide molecules in the deprotonization state have a major affinity to DNA. |
<filename>src/utils/faker.go
package utils
import (
"math/rand"
"time"
"github.com/consensys/quorum-hashicorp-vault-plugin/src/vault/entities"
"github.com/consensys/quorum/common"
)
func FakeETHAccount() *entities.ETHAccount {
return &entities.ETHAccount{
Address: common.HexToAddress(randHexString(12)).String(),
PublicKey: common.HexToHash(randHexString(12)).String(),
CompressedPublicKey: common.HexToHash(randHexString(12)).String(),
Namespace: "_",
}
}
func FakeZksAccount() *entities.ZksAccount {
return &entities.ZksAccount{
Algorithm: entities.EDDSA,
Curve: entities.Babyjubjub,
PublicKey: "<KEY>",
PrivateKey: "<KEY>",
Namespace: "_",
}
}
func FakeKey() *entities.Key {
return &entities.Key{
Algorithm: entities.EDDSA,
Curve: entities.Babyjubjub,
PublicKey: "<KEY>
PrivateKey: "<KEY>",
Namespace: "_",
ID: "my-key",
Tags: map[string]string{
"tag1": "tagValue1",
"tag2": "tagValue2",
},
Version: 1,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
}
func randHexString(n int) string {
var letterRunes = []rune("abcdef0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.