repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
alex2ching/QQConnector
|
WPFTencentQQ/CCodecWarpper/RespEncounterInfo.h
|
<filename>WPFTencentQQ/CCodecWarpper/RespEncounterInfo.h
#pragma once
#include"PacketType.h"
#include"../JceProtocol/JceStruct.h"
#include"../JceProtocol/JCELong.h"
#include"../JceProtocol/JCEShort.h"
#include"../JceProtocol/JCEChar.h"
#include"VipBaseInfo.h"
#include"RishState.h"
class CRespEncounterInfo:public JCE::CJceStruct
{
public:
CRespEncounterInfo(void);
virtual ~CRespEncounterInfo(void);
public:
JCE::JCELong lEctID;
JCE::JCEInt iDistance;
JCE::JCEInt lTime;
JCE::JCEString strDescription;
JCE::JCEShort wFace;
JCE::JCEChar cSex;
JCE::JCEChar cAge;
JCE::JCEString strNick;
JCE::JCEChar cGroupId;
JCE::JCEString strPYFaceUrl;
JCE::JCEString strSchoolName;
JCE::JCEString strCompanyName;
JCE::JCEString strPYName;
JCE::JCEInt nFaceNum;
JCE::JCEString strCertification;
JCE::JCEShort shIntroType;
JCE::JCEByteArray vIntroContent;
JCE::JCEByteArray vFaceID;
JCE::JCEInt eMerchantType;
JCE::JCEInt eUserIdentityType;
JCE::JCEInt iVoteIncrement;
JCE::JCEChar bIsSingle;
JCE::JCEInt iLat;
JCE::JCEInt iLon;
JCE::JCEInt iRank;
JCE::JCELong lTotalVisitorsNum;
JCE::JCEChar cSpecialFlag;
CVipBaseInfo vipBaseInfo;
CRishState richState;
JCE::JCEByteArray sig;
JCE::JCEString enc_id;
JCE::JCEString uid;
JCE::JCEChar is_trav;
JCE::JCEChar constellation;
JCE::JCEInt profession_id;
JCE::JCEByteArray vDateInfo;
JCE::JCEChar marriage;
JCE::JCELong tiny_id;
JCE::JCEInt common_face_timestamp;
JCE::JCEInt stranger_face_timestamp;
JCE::JCEChar authFlag;
JCE::JCEInt iVoteNum;
JCE::JCEChar god_flag;
JCE::JCEInt charm;
JCE::JCEInt charm_level;
JCE::JCEChar watch_color;
JCE::JCEChar charm_shown;
JCE::JCEByteArray vInterestInfo;
public:
void readFrom(CJceInputStream& paramd);
void writeTo(CJceOutputStream& paramd);
public:
unsigned int type(){return StructRespEncounterInfo;};
};
|
ViaOA/oa-web
|
src/test/java/test/hifive/model/oa/propertypath/PointsRecordPP.java
|
<filename>src/test/java/test/hifive/model/oa/propertypath/PointsRecordPP.java
// Generated by OABuilder
package test.hifive.model.oa.propertypath;
import test.hifive.model.oa.*;
public class PointsRecordPP {
private static EmailPPx email;
private static InspireOrderPPx inspireOrder;
private static PointsCoreValuePPx pointsCoreValue;
private static PointsRequestPPx pointsRequest;
private static EmployeePPx pointsToEmployee;
private static ProgramPPx pointsToProgram;
public static EmailPPx email() {
if (email == null) email = new EmailPPx(PointsRecord.P_Email);
return email;
}
public static InspireOrderPPx inspireOrder() {
if (inspireOrder == null) inspireOrder = new InspireOrderPPx(PointsRecord.P_InspireOrder);
return inspireOrder;
}
public static PointsCoreValuePPx pointsCoreValue() {
if (pointsCoreValue == null) pointsCoreValue = new PointsCoreValuePPx(PointsRecord.P_PointsCoreValue);
return pointsCoreValue;
}
public static PointsRequestPPx pointsRequest() {
if (pointsRequest == null) pointsRequest = new PointsRequestPPx(PointsRecord.P_PointsRequest);
return pointsRequest;
}
public static EmployeePPx pointsToEmployee() {
if (pointsToEmployee == null) pointsToEmployee = new EmployeePPx(PointsRecord.P_PointsToEmployee);
return pointsToEmployee;
}
public static ProgramPPx pointsToProgram() {
if (pointsToProgram == null) pointsToProgram = new ProgramPPx(PointsRecord.P_PointsToProgram);
return pointsToProgram;
}
public static String id() {
String s = PointsRecord.P_Id;
return s;
}
public static String created() {
String s = PointsRecord.P_Created;
return s;
}
public static String points() {
String s = PointsRecord.P_Points;
return s;
}
public static String toDiscretionary() {
String s = PointsRecord.P_ToDiscretionary;
return s;
}
public static String reason() {
String s = PointsRecord.P_Reason;
return s;
}
public static String comment() {
String s = PointsRecord.P_Comment;
return s;
}
public static String event() {
String s = PointsRecord.P_Event;
return s;
}
public static String custom1() {
String s = PointsRecord.P_Custom1;
return s;
}
public static String custom2() {
String s = PointsRecord.P_Custom2;
return s;
}
public static String custom3() {
String s = PointsRecord.P_Custom3;
return s;
}
public static String engaged() {
String s = PointsRecord.P_Engaged;
return s;
}
}
|
thekerrlab/brainstaves
|
brainstaves/bs_recordmindwave.py
|
<gh_stars>0
'''
Record data from headset. Protocol:
./bt_pair
./bt_read
./bt_record # calls this file
'''
import os
import sys
import time
import pylab as pl
import bsmindwave as bsmw
if len(sys.argv)>1:
name = sys.argv[1]
else:
print('Setting default')
name = 'v1'
mapping = {'v1': '00:81:F9:08:A1:72',
'v2': '00:81:F9:29:BA:98',
'va': '00:81:F9:29:EF:80',
'vc': 'C4:64:E3:EA:75:6D',}
mapping2 = {'v1': 'rfcomm0',
'v2': 'rfcomm1',
'va': 'rfcomm2',
'vc': 'rfcomm3',}
secs = ['B','C','D','E','F','G','H']
count = 0
mw = bsmw.Mindwave(port='/dev/%s' % mapping2[name])
mw.start()
for sec in secs:
count += 1
print('\n'*10)
print('STARTING %s %s (%s/%s)' % (sec, name, count, len(secs)))
MAC = mapping[name]
maxtime = 20
delay = 0.02
filename = '../data/live/rawdata-%s-%s.dat' % (sec, name)
maxcount = int(maxtime/delay)
print('Recording for %s s...' % maxtime)
data = []
origtime = time.time()
hz = int(1/delay)
for i in range(maxcount):
if not i%hz:
print('...%s/%s' % (i+1, maxcount))
data.append(str(mw.rawValue))
elapsed = time.time() - (origtime + i*delay)
remaining = delay-elapsed
if remaining>0:
pl.pause(remaining)
else:
print('Not pausing because time is negative (%s vs %s)' % (delay, elapsed))
with open(filename,'w') as f:
f.write('\n'.join(data))
print('Stopping...')
mw.stop()
print('Done.')
|
jwilger/racing_on_rails
|
test/integration/events_test.rb
|
# frozen_string_literal: true
require_relative "racing_on_rails/integration_test"
# :stopdoc:
class EventsTest < RacingOnRails::IntegrationTest
test "index" do
Timecop.freeze(Time.zone.local(2013, 3)) do
FactoryBot.create(:event)
FactoryBot.create(:event)
get "/events"
assert_redirected_to schedule_path
get "/events.xml"
assert_response :success
xml = Hash.from_xml(response.body)
assert_not_nil xml["single_day_events"], "Should have :single_day_events root element in #{xml}"
get "/events.json"
assert_response :success
assert_equal 2, JSON.parse(response.body).size, "Should have JSON array"
end
end
end
|
peroxy/starsky
|
src/main/java/com/starsky/backend/repository/UserRepository.java
|
package com.starsky.backend.repository;
import com.starsky.backend.domain.user.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
import java.util.Optional;
@RepositoryRestResource(exported = false)
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmailAndEnabled(String email, boolean enabled);
Optional<User> findByEmailAndEnabledAndManuallyAdded(String email, boolean enabled, boolean manuallyAdded);
Optional<User> findByIdAndEnabled(long id, boolean enabled);
List<User> findAllByParentUserAndEnabled(User parentUser, boolean enabled);
Optional<User> findByIdAndParentUserAndEnabled(long id, User owner, boolean enabled);
boolean existsAllByIdInAndParentUserAndEnabled(Long[] ids, User owner, boolean enabled);
}
|
bantonsson/sbt
|
compile/inc/src/main/scala/sbt/inc/Changes.scala
|
/* sbt -- Simple Build Tool
* Copyright 2010 <NAME>
*/
package sbt
package inc
import xsbt.api.NameChanges
import java.io.File
final case class InitialChanges(internalSrc: Changes[File], removedProducts: Set[File], binaryDeps: Set[File], external: APIChanges[String])
final class APIChanges[T](val modified: Set[T], val names: NameChanges)
{
override def toString = "API Changes: " + modified + "\n" + names
}
trait Changes[A]
{
def added: Set[A]
def removed: Set[A]
def changed: Set[A]
def unmodified: Set[A]
}
sealed abstract class Change(val file: File)
final class Removed(f: File) extends Change(f)
final class Added(f: File, newStamp: Stamp) extends Change(f)
final class Modified(f: File, oldStamp: Stamp, newStamp: Stamp) extends Change(f)
|
damicoedoardo/NNMF
|
RecSysFramework/Recommender/SLIM/BPR/SLIM_BPR.py
|
<filename>RecSysFramework/Recommender/SLIM/BPR/SLIM_BPR.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 28 June 2017
@author: XXX
"""
import sys
import time
import numpy as np
from scipy.special import expit
from RecSysFramework.Recommender import Recommender
class SLIM_BPR(Recommender):
"""
This class is a python porting of the BPRSLIM algorithm in MyMediaLite written in C#
The code is identical with no optimizations
"""
def __init__(self, URM_train, lambda_i = 0.0025, lambda_j = 0.00025, learning_rate = 0.05):
super(SLIM_BPR, self).__init__()
self.URM_train = URM_train
self.n_users = URM_train.shape[0]
self.n_items = URM_train.shape[1]
self.lambda_i = lambda_i
self.lambda_j = lambda_j
self.learning_rate = learning_rate
self.normalize = False
self.sparse_weights = False
def update_factors(self, user_id, pos_item_id, neg_item_id):
# Calculate current predicted score
userSeenItems = self.URM_train[user_id].indices
prediction = 0
for userSeenItem in userSeenItems:
prediction += self.S[pos_item_id, userSeenItem] - self.S[neg_item_id, userSeenItem]
x_uij = prediction
logisticFunction = expit(-x_uij)
# Update similarities for all items except those sampled
for userSeenItem in userSeenItems:
# For positive item is PLUS logistic minus lambda*S
if(pos_item_id != userSeenItem):
update = logisticFunction - self.lambda_i*self.S[pos_item_id, userSeenItem]
self.S[pos_item_id, userSeenItem] += self.learning_rate*update
# For positive item is MINUS logistic minus lambda*S
if (neg_item_id != userSeenItem):
update = - logisticFunction - self.lambda_j*self.S[neg_item_id, userSeenItem]
self.S[neg_item_id, userSeenItem] += self.learning_rate*update
def fit(self, epochs=15):
"""
Train SLIM wit BPR. If the model was already trained, overwrites matrix S
:param epochs:
:return: -
"""
# Initialize similarity with random values and zero-out diagonal
self.S = np.random.random((self.n_items, self.n_items)).astype('float32')
self.S[np.arange(self.n_items),np.arange(self.n_items)] = 0
start_time_train = time.time()
for currentEpoch in range(epochs):
start_time_epoch = time.time()
self.epoch_iteration()
print("Epoch {} of {} complete in {:.2f} minutes".format(currentEpoch+1, epochs, float(time.time()-start_time_epoch)/60))
print("Train completed in {:.2f} minutes".format(float(time.time()-start_time_train)/60))
# The similarity matrix is learnt row-wise
# To be used in the product URM*S must be transposed to be column-wise
self.W = self.S.T
del self.S
def epoch_iteration(self):
# Get number of available interactions
numPositiveIteractions = self.URM_train.nnz
start_time = time.time()
# Uniform user sampling without replacement
for numSample in range(numPositiveIteractions):
user_id, pos_item_id, neg_item_id = self.sample_triple()
self.update_factors(user_id, pos_item_id, neg_item_id)
if(numSample % 5000 == 0):
print("Processed {} ( {:.2f}% ) in {:.4f} seconds".format(numSample,
100.0* float(numSample)/numPositiveIteractions,
time.time()-start_time))
sys.stderr.flush()
start_time = time.time()
def sample_user(self):
"""
Sample a user that has viewed at least one and not all items
:return: user_id
"""
while(True):
user_id = np.random.randint(0, self.n_users)
numSeenItems = self.URM_train[user_id].nnz
if(numSeenItems >0 and numSeenItems<self.n_items):
return user_id
def sample_item_pair(self, user_id):
"""
Returns for the given user a random seen item and a random not seen item
:param user_id:
:return: pos_item_id, neg_item_id
"""
userSeenItems = self.URM_train[user_id].indices
pos_item_id = userSeenItems[np.random.randint(0,len(userSeenItems))]
while(True):
neg_item_id = np.random.randint(0, self.n_items)
if(neg_item_id not in userSeenItems):
return pos_item_id, neg_item_id
def sample_triple(self):
"""
Randomly samples a user and then samples randomly a seen and not seen item
:return: user_id, pos_item_id, neg_item_id
"""
user_id = self.sample_user()
pos_item_id, neg_item_id = self.sample_item_pair(user_id)
return user_id, pos_item_id, neg_item_id
|
xlnwel/grl
|
algo/sacd/nn.py
|
<reponame>xlnwel/grl
import logging
import numpy as np
import tensorflow as tf
from tensorflow_probability import distributions as tfd
from utility.rl_utils import epsilon_greedy, epsilon_scaled_logits
from core.module import Module, Ensemble
from nn.func import mlp
from algo.sac.nn import Temperature
from algo.dqn.nn import Encoder, Q
logger = logging.getLogger(__name__)
class Actor(Module):
def __init__(self, config, action_dim, name='actor'):
super().__init__(name=name)
config = config.copy()
self._action_dim = action_dim
prior = np.ones(action_dim, dtype=np.float32)
prior /= np.sum(prior)
self.prior = tf.Variable(prior, trainable=False, name='prior')
self._epsilon_scaled_logits = config.pop('epsilon_scaled_logits', False)
self._layers = mlp(
**config,
out_size=action_dim,
out_dtype='float32',
name=name)
@property
def action_dim(self):
return self._action_dim
def call(self, x, evaluation=False, epsilon=0, temp=1):
self.logits = logits = self._layers(x)
if evaluation:
temp = tf.where(temp == 0, 1e-9, temp)
logits = logits / temp
dist = tfd.Categorical(logits)
action = dist.sample()
else:
if self._epsilon_scaled_logits and \
(isinstance(epsilon, tf.Tensor) or epsilon):
self.logits = epsilon_scaled_logits(logits, epsilon, temp)
else:
self.logits = logits / temp
dist = tfd.Categorical(self.logits)
action = dist.sample()
if not self._epsilon_scaled_logits and \
(isinstance(epsilon, tf.Tensor) or epsilon):
action = epsilon_greedy(action, epsilon, True, action_dim=self.action_dim)
self._dist = dist
self._action = action
return action
def train_step(self, x):
x = self._layers(x)
pi = tf.nn.softmax(x)
logpi = tf.math.log(tf.maximum(pi, 1e-8)) # bound logpi to avoid numerical instability
return pi, logpi
def update_prior(self, x, lr):
self.prior.assign_add(lr * (x - self.prior))
def compute_prob(self):
# do not take into account epsilon and temperature to reduce variance
prob = self._dist.prob(self._action)
return prob
class SAC(Ensemble):
def __init__(self, config, *, model_fn=None, env, **kwargs):
model_fn = model_fn or create_components
super().__init__(
model_fn=model_fn,
config=config,
env=env,
**kwargs)
@tf.function
def action(self, x, evaluation=False, epsilon=0, temp=1., return_stats=False, return_eval_stats=False, **kwargs):
if x.shape.ndims % 2 != 0:
x = tf.expand_dims(x, axis=0)
x = self.encoder(x)
action = self.actor(x, evaluation=evaluation, epsilon=epsilon, temp=temp)
terms = {}
if return_eval_stats:
action, terms = action
q = self.q(x)
q = tf.squeeze(q)
idx = tf.stack([tf.range(action.shape[0]), action], -1)
q = tf.gather_nd(q, idx)
action_best_q = tf.argmax(q, 1)
action_best_q = tf.squeeze(action_best_q)
terms = {
'action': action,
'action_best_q': action_best_q,
'q': q,
}
elif return_stats:
q = self.q(x, action=action)
q = tf.squeeze(q)
terms['q'] = q
if self.reward_kl:
kl = -tfd.Categorical(self.actor.logits).entropy()
if self.temperature.type == 'schedule':
_, temp = self.temperature(self._train_step)
elif self.temperature.type == 'state':
raise NotImplementedError
else:
_, temp = self.temperature()
kl = temp * kl
terms['kl'] = kl
action = tf.squeeze(action)
return action, terms
@tf.function
def value(self, x):
if x.shape.ndims % 2 != 0:
x = tf.expand_dims(x, axis=0)
assert x.shape.ndims == 4, x.shape
x = self.encoder(x)
value = self.q(x)
value = tf.squeeze(value)
return value
def create_components(config, env):
assert env.is_action_discrete
config = config.copy()
action_dim = env.action_dim
encoder_config = config['encoder']
actor_config = config['actor']
q_config = config['q']
temperature_config = config['temperature']
models = dict(
encoder=Encoder(encoder_config, name='encoder'),
actor=Actor(actor_config, action_dim),
q=Q(q_config, action_dim, name='q'),
target_encoder=Encoder(encoder_config, name='target_encoder'),
target_actor=Actor(actor_config, action_dim, name='target_actor'),
target_q=Q(q_config, action_dim, name='target_q'),
temperature=Temperature(temperature_config),
)
return models
def create_model(config, env, **kwargs):
return SAC(config=config, env=env, **kwargs)
|
techAi007/spring-boot
|
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/OptionsCapableConnectionFactory.java
|
<filename>spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/OptionsCapableConnectionFactory.java
/*
* Copyright 2012-2021 the original author or 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
*
* https://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.springframework.boot.r2dbc;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryMetadata;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Wrapped;
import org.reactivestreams.Publisher;
/**
* {@link ConnectionFactory} capable of providing access to the
* {@link ConnectionFactoryOptions} from which it was built.
*
* @author <NAME>
* @since 2.5.0
*/
public class OptionsCapableConnectionFactory implements Wrapped<ConnectionFactory>, ConnectionFactory {
private final ConnectionFactoryOptions options;
private final ConnectionFactory delegate;
/**
* Create a new {@code OptionsCapableConnectionFactory} that will provide access to
* the given {@code options} that were used to build the given {@code delegate}
* {@link ConnectionFactory}.
* @param options the options from which the connection factory was built
* @param delegate the delegate connection factory that was built with options
*/
public OptionsCapableConnectionFactory(ConnectionFactoryOptions options, ConnectionFactory delegate) {
this.options = options;
this.delegate = delegate;
}
public ConnectionFactoryOptions getOptions() {
return this.options;
}
@Override
public Publisher<? extends Connection> create() {
return this.delegate.create();
}
@Override
public ConnectionFactoryMetadata getMetadata() {
return this.delegate.getMetadata();
}
@Override
public ConnectionFactory unwrap() {
return this.delegate;
}
/**
* Returns, if possible, an {@code OptionsCapableConnectionFactory} by unwrapping the
* given {@code connectionFactory} as necessary. If the given
* {@code connectionFactory} does not wrap an {@code OptionsCapableConnectionFactory}
* and is not itself an {@code OptionsCapableConnectionFactory}, {@code null} is
* returned.
* @param connectionFactory the connection factory to unwrap
* @return the {@code OptionsCapableConnectionFactory} or {@code null}
* @since 2.5.1
*/
public static OptionsCapableConnectionFactory unwrapFrom(ConnectionFactory connectionFactory) {
if (connectionFactory instanceof OptionsCapableConnectionFactory) {
return (OptionsCapableConnectionFactory) connectionFactory;
}
if (connectionFactory instanceof Wrapped) {
Object unwrapped = ((Wrapped<?>) connectionFactory).unwrap();
if (unwrapped instanceof ConnectionFactory) {
return unwrapFrom((ConnectionFactory) unwrapped);
}
}
return null;
}
}
|
joshlyman/Josh-LeetCode
|
022_Generate_Parentheses.py
|
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
# remaining # of ( must be > # of )
path = []
results = []
self.dfs(path,results,0,0,n,n)
return results
# path, para,results, remain # of (, remain # of ), current # of (, current # of )
def dfs(self,path,results,leftCur,rightCur,leftRem,rightRem):
if leftRem < 0 or rightRem < 0:
return
if rightCur > leftCur:
return
if leftRem == 0 and rightRem == 0:
results.append("".join(path))
path.append("(")
self.dfs(path,results,leftCur+1,rightCur,leftRem-1,rightRem)
path.pop()
path.append(")")
self.dfs(path,results,leftCur,rightCur+1,leftRem,rightRem-1)
path.pop()
# https://www.jiuzhang.com/problem/generate-parentheses/
# https://leetcode.com/problems/generate-parentheses/solution/
# Time: O(4^n/sqrt(n))
# Space:O(4^n/sqrt(n))
|
koki0702/chainer0
|
chainer0/links/__init__.py
|
<filename>chainer0/links/__init__.py
from chainer0.links.linear import Linear
from chainer0.links.embed_id import EmbedID
from chainer0.links.simple_rnn import SimpleRNN
from chainer0.links.classifier import Classifier
|
CreepyCre/DimDoors
|
src/main/schematics/org/dimdev/dimdoors/util/schematic/v2/SchematicBiomePalette.java
|
package org.dimdev.dimdoors.util.schematic.v2;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.UnboundedMapCodec;
import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.world.biome.Biome;
public class SchematicBiomePalette {
public static final UnboundedMapCodec<Biome, Integer> CODEC = Codec.unboundedMap(BuiltinRegistries.BIOME, Codec.INT);
}
|
ginlime/narou
|
preset/ncode.syosetu.com/n2525bs/converter.rb
|
<reponame>ginlime/narou
# -*- coding: utf-8 -*-
#
# 対象小説情報
# タイトル: 魔剣ゾルディの女主人公とっかえひっかえ成長記録
# 作者: 木原ゆう
# URL: http://ncode.syosetu.com/n2525bs/
#
converter "n2525bs 魔剣ゾルディの女主人公とっかえひっかえ成長記録" do
def before(io, text_type)
super
io.string.gsub!(/(\/{2,})/) do
if $1.length == 3
"❤"
else
"❤❤"
end
end
io
end
def is_parameter_block?(line)
!!(line =~ /={2,}/)
end
def in_parameter_block?(line)
unless @in_parameter_block
if is_parameter_block?(line)
@in_parameter_block = true
return true
end
end
return false
end
def out_parameter_block?(line)
if @in_parameter_block
if is_parameter_block?(line)
@in_parameter_block = false
return true
end
end
return false
end
def after(io, text_type)
return io unless text_type == "body"
write_fp = StringIO.new
non_close_parameter = false
@in_parameter_block = false
io.each do |line|
line.rstrip!
if in_parameter_block?(line)
non_close_parameter = true
write_fp.puts("[#ここからパラメーター]")
next
end
if out_parameter_block?(line)
non_close_parameter = false
write_fp.puts("[#ここでパラメーター終わり]")
next
end
write_fp.puts(line)
end
if non_close_parameter
write_fp.puts("[#ここでパラメーター終わり]")
end
data = write_fp.string
data.lstrip!
data.gsub!(/\n\n([#ここからパラメーター])/m, "\n\\1")
data.gsub!(/([#ここでパラメーター終わり]\n\n)/m, "[#ここでパラメーター終わり]\n")
data.gsub!(" ❤", "❤")
write_fp
end
end
|
yangaoting/guns-dubbo-metting
|
guns-api/src/main/java/com/stylefeng/guns/api/film/FilmAsyncServiceApi.java
|
<filename>guns-api/src/main/java/com/stylefeng/guns/api/film/FilmAsyncServiceApi.java
package com.stylefeng.guns.api.film;
import com.stylefeng.guns.api.film.vo.ActorVo;
import com.stylefeng.guns.api.film.vo.FilmDescVo;
import com.stylefeng.guns.api.film.vo.ImgVo;
import java.util.List;
public interface FilmAsyncServiceApi {
//描述信息
FilmDescVo getFilmDesc(String filmId);
//电影图片
ImgVo getImgs(String filmId);
//导演信息
ActorVo getDectInfo(String filmId);
//演员信息
List<ActorVo> getActors(String filmId);
}
|
kn0t3k/kyrys
|
include/friend.hpp
|
<reponame>kn0t3k/kyrys<filename>include/friend.hpp<gh_stars>0
#pragma once
#include <reference.hpp>
namespace Kyrys {
/**
* @brief class Friend represents one user in user's friend list. This class obtain informations about friend as ID, IP adress(not neccesary), history of communication etc.
*
*/
class Friend {
private:
unsigned int m_ID; //ID of friend - primary key in database of all user's of Kyrys project
std::string m_nickname; //Nickname of friend
//std::string m_history_path; //Holds path to file with encrypted history of communication with friend
bool m_chatting; //This is flag if user Friend created handshake consisting from CHAT_REQUEST and accepting CHAT_RESPONSE
public:
//Constructors
Friend();
Friend(unsigned int ID);
Friend(unsigned int ID, const std::string &nickname);
//Setters
void clear();
void setChatting(bool m_chatting);
//Getters
unsigned int getID() const;
const string &getNickname() const;
bool isChatting() const;
};
}
|
uwplse/staccato
|
src/edu/washington/cse/instrumentation/resolution/MethodDescSelector.java
|
package edu.washington.cse.instrumentation.resolution;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import edu.washington.cse.instrumentation.TaintUtils;
public class MethodDescSelector implements MethodSpecGenerator<MethodSpec> {
private final String methodName, methodDescriptor;
private final boolean isPhosphor;
public MethodDescSelector(String methodName, String methodDescriptor, boolean isPhosphor) {
this.methodDescriptor = methodDescriptor;
this.methodName = methodName;
this.isPhosphor = isPhosphor;
}
public MethodDescSelector(CtMethod meth) {
this(meth.getName(), meth.getMethodInfo().getDescriptor(), false);
}
@Override
public Collection<MethodSpec> findMethods(CtClass theKlass, Set<CtClass> taintClasses) {
try {
return findMethodsThrow(theKlass, taintClasses);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Could not find specified method: " + methodName + ":" + methodDescriptor, e);
}
}
private Collection<MethodSpec> findMethodsThrow(CtClass theKlass, Set<CtClass> taintClasses) throws NotFoundException {
CtMethod meth = theKlass.getMethod(methodName, methodDescriptor);
List<MethodSpec> toRet = new ArrayList<>();
toRet.add(MethodSpec.ofMethod(meth, TaintUtils.extractTaintArgs(meth, taintClasses)));
if(!isPhosphor) {
return toRet;
}
String phosphorDesc = TaintUtils.transformPhosphorMeth(methodDescriptor);
if(phosphorDesc.equals(methodDescriptor)) {
return toRet;
}
CtMethod phosMeth = theKlass.getMethod(methodName + "$$PHOSPHORTAGGED", phosphorDesc);
toRet.add(MethodSpec.ofMethod(phosMeth, TaintUtils.extractTaintArgs(phosMeth, taintClasses)));
return toRet;
}
@Override
public String toString() {
return "MethodDescSelector [methodName=" + methodName
+ ", methodDescriptor=" + methodDescriptor + "]";
}
}
|
ScalablyTyped/SlinkyTyped
|
a/aws-sdk/src/main/scala/typingsSlinky/awsSdk/cloudsearchMod/BuildSuggestersRequest.scala
|
package typingsSlinky.awsSdk.cloudsearchMod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait BuildSuggestersRequest extends StObject {
var DomainName: typingsSlinky.awsSdk.cloudsearchMod.DomainName = js.native
}
object BuildSuggestersRequest {
@scala.inline
def apply(DomainName: DomainName): BuildSuggestersRequest = {
val __obj = js.Dynamic.literal(DomainName = DomainName.asInstanceOf[js.Any])
__obj.asInstanceOf[BuildSuggestersRequest]
}
@scala.inline
implicit class BuildSuggestersRequestMutableBuilder[Self <: BuildSuggestersRequest] (val x: Self) extends AnyVal {
@scala.inline
def setDomainName(value: DomainName): Self = StObject.set(x, "DomainName", value.asInstanceOf[js.Any])
}
}
|
ryanhs/graphql-koa-scripts
|
tests/e2e/test-server-simple/using-test.test.js
|
<gh_stars>0
const { UsingTestServer } = require('../../../src');
describe('using UsingTestServer(App, fn)', () => {
it(
'auto quit',
UsingTestServer(`${__dirname}/app.js`, async () => {
expect(1).toBe(1);
}),
);
it(
'try /qs',
UsingTestServer(`${__dirname}/app.js`, async ({ supertest }) => {
const response = supertest.get('/qs?foo=bar');
await expect(response).resolves.not.toThrow();
const { body } = await response;
expect(body).toMatchObject({ foo: 'bar' });
}),
);
it(
'try /healthcheck',
UsingTestServer(`${__dirname}/app.js`, async ({ supertest }) => {
const response = supertest.get('/ping');
await expect(response).resolves.not.toThrow();
const { text } = await response;
expect(new Date(text).toISOString()).toBe(text); // parse iso string and ok
}),
);
it(
'try graphql',
UsingTestServer(`${__dirname}/app.js`, async ({ apolloClients }) => {
const res = apolloClients['/graphql'].query({
query: '{ hello }',
});
await expect(res).resolves.toMatchObject({
data: {
hello: 'Awesome!',
},
});
}),
);
});
|
yuanice/aliyun-odps-java-sdk
|
odps-sdk-impl/odps-mapred-local/src/test/java/com/aliyun/odps/mapred/local/AllowNoInputPositive.java
|
<reponame>yuanice/aliyun-odps-java-sdk<filename>odps-sdk-impl/odps-mapred-local/src/test/java/com/aliyun/odps/mapred/local/AllowNoInputPositive.java
/*
* 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 com.aliyun.odps.mapred.local;
import java.io.IOException;
import org.junit.Test;
import com.aliyun.odps.OdpsException;
import com.aliyun.odps.local.common.WareHouse;
import com.aliyun.odps.mapred.JobClient;
import com.aliyun.odps.mapred.MapperBase;
import com.aliyun.odps.mapred.RunningJob;
import com.aliyun.odps.mapred.conf.JobConf;
import com.aliyun.odps.mapred.conf.SessionState;
import com.aliyun.odps.mapred.local.utils.TestUtils;
public class AllowNoInputPositive {
public static class Mapper1 extends MapperBase {
@Override
public void setup(TaskContext context) throws IOException {
System.err.println("Mapper1 running");
context.getCounter("MyCounters", "EnterSetup").increment(1);
}
}
public static void main(String[] args) throws OdpsException {
JobConf job1 = new JobConf();
job1.setMapperClass(Mapper1.class);
job1.setNumReduceTasks(0);
// job.setAllowNoInput(true); // new mr do not need this
RunningJob rj = JobClient.runJob(job1);
long counter = rj.getCounters().findCounter("MyCounters", "EnterSetup").getValue();
int expect = job1.getInt("odps.stage.mapper.num", 1);
if (counter != expect) {
throw new RuntimeException("Incorrect counter, expect: " + expect + ", get: " + counter);
}
}
@Test
public void test() throws Exception {
WareHouse wareHouse = WareHouse.getInstance();
String project = TestUtils.odps_test_mrtask;
TestUtils.setEnvironment(project);
new AllowNoInputPositive().main(new String[0]);
}
}
|
sravani-m/Web-Application-Security-Framework
|
tools/arachni/system/gems/gems/arachni-1.5.1/spec/arachni/framework/parts/platform_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
describe Arachni::Framework::Parts::Platform do
include_examples 'framework'
describe '#list_platforms' do
it 'returns information about all valid platforms' do
expect(subject.list_platforms).to eq({
'Operating systems' => {
unix: 'Generic Unix family',
linux: 'Linux',
bsd: 'Generic BSD family',
aix: 'IBM AIX',
solaris: 'Solaris',
windows: 'MS Windows'
},
'Databases' => {
sql: 'Generic SQL family',
access: 'MS Access',
db2: 'DB2',
emc: 'EMC',
firebird: 'Firebird',
frontbase: 'Frontbase',
hsqldb: 'HSQLDB',
informix: 'Informix',
ingres: 'IngresDB',
interbase: 'InterBase',
maxdb: 'SaP Max DB',
mssql: 'MSSQL',
mysql: 'MySQL',
oracle: 'Oracle',
pgsql: 'Postgresql',
sqlite: 'SQLite',
sybase: 'Sybase',
nosql: 'Generic NoSQL family',
mongodb: 'MongoDB'
},
'Web servers' => {
apache: 'Apache',
iis: 'IIS',
jetty: 'Jetty',
nginx: 'Nginx',
tomcat: 'TomCat',
gunicorn: 'Gunicorn',
},
'Programming languages' => {
asp: 'ASP',
aspx: 'ASP.NET',
java: 'Java',
perl: 'Perl',
php: 'PHP',
python: 'Python',
ruby: 'Ruby'
},
'Frameworks' => {
rack: 'Rack',
django: 'Django',
rails: 'Ruby on Rails',
aspx_mvc: 'ASP.NET MVC',
jsf: 'JavaServer Faces',
cherrypy: 'CherryPy',
cakephp: 'CakePHP',
symfony: 'Symfony',
nette: 'Nette'
}
})
end
end
end
|
leanwithdata/hop
|
plugins/tech/parquet/src/main/java/org/apache/hop/parquet/transforms/input/ParquetValueConverter.java
|
<filename>plugins/tech/parquet/src/main/java/org/apache/hop/parquet/transforms/input/ParquetValueConverter.java
/*
* 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.hop.parquet.transforms.input;
import org.apache.hop.core.RowMetaAndData;
import org.apache.hop.core.row.IValueMeta;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.io.api.PrimitiveConverter;
import java.math.BigDecimal;
import java.util.Date;
public class ParquetValueConverter extends PrimitiveConverter {
private final RowMetaAndData group;
private final IValueMeta valueMeta;
private final int rowIndex;
public ParquetValueConverter(RowMetaAndData group, int rowIndex) {
this.group = group;
this.valueMeta = group.getValueMeta(rowIndex);
this.rowIndex = rowIndex;
}
@Override
public void addBinary(Binary value) {
if (rowIndex < 0) {
return;
}
Object object;
switch (valueMeta.getType()) {
case IValueMeta.TYPE_STRING:
object = value.toStringUsingUTF8();
break;
case IValueMeta.TYPE_BINARY:
object = value.getBytes();
break;
case IValueMeta.TYPE_BIGNUMBER:
object = new BigDecimal(value.toStringUsingUTF8());
break;
default:
throw new RuntimeException(
"Unable to convert Binary source data to type " + valueMeta.getTypeDesc());
}
group.getData()[rowIndex] = object;
}
@Override
public void addLong(long value) {
if (rowIndex < 0) {
return;
}
Object object;
switch (valueMeta.getType()) {
case IValueMeta.TYPE_INTEGER:
object = value;
break;
case IValueMeta.TYPE_STRING:
object = Long.toString(value);
break;
case IValueMeta.TYPE_DATE:
object = new Date(value);
break;
case IValueMeta.TYPE_BIGNUMBER:
object = new BigDecimal(value);
break;
default:
throw new RuntimeException(
"Unable to convert Long source data to type " + valueMeta.getTypeDesc());
}
group.getData()[rowIndex] = object;
}
@Override
public void addDouble(double value) {
if (rowIndex < 0) {
return;
}
Object object;
switch (valueMeta.getType()) {
case IValueMeta.TYPE_NUMBER:
object = value;
break;
case IValueMeta.TYPE_STRING:
object = Double.toString(value);
break;
case IValueMeta.TYPE_BIGNUMBER:
object = BigDecimal.valueOf(value);
break;
default:
throw new RuntimeException(
"Unable to convert Double/Float source data to type " + valueMeta.getTypeDesc());
}
group.getData()[rowIndex] = object;
}
@Override
public void addBoolean(boolean value) {
if (rowIndex < 0) {
return;
}
Object object;
switch (valueMeta.getType()) {
case IValueMeta.TYPE_BOOLEAN:
object = value;
break;
case IValueMeta.TYPE_STRING:
object = value ? "true" : "false";
break;
case IValueMeta.TYPE_INTEGER:
object = value ? 1L : 0L;
break;
default:
throw new RuntimeException(
"Unable to convert Boolean source data to type " + valueMeta.getTypeDesc());
}
group.getData()[rowIndex] = object;
}
@Override
public void addFloat(float value) {
addDouble(value);
}
@Override
public void addInt(int value) {
addLong(value);
}
}
|
danielNaczo/Python3Parser
|
src/main/java/io/github/danielnaczo/python3parser/manipulation/AddFunctionManipulation.java
|
package io.github.danielnaczo.python3parser.manipulation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import io.github.danielnaczo.python3parser.Python3Lexer;
import io.github.danielnaczo.python3parser.Python3Parser;
import io.github.danielnaczo.python3parser.model.AST;
import io.github.danielnaczo.python3parser.model.Identifier;
import io.github.danielnaczo.python3parser.model.expr.atoms.Str;
import io.github.danielnaczo.python3parser.model.stmts.Body;
import io.github.danielnaczo.python3parser.model.stmts.Statement;
import io.github.danielnaczo.python3parser.model.stmts.compoundStmts.ClassDef;
import io.github.danielnaczo.python3parser.model.stmts.compoundStmts.functionStmts.FunctionDef;
import io.github.danielnaczo.python3parser.model.stmts.flowStmts.Return;
import io.github.danielnaczo.python3parser.visitors.ast.ModuleVisitor;
import io.github.danielnaczo.python3parser.visitors.modifier.ModifierVisitor;
import io.github.danielnaczo.python3parser.visitors.prettyprint.IndentationPrettyPrint;
import io.github.danielnaczo.python3parser.visitors.prettyprint.ModulePrettyPrintVisitor;
public class AddFunctionManipulation {
public static void main(String[] args) throws IOException {
CharStream charStream = CharStreams.fromFileName("trunk/examples/Elevator.py");
Python3Lexer lexer = new Python3Lexer(charStream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
Python3Parser parser = new Python3Parser(tokens);
ModuleVisitor moduleVisitor = new ModuleVisitor();
AST ast = moduleVisitor.visit(parser.file_input());
//creating a new function: def getFloor(): return floor
List<Statement> statements = new ArrayList<>();
statements.add(new Return(new Str("floor")));
Body body = new Body(statements);
FunctionDef newFunctionDef = new FunctionDef(new Identifier("getFloor"), null,
body, null, null);
AddFunctionModifier addFunctionModifier = new AddFunctionModifier();
AST modifiedAST = addFunctionModifier.visitAST(ast, newFunctionDef);
//pretty print the modified AST
ModulePrettyPrintVisitor modulePrettyPrintVisitor = new ModulePrettyPrintVisitor();
String string = modulePrettyPrintVisitor.visitAST(modifiedAST, new IndentationPrettyPrint(0));
System.out.println(string);
}
private static class AddFunctionModifier extends ModifierVisitor<FunctionDef>{
@Override
public AST visitClassDef(ClassDef classDef, FunctionDef functionDef) {
super.visitClassDef(classDef, functionDef);
Body body = (Body) classDef.getBody();
List<Statement> statements = body.getStatements();
statements.add(functionDef);
return classDef;
}
}
}
|
threefoldtech/threefold-forums
|
app/serializers/category_and_topic_lists_serializer.rb
|
# frozen_string_literal: true
class CategoryAndTopicListsSerializer < ApplicationSerializer
has_one :category_list, serializer: CategoryListSerializer, embed: :objects
has_one :topic_list, serializer: TopicListSerializer, embed: :objects
has_many :users, serializer: BasicUserSerializer, embed: :objects
def users
users = object.topic_list.topics.map do |t|
t.posters.map { |poster| poster.try(:user) }
end
users.flatten!
users.compact!
users.uniq!(&:id)
users
end
end
|
nickwinder/buildkit
|
spec/client/organizations_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
describe Buildkit::Client::Organizations do
context '#organizations' do
it 'returns the list of organizations' do
VCR.use_cassette 'organizations' do
organizations = client.organizations
expect(organizations.size).to be == 1
organization = organizations.first
expect(organization.name).to be == 'Shopify'
expect(organization.slug).to be == 'shopify'
end
end
end
context '#organization' do
it 'returns an organization' do
VCR.use_cassette 'organization' do
organization = client.organization('shopify')
expect(organization.name).to be == 'Shopify'
expect(organization.slug).to be == 'shopify'
expect(organization.rels.keys).to be == %i[self web pipelines agents emojis]
end
end
end
end
|
aalleavitch/react-storefront
|
packages/react-storefront/test/amp/AmpMenu.test.js
|
<gh_stars>0
/**
* @license
* Copyright © 2017-2018 Moov Corporation. All rights reserved.
*/
import React from 'react'
import { mount } from 'enzyme'
import Menu from '../../src/amp/AmpMenu'
import MenuContext from '../../src/menu/MenuContext'
import Provider from '../TestProvider'
import AppModelBase from '../../src/model/AppModelBase'
describe('AmpMenu', () => {
let app
beforeEach(() => {
app = AppModelBase.create({
amp: true,
location: {
pathname: '/',
search: '',
hostname: 'localhost'
},
menu: {
levels: [
{
root: true,
items: [
{
text: 'Group 1',
className: 'group-1',
items: [
{
text: 'Item 1',
url: '/item1',
items: [{ text: 'Child 1', url: '/item1/child1' }]
}
]
}
]
}
]
}
})
})
it('should render full AMP menu', () => {
const wrapper = mount(
<Provider app={app}>
<MenuContext.Provider value={{ classes: {} }}>
<Menu />
</MenuContext.Provider>
</Provider>
)
expect(wrapper).toMatchSnapshot()
expect(
wrapper
.find('ItemContent')
.at(0)
.text()
).toBe('Group 1')
expect(
wrapper
.find('ItemContent')
.at(1)
.text()
).toBe('Item 1')
expect(
wrapper
.find('ItemContent')
.at(2)
.text()
).toBe('Child 1')
})
})
|
deepns/go
|
exercises/practice/ocr-numbers/.meta/example.go
|
package ocr
import "strings"
var digit = map[string]byte{
" _ | ||_| ": '0',
" | | ": '1',
" _ _||_ ": '2',
" _ _| _| ": '3',
" |_| | ": '4',
" _ |_ _| ": '5',
" _ |_ |_| ": '6',
" _ | | ": '7',
" _ |_||_| ": '8',
" _ |_| _| ": '9',
}
func recognizeDigit(lines []string, start int) byte {
if len(lines) < 4 {
return '?'
}
need := start + 3
for _, l := range lines {
if len(l) < need {
return '?'
}
}
if d, ok := digit[lines[0][start:need]+
lines[1][start:need]+
lines[2][start:need]+
lines[3][start:need]]; ok {
return d
}
return '?'
}
func Recognize(s string) []string {
lines := strings.Split(s, "\n")
if lines[0] == "" {
lines = lines[1:]
}
r := make([]string, (len(lines)+3)/4)
for i := range r {
max := 0
for l := 0; l < 4 && l < len(lines); l++ {
if n := len(lines[l]); n > max {
max = n
}
}
b := make([]byte, (max+2)/3)
for j := range b {
b[j] = recognizeDigit(lines, j*3)
}
r[i] = string(b)
lines = lines[4:]
}
return r
}
|
YaibaToKen/soulus
|
src/main/java/yuudaari/soulus/common/world/SummonerReplacer.java
|
<filename>src/main/java/yuudaari/soulus/common/world/SummonerReplacer.java<gh_stars>0
package yuudaari.soulus.common.world;
import java.util.ArrayList;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.IChunkGenerator;
import net.minecraftforge.event.terraingen.PopulateChunkEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import yuudaari.soulus.Soulus;
import yuudaari.soulus.common.ModBlocks;
import yuudaari.soulus.common.block.summoner.Summoner;
import yuudaari.soulus.common.block.summoner.SummonerTileEntity;
import yuudaari.soulus.common.block.summoner.Summoner.Upgrade;
import yuudaari.soulus.common.config.ConfigInjected;
import yuudaari.soulus.common.config.ConfigInjected.Inject;
import yuudaari.soulus.common.config.world.summoner_replacement.ConfigSummonerReplacement;
import yuudaari.soulus.common.config.world.summoner_replacement.ConfigStructure;
import yuudaari.soulus.common.config.world.summoner_replacement.ConfigReplacement;
import yuudaari.soulus.common.util.GeneratorName;
import yuudaari.soulus.common.util.Logger;
@Mod.EventBusSubscriber
@ConfigInjected(Soulus.MODID)
public class SummonerReplacer {
@Inject public static ConfigSummonerReplacement CONFIG;
@SubscribeEvent(priority = EventPriority.LOWEST)
public static void populateChunkPost (PopulateChunkEvent.Post event) {
World world = event.getWorld();
Chunk chunk = world.getChunkFromChunkCoords(event.getChunkX(), event.getChunkZ());
IChunkGenerator cg = event.getGenerator();
Map<BlockPos, TileEntity> teMap = chunk.getTileEntityMap();
ConfigStructure defaultStructureConfig = CONFIG.structures.get("*");
if (defaultStructureConfig == null)
return;
for (TileEntity te : new ArrayList<>(teMap.values())) {
Block block = te.getBlockType();
// Logger.info("found a tile entity " + block.getRegistryName());
if (block == Blocks.MOB_SPAWNER) {
BlockPos pos = te.getPos();
// Logger.info("found a spawner " + pos);
ConfigStructure structureConfig = defaultStructureConfig;
for (Map.Entry<String, ConfigStructure> structureConfigEntry : CONFIG.structures
.entrySet()) {
if (cg.isInsideStructure(world, GeneratorName.get(structureConfigEntry.getKey()), pos)) {
structureConfig = structureConfigEntry.getValue();
}
}
String entityType = getTheIdFromAStupidMobSpawnerTileEntity(te);
// Logger.info("entity type " + entityType);
ConfigReplacement replacement = structureConfig.replacementsByCreature.get(entityType);
if (replacement == null) {
replacement = structureConfig.replacementsByCreature
.get(new ResourceLocation(entityType).getResourceDomain() + ":*");
if (replacement == null) {
replacement = structureConfig.replacementsByCreature.get("*");
if (replacement == null) {
// this spawner isn't configured to be replaced
return;
}
}
}
// Logger.info("endersteel type " + endersteelType);
world.setBlockState(pos, ModBlocks.SUMMONER.getDefaultState()
.withProperty(Summoner.VARIANT, replacement.type)
.withProperty(Summoner.HAS_SOULBOOK, replacement.midnightJewel), 7);
if (!replacement.midnightJewel) return;
TileEntity nte = world.getTileEntity(pos);
if (nte == null || !(nte instanceof SummonerTileEntity)) {
Logger.warn("Unable to insert midnight jewel into replaced summoner");
return;
}
SummonerTileEntity ste = (SummonerTileEntity) nte;
ste.setEssenceType(entityType);
ste.upgrades.put(Upgrade.CRYSTAL_DARK, 1);
}
}
}
public static String getTheIdFromAStupidMobSpawnerTileEntity (TileEntity te) {
if (!(te instanceof TileEntityMobSpawner))
return null;
TileEntityMobSpawner mste = (TileEntityMobSpawner) te;
NBTTagCompound nbt = new NBTTagCompound();
mste.writeToNBT(nbt);
NBTTagList taglist = nbt.getTagList("SpawnPotentials", 10);
NBTBase firstSpawnPotential = taglist.get(0);
if (!(firstSpawnPotential instanceof NBTTagCompound))
return null;
NBTTagCompound firstSpawnPotentialTheRealOne = (NBTTagCompound) firstSpawnPotential;
NBTTagCompound theActualEntityOhMyGod = firstSpawnPotentialTheRealOne.getCompoundTag("Entity");
return theActualEntityOhMyGod.getString("id");
}
}
|
niloc132/RelaxFactory
|
rxf-server/src/main/java/rxf/server/RelaxFactoryServerImpl.java
|
package rxf.server;
import one.xio.AsioVisitor;
import one.xio.HttpMethod;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.ServerSocketChannel;
import static java.lang.StrictMath.min;
import static java.nio.channels.SelectionKey.OP_ACCEPT;
public class RelaxFactoryServerImpl implements RelaxFactoryServer {
private int port = 8080;
private AsioVisitor topLevel;
private InetAddress hostname;
private ServerSocketChannel serverSocketChannel;
private volatile boolean isRunning;
/**
* handles the threadlocal ugliness if any to registering user threads into the selector/reactor pattern
*
* @param channel the socketchanel
* @param op int ChannelSelector.operator
* @param s the payload: grammar {enum,data1,data..n}
* @throws java.nio.channels.ClosedChannelException
*
*/
public static void enqueue(SelectableChannel channel, int op, Object... s)
throws ClosedChannelException {
HttpMethod.enqueue(channel, op, s);
}
public static String wheresWaldo(int... depth) {
int d = depth.length > 0 ? depth[0] : 2;
Throwable throwable = new Throwable();
Throwable throwable1 = throwable.fillInStackTrace();
StackTraceElement[] stackTrace = throwable1.getStackTrace();
String ret = "";
for (int i = 2, end = min(stackTrace.length - 1, d); i <= end; i++) {
StackTraceElement stackTraceElement = stackTrace[i];
ret +=
"\tat " + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
+ "(" + stackTraceElement.getFileName() + ":" + stackTraceElement.getLineNumber()
+ ")\n";
}
return ret;
}
public static void init(AsioVisitor protocoldecoder, String... a) throws IOException {
HttpMethod.init(protocoldecoder, a);
}
public void setPort(int port) {
this.port = port;
}
@Override
public void init(String hostname, int port, AsioVisitor topLevel) throws UnknownHostException {
assert this.topLevel == null && this.serverSocketChannel == null : "Can't call init twice";
this.topLevel = topLevel;
this.setPort(port);
this.hostname = InetAddress.getByName(hostname);
}
@Override
public void start() throws IOException {
assert serverSocketChannel == null : "Can't start already started server";
isRunning = true;
try {
serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress addr = new InetSocketAddress(hostname, getPort());
serverSocketChannel.socket().bind(addr);
setPort(serverSocketChannel.socket().getLocalPort());
System.out.println(hostname.getHostAddress() + ":" + getPort());
serverSocketChannel.configureBlocking(false);
enqueue(serverSocketChannel, OP_ACCEPT, topLevel);
init(topLevel);
} finally {
isRunning = false;
}
}
@Override
public int getPort() {
return port;
}
@Override
public void stop() throws IOException {
HttpMethod.killswitch = true;
serverSocketChannel.close();
}
@Override
public boolean isRunning() {
return isRunning;
}
}
|
ionox0/bunny
|
rabix-bindings/src/main/java/org/rabix/bindings/BindingsFactory.java
|
package org.rabix.bindings;
import org.apache.commons.lang.NotImplementedException;
import org.rabix.bindings.model.Application;
import org.rabix.bindings.model.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
public class BindingsFactory {
private final static Logger logger = LoggerFactory.getLogger(BindingsFactory.class);
public static final String MULTIPROTOCOL_KEY = "rabix.multiprotocol";
private static SortedSet<Bindings> bindings = new TreeSet<>(new Comparator<Bindings>() {
@Override
public int compare(Bindings b1, Bindings b2) {
return b1.getProtocolType().order - b2.getProtocolType().order;
}
});
static {
for (ProtocolType type : ProtocolType.values()) {
try {
Class<?> clazz = Class.forName(type.bindingsClass);
if (clazz == null) {
continue;
}
try {
bindings.add((Bindings) clazz.newInstance());
} catch (Exception e) {
logger.warn("Failed to instantiate class " + clazz, e);
}
} catch (Exception e) {
// ignore
}
}
}
public static Bindings create(String appURL) throws BindingException {
int wrongVersions = 0;
Exception finalException = null;
for (Bindings binding : bindings) {
try {
Application app = binding.loadAppObject(appURL);
if (app == null) {
continue;
}
if (app.getVersion() != null && binding.getProtocolType().appVersion.equalsIgnoreCase(app.getVersion())) {
return binding;
}
else if(app.getVersion() == null && binding.getProtocolType().appVersion == null) {
return binding;
}
} catch (NotImplementedException e) {
throw e; // fail if we do not support this kind of deserialization (Schema salad)
} catch (BindingWrongVersionException ignore) {
wrongVersions++;
} catch (Exception e) {
finalException = e;
}
}
if (wrongVersions == bindings.size()) {
StringBuilder validVersions = new StringBuilder();
boolean first = true;
for (Bindings b : bindings) {
if (b.getProtocolType().appVersion == null)
continue;
if (!first)
validVersions.append(", ");
validVersions.append(b.getProtocolType().appVersion);
first = false;
}
throw new BindingException("Invalid cwlVersion. Allowed values are: " + validVersions);
}
if (finalException != null && finalException.getMessage() != null) {
throw new BindingException(finalException.getMessage(), finalException);
}
throw new BindingException("Unknown error when parsing the app!");
}
public static Bindings create(Job job) throws BindingException {
return create(job.getApp());
}
public static Bindings create(ProtocolType protocol) throws BindingException {
for(Bindings binding: bindings) {
if(binding.getProtocolType().equals(protocol)) {
return binding;
}
}
throw new BindingException("Cannot find binding for the protocol.");
}
}
|
bonniech3n/merou
|
grouper/setup.py
|
<reponame>bonniech3n/merou
import logging
from argparse import ArgumentParser
from typing import TYPE_CHECKING
from grouper import __version__
from grouper.settings import default_settings_path
if TYPE_CHECKING:
from argparse import Namespace
def build_arg_parser(description):
# type(str) -> ArgumentParser
parser = ArgumentParser(description=description)
parser.add_argument(
"-c", "--config", default=default_settings_path(), help="Path to config file."
)
parser.add_argument(
"-v", "--verbose", action="count", default=0, help="Increase logging verbosity."
)
parser.add_argument(
"-q", "--quiet", action="count", default=0, help="Decrease logging verbosity."
)
parser.add_argument(
"-V",
"--version",
action="version",
version="%%(prog)s {}".format(__version__),
help="Display version information.",
)
parser.add_argument(
"-a", "--address", type=str, default=None, help="Override address in config."
)
parser.add_argument("-p", "--port", type=int, default=None, help="Override port in config.")
parser.add_argument(
"-n", "--deployment-name", type=str, default="", help="Name of the deployment."
)
parser.add_argument(
"-d", "--database-url", type=str, default=None, help="Override database URL in config."
)
return parser
def setup_logging(args, log_format):
# type: (Namespace, str) -> None
# `logging` levels are integer multiples of 10. so each verbose/quiet level
# is multiplied by 10
verbose = args.verbose * 10
quiet = args.quiet * 10
log_level = logging.getLogger().level - verbose + quiet
sa_log = logging.getLogger("sqlalchemy.engine.base.Engine")
logging.basicConfig(level=log_level, format=log_format)
if log_level < 0:
sa_log.setLevel(logging.INFO)
|
iadgovuser26/HIRS
|
HIRS_Utils/src/test/java/hirs/persist/DBAlertManagerDateFilterTest.java
|
<filename>HIRS_Utils/src/test/java/hirs/persist/DBAlertManagerDateFilterTest.java
package hirs.persist;
import hirs.data.persist.SpringPersistenceTest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.DateTime;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import hirs.FilteredRecordsList;
import hirs.data.persist.Alert;
/**
* Tests the DBAlertManager's ability to retrieve an ordered list of alerts
* based on start and end dates.
*/
public class DBAlertManagerDateFilterTest extends SpringPersistenceTest {
private static final Logger LOGGER = LogManager.getLogger(DBAlertManagerTrustAlertsTest.class);
private static final String ORDER_COL = "id";
private AlertManager mgr;
private List<Alert> sequentialAlerts;
/**
* Creates a new <code>DBAlertManagerDateFilterTest</code>.
*/
public DBAlertManagerDateFilterTest() {
/* do nothing */
}
/**
* Initializes a <code>SessionFactory</code>. The factory is used for an
* in-memory database that is used for testing.
*
* @throws InterruptedException if the sleep operation is interrupted
*/
@BeforeClass
public void setup() throws InterruptedException {
mgr = new DBAlertManager(sessionFactory);
sequentialAlerts = new ArrayList<>();
// sleep between each creation to ensure that each alert has a distinct create time
sequentialAlerts.add(createAlert(mgr, "1"));
Thread.sleep(2000);
sequentialAlerts.add(createAlert(mgr, "2"));
Thread.sleep(2000);
sequentialAlerts.add(createAlert(mgr, "3"));
Thread.sleep(2000);
sequentialAlerts.add(createAlert(mgr, "4"));
Thread.sleep(2000);
sequentialAlerts.add(createAlert(mgr, "5"));
List<Alert> allAlerts = mgr.getAlertList();
Assert.assertEquals(allAlerts.size(), 5);
Date previousAlertDate = sequentialAlerts.get(0).getCreateTime();
// verify alerts have sequential creation times
for (Alert alert : sequentialAlerts.subList(1, sequentialAlerts.size() - 1)) {
Assert.assertTrue(alert.getCreateTime().getTime() > previousAlertDate.getTime());
previousAlertDate = alert.getCreateTime();
}
}
/**
* Closes the <code>SessionFactory</code> from setup.
*/
@AfterClass
public void tearDown() {
}
/**
* Tests that specifying no date filtering returns the full set of alerts.
*/
@Test
public void noDateFilteringReturnsFullList() {
FilteredRecordsList<Alert> allAlerts = mgr.getOrderedAlertList(null, ORDER_COL,
true, 0, 0, null, AlertManager.AlertListType.UNRESOLVED_ALERTS, null, null, null);
Assert.assertEquals(allAlerts.size(), sequentialAlerts.size());
}
/**
* Tests that specifying only a begin date will only exclude older alerts.
*/
@Test
public void beginDateOnlyFilteringExcludesOlderAlerts() {
DateTime beginDate = new DateTime(sequentialAlerts.get(2).getCreateTime()).plusSeconds(1);
FilteredRecordsList<Alert> returnAlerts = mgr.getOrderedAlertList(null, ORDER_COL,
true, 0, 0, null, AlertManager.AlertListType.UNRESOLVED_ALERTS, null,
beginDate.toDate(), null);
// nothing before alert index 2
Assert.assertEquals(returnAlerts.size(), 2);
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(3)));
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(4)));
}
/**
* Tests that specifying only an end date will only exclude newer alerts.
*/
@Test
public void endDateOnlyFilteringExcludesNewerAlerts() {
DateTime endDate = new DateTime(sequentialAlerts.get(2).getCreateTime()).plusSeconds(1);
FilteredRecordsList<Alert> returnAlerts = mgr.getOrderedAlertList(null, ORDER_COL,
true, 0, 0, null, AlertManager.AlertListType.UNRESOLVED_ALERTS, null,
null, endDate.toDate());
// nothing after alert index 2
Assert.assertEquals(returnAlerts.size(), 3);
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(0)));
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(1)));
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(2)));
}
/**
* Tests that specifying a begin and end date (date range) will exclude alerts outside
* the range.
*/
@Test
public void beginAndEndDateFilteringExcludesCorrectAlerts() {
DateTime beginDate = new DateTime(sequentialAlerts.get(1).getCreateTime()).minusSeconds(1);
DateTime endDate = new DateTime(sequentialAlerts.get(3).getCreateTime()).plusSeconds(1);
FilteredRecordsList<Alert> returnAlerts = mgr.getOrderedAlertList(null, ORDER_COL,
true, 0, 0, null, AlertManager.AlertListType.UNRESOLVED_ALERTS, null,
beginDate.toDate(), endDate.toDate());
// only alerts 1 through 3
Assert.assertEquals(returnAlerts.size(), 3);
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(1)));
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(2)));
Assert.assertTrue(returnAlerts.contains(sequentialAlerts.get(3)));
}
private Alert createAlert(final AlertManager mgr, final String details)
throws AlertManagerException {
String alertDetails = details;
if (details == null) {
alertDetails = "default";
}
final Alert alert = new Alert(alertDetails);
return mgr.saveAlert(alert);
}
}
|
zeryabkhan91/solidus_square
|
spec/models/solidus_square/payment_method_spec.rb
|
<filename>spec/models/solidus_square/payment_method_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe SolidusSquare::PaymentMethod, type: :model do
it { is_expected.to delegate_method(:create_profile).to(:gateway) }
describe '#payment_profiles_supported?' do
it 'return true' do
expect(described_class.new).to be_payment_profiles_supported
end
end
end
|
caridy/es6-module-transpiler
|
test/features/export_identifier.globals.js
|
(function(exports) {
"use strict";
var jQuery = function() { };
exports.jQuery = jQuery;
})(window);
|
robtweed/wc-admin-ui
|
components/adminui-crud.js
|
/*
----------------------------------------------------------------------------
| admin-ui: SB2-Admin UI Theme WebComponents Library |
| |
| Copyright (c) 2020 M/Gateway Developments Ltd, |
| Redhill, Surrey UK. |
| All rights reserved. |
| |
| http://www.mgateway.com |
| Email: <EMAIL> |
| |
| |
| 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. |
----------------------------------------------------------------------------
14 August 2020
*/
export function crud_assembly(QEWD, state) {
state = state || {};
state.name = state.name || 'crud-' + Date.now();
//state.assemblyName = state.assemblyName || state.name;
state.title = state.title || 'Record Maintenance Page';
state.summary = state.summary || {};
state.detail = state.detail || {};
state.update = state.update || {};
state.summary.headers = state.summary.headers || ['Name'];
state.summary.data_properties = state.summary.data_properties || ['name'];
if (state.summary.headers.length === state.summary.data_properties.length) {
state.summary.headers.push('Select');
};
state.summary.qewd = state.summary.qewd || {};
state.update.qewd = state.update.qewd || {};
let formFields = {};
let formFieldPropertyNames = {};
if (state.detail.fields) {
state.detail.fields.forEach(function(field, index) {
if (field.name && !field.data_property) field.data_property = field.name;
if (!field.name && field.data_property) field.name = field.data_property;
formFields[field.data_property] = state.detail.fields[index];
formFieldPropertyNames[field.name] = field.data_property;
});
}
let component = {
componentName: 'adminui-content-page',
assemblyName: state.assemblyName,
state: {
name: state.name
},
hooks: ['loadModal'],
children: [
{
componentName: 'adminui-content-page-header',
state: {
title: state.title
}
},
{
componentName: 'adminui-row',
children: [
{
componentName: 'adminui-content-card',
state: {
name: state.name + '-summary-card'
},
children: [
{
componentName: 'adminui-content-card-header',
children: [
{
componentName: 'adminui-content-card-button-title',
state: {
title: state.summary.title || 'Summary of Records',
title_colour: state.summary.titleColour || 'info',
icon: state.summary.btnIcon || 'plus',
buttonColour: state.summary.btnColour || 'success',
tooltip: state.summary.btnTooltip || 'Add a new Record',
hideButton: state.summary.disableAdd
},
hooks: ['createNewRecord']
}
]
},
{
componentName: 'adminui-content-card-body',
children: [
{
componentName: 'adminui-datatables',
state: {
name: state.name
},
hooks: ['retrieveRecordSummary']
}
]
}
]
},
{
componentName: 'adminui-content-card',
state: {
name: state.name + '-details-card',
hide: true,
width: state.detail.cardWidth || '400px'
},
children: [
{
componentName: 'adminui-content-card-header',
children: [
{
componentName: 'adminui-content-card-button-title',
state: {
title: state.detail.title,
title_colour: state.detail.titleColour || 'info',
icon: state.detail.btnIcon || 'cog',
buttonColour: state.detail.btnColour || 'info',
tooltip: state.detail.btnTooltip || 'Edit record',
disableButton: state.detail.disableEdit
},
hooks: ['updateRecord']
}
]
},
{
componentName: 'adminui-content-card-body',
state: {
name: state.name + '-details-card-body'
},
children: [
{
componentName: 'adminui-form',
state: {
name: state.name
},
hooks: ['addFormFields']
}
]
},
{
componentName: 'adminui-content-card-footer',
state: {
hidden: true
},
children: [
{
componentName: 'adminui-button',
state: {
text: state.update.btnText || 'Save',
colour: state.update.btnColour || 'success',
cls: 'btn-block'
},
hooks: ['save']
}
]
}
]
}
]
}
]
};
let showRecordBtn = {
componentName: 'adminui-button',
assemblyName: state.assemblyName,
state: {
icon: state.summary.rowBtnIcon || 'edit',
colour: state.summary.rowBtnColour || 'info'
},
hooks: ['getDetail']
};
let deleteBtn = {
assemblyName: state.assemblyName,
componentName: 'adminui-button',
state: {
icon: 'trash-alt',
colour: 'danger'
},
hooks: ['confirmDelete']
};
let selectBtn = {
assemblyName: state.assemblyName,
componentName: 'adminui-button',
state: {
icon: 'check-square',
colour: 'info',
tooltip: 'Select Record'
},
hooks: ['selectRecord']
};
let confirmDeleteModal = {
componentName: 'adminui-modal-root',
assemblyName: state.assemblyName,
state: {
name: 'confirm-delete-' + state.name
},
children: [
{
componentName: 'adminui-modal-header',
state: {
name: state.name + '-delete',
title: 'Delete Record'
},
children: [
{
componentName: 'adminui-modal-close-button',
}
]
},
{
componentName: 'adminui-modal-body',
state: {
text: 'Are you sure you want to delete this record?'
}
},
{
componentName: 'adminui-modal-footer',
children: [
{
componentName: 'adminui-modal-cancel-button',
},
{
componentName: 'adminui-button',
state: {
name: 'deleteRecord-' + state.name,
text: 'Yes',
colour: 'danger',
cls: 'btn-block'
},
hooks: ['delete']
}
]
}
]
};
let hooks = {
'adminui-content-page': {
loadModal: function() {
let modal = this.getComponentByName('adminui-modal-root', 'confirm-delete-' + state.name);
if (!modal) {
// add modal for confirming record deletions
this.loadGroup(confirmDeleteModal, document.getElementsByTagName('body')[0], this.context);
}
}
},
'adminui-form': {
addFormFields: function() {
let form = this;
let fields = state.detail.fields;
let noOfFields = fields.length;
function addFormField(no) {
if (no === noOfFields) return;
var field = fields[no];
let componentName = 'adminui-form-field';
var assembly;
if (field.type === 'radios') {
assembly = {
componentName: 'adminui-form-radio-group',
state: {
name: field.name,
label: field.label,
radios: field.radios
}
};
form.loadGroup(assembly, form, form.context, function() {
addFormField(no + 1);
});
return;
}
if (field.type === 'checkboxes') {
let checkboxes = [];
field.checkboxes.forEach(function(checkbox) {
if (typeof checkbox.if === 'function') {
if (!checkbox.if.call(form)) {
return;
}
}
checkboxes.push({
text: checkbox.text,
value: checkbox.value
});
});
assembly = {
componentName: 'adminui-form-checkbox-group',
state: {
name: field.name,
label: field.label,
checkboxes: checkboxes
}
};
form.loadGroup(assembly, form, form.context, function() {
addFormField(no + 1);
});
return;
}
if (field.type === 'range') componentName = 'adminui-form-range';
if (field.type === 'select') componentName = 'adminui-form-select';
if (field.type === 'multiselect') componentName = 'adminui-form-select-multiple';
if (field.type === 'textarea') componentName = 'adminui-form-textarea';
assembly = {
componentName: componentName,
state: {
name: field.name,
type: field.type,
label: field.label,
placeholder: field.placeholder,
readonly: true,
row: field.labelWidth
}
};
if (field.type === 'select' || field.type === 'multiselect') {
assembly.hooks = ['displayOptions'];
assembly.state.options = field.options;
}
if (field.type === 'range') {
assembly.state.min = field.min;
assembly.state.max = field.max;
assembly.state.step = field.step;
assembly.state.marker = field.marker;
}
if (field.type === 'textarea') {
assembly.state.height = field.height;
assembly.state.rows = field.rows;
}
form.loadGroup(assembly, form, form.context, function() {
addFormField(no + 1);
});
}
addFormField(0);
}
},
'adminui-form-select': {
displayOptions: function(state) {
this.setState({options: state.options});
}
},
'adminui-form-select-multiple': {
displayOptions: function(state) {
this.setState({options: state.options});
}
},
'adminui-datatables': {
retrieveRecordSummary: async function() {
let table = this;
let contentPage = this.getParentComponent('adminui-content-page');
let responseObj = await QEWD.reply({
type: state.summary.qewd.getSummary || 'getSummary',
params: {
properties: state.summary.data_properties,
selectedRecordId: table.context.selectedRecordId
}
});
if (!responseObj.message.error) {
table.data = {};
let data = [];
responseObj.message.summary.forEach(function(record) {
table.data[record.id] = record;
let row = [];
state.summary.data_properties.forEach(function(property) {
row.push(record[property]);
});
row.push(record.id);
if (state.summary.enableDelete) {
row.push('');
}
data.push(row);
});
let columns = [];
let noOfCols = state.summary.headers.length;
state.summary.headers.forEach(function(header) {
columns.push({title: header});
});
if (state.summary.enableDelete) {
columns.push({title: 'Delete'});
}
let obj = {
data: data,
columns: columns
};
table.render(obj);
table.datatable.rows().every(function(index, element) {
let row = $(this.node());
let td = row.find('td').eq(noOfCols - 1)[0];
let id = td.textContent;
table.row = table.data[id];
td.id = state.name + '-record-' + id;
td.textContent = '';
if (state.summary.enableDelete) {
td = row.find('td').eq(noOfCols)[0];
td.id = state.name + '-delete-' + id;
let confirmTextFn = state.summary.deleteConfirmText;
let confirmText;
if (typeof confirmTextFn === 'function') {
let fields = [];
for (let i = 0; i < (noOfCols - 1); i++) {
fields.push(row.find('td').eq(i)[0].textContent);
}
confirmText = confirmTextFn(fields);
}
else {
let name_td = row.find('td').eq(0)[0];
confirmText = name_td.textContent;
}
td.setAttribute('data-confirm', confirmText);
}
});
table.datatable.rows({page: 'current'}).every(function(index, element) {
let row = $(this.node());
let td = row.find('td').eq(noOfCols - 1)[0];
table.loadGroup(showRecordBtn, td, table.context);
if (state.summary.enableDelete) {
td = row.find('td').eq(noOfCols)[0];
table.loadGroup(deleteBtn, td, table.context);
}
});
table.datatable.on('draw', function() {
table.datatable.rows({page: 'current'}).every(function(index, element) {
let row = $(this.node());
let td = row.find('td').eq(2)[0];
let btn = td.querySelector('adminui-button');
if (btn) {
td.removeChild(btn);
}
table.loadGroup(showRecordBtn, td, table.context);
if (state.summary.enableDelete) {
td = row.find('td').eq(3)[0];
btn = td.querySelector('adminui-button');
if (btn) {
td.removeChild(btn);
}
table.loadGroup(deleteBtn, td, table.context);
}
});
});
contentPage.rendered = true;
}
contentPage.onSelected = function() {
if (contentPage.rendered && state.summary.refetchSummaryOnSelected) {
let target = table.getParentComponent('adminui-content-card-body');
table.datatable.destroy();
table.remove();
let assembly = {
componentName: 'adminui-datatables',
assemblyName: state.assemblyName,
state: {
name: state.name
},
hooks: ['retrieveRecordSummary']
};
table.loadGroup(assembly, target, table.context);
}
};
}
},
'adminui-button': {
confirmDelete: function() {
let _this = this;
this.rootElement.setAttribute('data-toggle', 'modal');
let modalRoot = this.getComponentByName('adminui-modal-root', 'confirm-delete-' + state.name);
if (modalRoot) {
this.rootElement.setAttribute('data-target', '#' + modalRoot.rootElement.id);
}
let fn = function() {
let card = _this.getComponentByName('adminui-content-card', state.name + '-details-card');
card.hide();
let id = _this.parentNode.id.split('delete-')[1];
let display = _this.parentNode.getAttribute('data-confirm');
let header = modalRoot.querySelector('adminui-modal-header');
header.setState({
title: 'Deleting ' + display
});
let button = _this.getComponentByName('adminui-button', 'deleteRecord-' + state.name);
button.recordId = id;
}
this.addHandler(fn);
},
delete: function() {
let _this = this;
let fn = async function() {
let id = _this.parentNode.id.split('delete-')[1];
let responseObj = await QEWD.reply({
type: state.summary.qewd.delete || 'deleteRecord',
params: {
id: _this.recordId
}
});
let modalRoot = _this.getParentComponent('adminui-modal-root');
modalRoot.hide();
if (!responseObj.message.error) {
toastr.info('Record deleted');
let table = _this.getComponentByName('adminui-datatables', state.name);
let target = table.getParentComponent('adminui-content-card-body');
table.datatable.destroy();
table.remove();
let assembly = {
componentName: 'adminui-datatables',
assemblyName: state.assemblyName,
state: {
name: state.name
},
hooks: ['retrieveRecordSummary']
};
_this.loadGroup(assembly, target, _this.context);
}
//});
};
this.addHandler(fn);
},
save: function() {
let _this = this;
let fn = async function() {
let form = _this.getComponentByName('adminui-form', state.name);
let field;
let value;
let params = {
id: form.recordId
};
for (let name in form.field) {
let value = form.fieldValues[name];
if (typeof value === 'object') {
let arr = [];
for (let xname in value) {
if (value[xname]) arr.push(xname);
}
params[formFieldPropertyNames[name]] = arr;
}
else {
params[formFieldPropertyNames[name]] = value;
}
}
let responseObj = await QEWD.reply({
type: state.update.qewd.save || 'saveRecord',
params: params
});
if (!responseObj.message.error) {
toastr.info('Record updated successfully');
let table = _this.getComponentByName('adminui-datatables', state.name);
let target = table.getParentComponent('adminui-content-card-body');
if (table) {
table.datatable.destroy();
table.remove();
}
let assembly = {
componentName: 'adminui-datatables',
assemblyName: state.assemblyName,
state: {
name: state.name
},
hooks: ['retrieveRecordSummary']
};
//console.log(target);
//console.log(assembly);
_this.loadGroup(assembly, target, _this.context);
let card = _this.getComponentByName('adminui-content-card', state.name + '-details-card');
card.hide();
}
};
this.addHandler(fn);
},
getDetail: function() {
let _this = this;
let id = this.parentNode.id.split('record-')[1];
let card = this.getComponentByName('adminui-content-card', state.name + '-details-card');
let title = card.querySelector('adminui-content-card-button-title');
title.selectedRecordId = id;
let form = this.getComponentByName('adminui-form', state.name);
let fn = async function() {
form.recordId = id;
let responseObj = await QEWD.reply({
type: state.summary.qewd.getDetail || 'getRecordDetail',
params: {
id: id
}
});
if (!responseObj.message.error) {
card.show();
card.footer.hide();
title.record = responseObj.message.record;
let title_value;
if (typeof state.detail.title_data_property === 'function') {
title_value = state.detail.title_data_property.call(title);
}
else if (!state.detail.title_data_property) {
title_value = 'Edit Record';
}
else {
title_value = title.record[state.detail.title_data_property];
}
title.setState({title: title_value});
title.showButton();
for (let fname in formFields) {
let name = formFields[fname].name;
let field = form.field[name];
if (field.type === 'radio-group') {
field.setState({
selectedValue: title.record[name],
readonly: true
});
}
else if (field.type === 'checkbox-group') {
field.setState({
selectedValues: title.record[name],
readonly: true
});
}
else if (field.type === 'select-multiple') {
field.setState({
selectedValues: title.record[name],
readonly: true
});
}
else {
if (field.type === 'range' && !title.record[name]) {
title.record[name] = field.min;
}
field.setState({
value: title.record[name],
readonly: true
});
}
}
}
};
this.addHandler(fn, this.rootElement);
},
selectRecord() {
let _this = this;
let title = this.getParentComponent('adminui-content-card-button-title');
let fn = function() {
_this.context.selectedRecordId = title.selectedRecordId;
_this.context.selectedRecord = title.record;
};
this.addHandler(fn, this.rootElement);
}
},
'adminui-content-card-button-title': {
updateRecord: function() {
let title = this;
let fn = function() {
title.hideButton();
let form = title.getComponentByName('adminui-form', state.name);
let card = title.getComponentByName('adminui-content-card', state.name + '-details-card');
card.footer.show();
let field;
for (let name in form.field) {
field = form.field[name];
field.setState({readonly: false});
}
};
this.addHandler(fn, this.button);
if (state.detail.enableSelect) {
let div = document.createElement('div');
div.classList.add('col');
title.rootElement.appendChild(div);
title.loadGroup(selectBtn, div, title.context);
}
},
createNewRecord: function() {
let _this = this;
let fn = function() {
let card = _this.getComponentByName('adminui-content-card', state.name + '-details-card');
let title = card.querySelector('adminui-content-card-button-title');
title.setState({title: state.detail.newRecordTitle || 'New Record'});
title.hideButton();
let form = _this.getComponentByName('adminui-form', state.name);
form.recordId = 'new-record';
card.show();
card.footer.show();
let field;
for (let name in form.field) {
field = form.field[name];
if (field.type === 'radio-group') {
field.setState({
selectedValue: '',
readonly: false
});
}
if (field.type === 'checkbox-group') {
field.setState({
selectedValues: [],
readonly: false
});
}
else {
field.setState({
value: '',
readonly: false
});
}
}
};
this.addHandler(fn, this.button);
}
}
};
return {component, hooks};
};
|
Myent/demo
|
libraries/jquery/13-06-2016bkpJsBarcode-master/dist/JsBarcode.all.js
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmory imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmory exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 10);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var EANencoder = function () {
function EANencoder() {
_classCallCheck(this, EANencoder);
// Standard start end and middle bits
this.startBin = "101";
this.endBin = "101";
this.middleBin = "01010";
// The L (left) type of encoding
this.Lbinary = ["0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011"];
// The G type of encoding
this.Gbinary = ["0100111", "0110011", "0011011", "0100001", "0011101", "0111001", "0000101", "0010001", "0001001", "0010111"];
// The R (right) type of encoding
this.Rbinary = ["1110010", "1100110", "1101100", "1000010", "1011100", "1001110", "1010000", "1000100", "1001000", "1110100"];
}
// Convert a numberarray to the representing
EANencoder.prototype.encode = function encode(number, structure, separator) {
// Create the variable that should be returned at the end of the function
var result = "";
// Make sure that the separator is set
separator = separator || "";
// Loop all the numbers
for (var i = 0; i < number.length; i++) {
// Using the L, G or R encoding and add it to the returning variable
if (structure[i] == "L") {
result += this.Lbinary[number[i]];
} else if (structure[i] == "G") {
result += this.Gbinary[number[i]];
} else if (structure[i] == "R") {
result += this.Rbinary[number[i]];
}
// Add separator in between encodings
if (i < number.length - 1) {
result += separator;
}
}
return result;
};
return EANencoder;
}();
exports.default = EANencoder;
/***/ },
/* 1 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// Encoding documentation
// https://en.wikipedia.org/wiki/MSI_Barcode#Character_set_and_binary_lookup
var MSI = function () {
function MSI(string) {
_classCallCheck(this, MSI);
this.string = string;
}
MSI.prototype.encode = function encode() {
// Start bits
var ret = "110";
for (var i = 0; i < this.string.length; i++) {
// Convert the character to binary (always 4 binary digits)
var digit = parseInt(this.string[i]);
var bin = digit.toString(2);
bin = addZeroes(bin, 4 - bin.length);
// Add 100 for every zero and 110 for every 1
for (var b = 0; b < bin.length; b++) {
ret += bin[b] == "0" ? "100" : "110";
}
}
// End bits
ret += "1001";
return {
data: ret,
text: this.string
};
};
MSI.prototype.valid = function valid() {
return this.string.search(/^[0-9]+$/) !== -1;
};
return MSI;
}();
function addZeroes(number, n) {
for (var i = 0; i < n; i++) {
number = "0" + number;
}
return number;
}
exports.default = MSI;
/***/ },
/* 2 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// This is the master class, it does require the start code to be
// included in the string
var CODE128 = function () {
function CODE128(string) {
_classCallCheck(this, CODE128);
// Fill the bytes variable with the ascii codes of string
this.bytes = [];
for (var i = 0; i < string.length; ++i) {
this.bytes.push(string.charCodeAt(i));
}
// First element should be startcode, remove that
this.string = string.substring(1);
// Data for each character, the last characters will not be encoded but are used for error correction
// Numbers encode to (n + 1000) -> binary; 740 -> (740 + 1000).toString(2) -> "11011001100"
this.encodings = [// + 1000
740, 644, 638, 176, 164, 100, 224, 220, 124, 608, 604, 572, 436, 244, 230, 484, 260, 254, 650, 628, 614, 764, 652, 902, 868, 836, 830, 892, 844, 842, 752, 734, 590, 304, 112, 94, 416, 128, 122, 672, 576, 570, 464, 422, 134, 496, 478, 142, 910, 678, 582, 768, 762, 774, 880, 862, 814, 896, 890, 818, 914, 602, 930, 328, 292, 200, 158, 68, 62, 424, 412, 232, 218, 76, 74, 554, 616, 978, 556, 146, 340, 212, 182, 508, 268, 266, 956, 940, 938, 758, 782, 974, 400, 310, 118, 512, 506, 960, 954, 502, 518, 886, 966, /* Start codes */668, 680, 692, 5379];
}
// The public encoding function
CODE128.prototype.encode = function encode() {
var encodingResult;
var bytes = this.bytes;
// Remove the startcode from the bytes and set its index
var startIndex = bytes.shift() - 105;
// Start encode with the right type
if (startIndex === 103) {
encodingResult = this.nextA(bytes, 1);
} else if (startIndex === 104) {
encodingResult = this.nextB(bytes, 1);
} else if (startIndex === 105) {
encodingResult = this.nextC(bytes, 1);
}
return {
text: this.string.replace(/[^\x20-\x7E]/g, ""),
data:
// Add the start bits
this.getEncoding(startIndex) +
// Add the encoded bits
encodingResult.result +
// Add the checksum
this.getEncoding((encodingResult.checksum + startIndex) % 103) +
// Add the end bits
this.getEncoding(106)
};
};
CODE128.prototype.getEncoding = function getEncoding(n) {
return this.encodings[n] ? (this.encodings[n] + 1000).toString(2) : '';
};
// Use the regexp variable for validation
CODE128.prototype.valid = function valid() {
// ASCII value ranges 0-127, 200-211
return this.string.search(/^[\x00-\x7F\xC8-\xD3]+$/) !== -1;
};
CODE128.prototype.nextA = function nextA(bytes, depth) {
if (bytes.length <= 0) {
return { "result": "", "checksum": 0 };
}
var next, index;
// Special characters
if (bytes[0] >= 200) {
index = bytes[0] - 105;
// Remove first element
bytes.shift();
// Swap to CODE128C
if (index === 99) {
next = this.nextC(bytes, depth + 1);
}
// Swap to CODE128B
else if (index === 100) {
next = this.nextB(bytes, depth + 1);
}
// Shift
else if (index === 98) {
// Convert the next character so that is encoded correctly
bytes[0] = bytes[0] > 95 ? bytes[0] - 96 : bytes[0];
next = this.nextA(bytes, depth + 1);
}
// Continue on CODE128A but encode a special character
else {
next = this.nextA(bytes, depth + 1);
}
}
// Continue encoding of CODE128A
else {
var charCode = bytes[0];
index = charCode < 32 ? charCode + 64 : charCode - 32;
// Remove first element
bytes.shift();
next = this.nextA(bytes, depth + 1);
}
// Get the correct binary encoding and calculate the weight
var enc = this.getEncoding(index);
var weight = index * depth;
return {
"result": enc + next.result,
"checksum": weight + next.checksum
};
};
CODE128.prototype.nextB = function nextB(bytes, depth) {
if (bytes.length <= 0) {
return { "result": "", "checksum": 0 };
}
var next, index;
// Special characters
if (bytes[0] >= 200) {
index = bytes[0] - 105;
// Remove first element
bytes.shift();
// Swap to CODE128C
if (index === 99) {
next = this.nextC(bytes, depth + 1);
}
// Swap to CODE128A
else if (index === 101) {
next = this.nextA(bytes, depth + 1);
}
// Shift
else if (index === 98) {
// Convert the next character so that is encoded correctly
bytes[0] = bytes[0] < 32 ? bytes[0] + 96 : bytes[0];
next = this.nextB(bytes, depth + 1);
}
// Continue on CODE128B but encode a special character
else {
next = this.nextB(bytes, depth + 1);
}
}
// Continue encoding of CODE128B
else {
index = bytes[0] - 32;
bytes.shift();
next = this.nextB(bytes, depth + 1);
}
// Get the correct binary encoding and calculate the weight
var enc = this.getEncoding(index);
var weight = index * depth;
return { "result": enc + next.result, "checksum": weight + next.checksum };
};
CODE128.prototype.nextC = function nextC(bytes, depth) {
if (bytes.length <= 0) {
return { "result": "", "checksum": 0 };
}
var next, index;
// Special characters
if (bytes[0] >= 200) {
index = bytes[0] - 105;
// Remove first element
bytes.shift();
// Swap to CODE128B
if (index === 100) {
next = this.nextB(bytes, depth + 1);
}
// Swap to CODE128A
else if (index === 101) {
next = this.nextA(bytes, depth + 1);
}
// Continue on CODE128C but encode a special character
else {
next = this.nextC(bytes, depth + 1);
}
}
// Continue encoding of CODE128C
else {
index = (bytes[0] - 48) * 10 + bytes[1] - 48;
bytes.shift();
bytes.shift();
next = this.nextC(bytes, depth + 1);
}
// Get the correct binary encoding and calculate the weight
var enc = this.getEncoding(index);
var weight = index * depth;
return { "result": enc + next.result, "checksum": weight + next.checksum };
};
return CODE128;
}();
exports.default = CODE128;
/***/ },
/* 3 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mod10 = mod10;
exports.mod11 = mod11;
function mod10(number) {
var sum = 0;
for (var i = 0; i < number.length; i++) {
var n = parseInt(number[i]);
if ((i + number.length) % 2 === 0) {
sum += n;
} else {
sum += n * 2 % 10 + Math.floor(n * 2 / 10);
}
}
return (10 - sum % 10) % 10;
}
function mod11(number) {
var sum = 0;
var weights = [2, 3, 4, 5, 6, 7];
for (var i = 0; i < number.length; i++) {
var n = parseInt(number[number.length - 1 - i]);
sum += weights[i % weights.length] * n;
}
return (11 - sum % 11) % 11;
}
/***/ },
/* 4 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = merge;
function merge(old, replaceObj) {
var newMerge = {};
var k;
for (k in old) {
if (old.hasOwnProperty(k)) {
newMerge[k] = old[k];
}
}
for (k in replaceObj) {
if (replaceObj.hasOwnProperty(k) && typeof replaceObj[k] !== "undefined") {
newMerge[k] = replaceObj[k];
}
}
return newMerge;
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CODE = __webpack_require__(16);
var _CODE2 = __webpack_require__(15);
var _EAN_UPC = __webpack_require__(22);
var _ITF = __webpack_require__(25);
var _ITF2 = __webpack_require__(24);
var _MSI = __webpack_require__(30);
var _pharmacode = __webpack_require__(31);
var _GenericBarcode = __webpack_require__(23);
exports.default = {
CODE39: _CODE.CODE39,
CODE128: _CODE2.CODE128, CODE128A: _CODE2.CODE128A, CODE128B: _CODE2.CODE128B, CODE128C: _CODE2.CODE128C,
EAN13: _EAN_UPC.EAN13, EAN8: _EAN_UPC.EAN8, EAN5: _EAN_UPC.EAN5, EAN2: _EAN_UPC.EAN2, UPC: _EAN_UPC.UPC,
ITF14: _ITF.ITF14,
ITF: _ITF2.ITF,
MSI: _MSI.MSI, MSI10: _MSI.MSI10, MSI11: _MSI.MSI11, MSI1010: _MSI.MSI1010, MSI1110: _MSI.MSI1110,
pharmacode: _pharmacode.pharmacode,
GenericBarcode: _GenericBarcode.GenericBarcode
};
/***/ },
/* 6 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = fixOptions;
function fixOptions(options) {
// Fix the margins
options.marginTop = options.marginTop || options.margin;
options.marginBottom = options.marginBottom || options.margin;
options.marginRight = options.marginRight || options.margin;
options.marginLeft = options.marginLeft || options.margin;
return options;
}
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _optionsFromStrings = __webpack_require__(32);
var _optionsFromStrings2 = _interopRequireDefault(_optionsFromStrings);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getOptionsFromElement(element, defaults) {
var options = {};
for (var property in defaults) {
// jsbarcode-*
if (element.hasAttribute("jsbarcode-" + property.toLowerCase())) {
options[property] = element.getAttribute("jsbarcode-" + property.toLowerCase());
}
// data-*
if (element.hasAttribute("data-" + property.toLowerCase())) {
options[property] = element.getAttribute("data-" + property.toLowerCase());
}
}
options["value"] = element.getAttribute("jsbarcode-value") || element.getAttribute("data-value");
// Since all atributes are string they need to be converted to integers
options = (0, _optionsFromStrings2.default)(options);
return options;
}
exports.default = getOptionsFromElement;
/***/ },
/* 8 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = linearizeEncodings;
// Encodings can be nestled like [[1-1, 1-2], 2, [3-1, 3-2]
// Convert to [1-1, 1-2, 2, 3-1, 3-2]
function linearizeEncodings(encodings) {
var linearEncodings = [];
function nextLevel(encoded) {
if (Array.isArray(encoded)) {
for (var i = 0; i < encoded.length; i++) {
nextLevel(encoded[i]);
}
} else {
encoded.text = encoded.text || "";
encoded.data = encoded.data || "";
linearEncodings.push(encoded);
}
}
nextLevel(encodings);
return linearEncodings;
}
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _canvas = __webpack_require__(33);
var _canvas2 = _interopRequireDefault(_canvas);
var _svg = __webpack_require__(34);
var _svg2 = _interopRequireDefault(_svg);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
canvas: _canvas2.default,
svg: _svg2.default
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
var _barcodes = __webpack_require__(5);
var _barcodes2 = _interopRequireDefault(_barcodes);
var _renderers = __webpack_require__(9);
var _renderers2 = _interopRequireDefault(_renderers);
var _merge = __webpack_require__(4);
var _merge2 = _interopRequireDefault(_merge);
var _linearizeEncodings = __webpack_require__(8);
var _linearizeEncodings2 = _interopRequireDefault(_linearizeEncodings);
var _fixOptions = __webpack_require__(6);
var _fixOptions2 = _interopRequireDefault(_fixOptions);
var _getOptionsFromElement = __webpack_require__(7);
var _getOptionsFromElement2 = _interopRequireDefault(_getOptionsFromElement);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// The protype of the object returned from the JsBarcode() call
// Help functions
// Import all the barcodes
var API = function API() {};
// The first call of the library API
// Will return an object with all barcodes calls and the information needed
// when the rendering function is called and options the barcodes might need
// Import the renderers
var JsBarcode = function JsBarcode(element, text, options) {
var api = new API();
if (typeof element === "undefined") {
throw Error("No element to render on was provided.");
}
// Variables that will be pased through the API calls
api._renderProperties = getRenderProperies(element);
api._encodings = [];
api._options = defaults;
// If text is set, use simple syntax
if (typeof text !== "undefined") {
options = options || {};
if (!options.format) {
options.format = autoSelectBarcode();
}
api.options(options);
api[options.format](text, options);
api.render();
}
return api;
};
// To make tests work TODO: remove
JsBarcode.getModule = function (name) {
return _barcodes2.default[name];
};
// Register all barcodes
for (var name in _barcodes2.default) {
if (_barcodes2.default.hasOwnProperty(name)) {
// Security check if the propery is a prototype property
registerBarcode(_barcodes2.default, name);
}
}
function registerBarcode(barcodes, name) {
API.prototype[name] = API.prototype[name.toUpperCase()] = API.prototype[name.toLowerCase()] = function (text, options) {
var newOptions = (0, _merge2.default)(this._options, options);
var Encoder = barcodes[name];
var encoded = encode(text, Encoder, newOptions);
this._encodings.push(encoded);
return this;
};
}
function encode(text, Encoder, options) {
// Ensure that text is a string
text = "" + text;
var encoder = new Encoder(text, options);
// If the input is not valid for the encoder, throw error.
// If the valid callback option is set, call it instead of throwing error
if (!encoder.valid()) {
if (options.valid === defaults.valid) {
throw new Error('"' + text + '" is not a valid input for ' + name);
} else {
options.valid(false);
}
}
var encoded = encoder.encode();
// Encodings can be nestled like [[1-1, 1-2], 2, [3-1, 3-2]
// Convert to [1-1, 1-2, 2, 3-1, 3-2]
encoded = (0, _linearizeEncodings2.default)(encoded);
// Merge
for (var i = 0; i < encoded.length; i++) {
encoded[i].options = (0, _merge2.default)(options, encoded[i].options);
}
return encoded;
}
function autoSelectBarcode() {
// If CODE128 exists. Use it
if (_barcodes2.default["CODE128"]) {
return "CODE128";
}
// Else, take the first (probably only) barcode
return Object.keys(_barcodes2.default)[0];
}
// Sets global encoder options
// Added to the api by the JsBarcode function
API.prototype.options = function (options) {
this._options = (0, _merge2.default)(this._options, options);
return this;
};
// Will create a blank space (usually in between barcodes)
API.prototype.blank = function (size) {
var zeroes = "0".repeat(size);
this._encodings.push({ data: zeroes });
return this;
};
API.prototype.init = function () {
// this._renderProperties can be
if (!Array.isArray(this._renderProperties)) {
this._renderProperties = [this._renderProperties];
}
var renderProperty;
for (var i in this._renderProperties) {
renderProperty = this._renderProperties[i];
var options = (0, _merge2.default)(this._options, renderProperty.options);
if (options.format == "auto") {
options.format = autoSelectBarcode();
}
var text = options.value;
var Encoder = _barcodes2.default[options.format.toUpperCase()];
var encoded = encode(text, Encoder, options);
render(renderProperty, encoded, options);
}
};
// The render API call. Calls the real render function.
API.prototype.render = function () {
if (Array.isArray(this._renderProperties)) {
for (var i in this._renderProperties) {
render(this._renderProperties[i], this._encodings, this._options);
}
} else {
render(this._renderProperties, this._encodings, this._options);
}
this._options.valid(true);
return this;
};
// Prepares the encodings and calls the renderer
function render(renderProperties, encodings, options) {
var renderer = _renderers2.default[renderProperties.renderer];
encodings = (0, _linearizeEncodings2.default)(encodings);
for (var i = 0; i < encodings.length; i++) {
encodings[i].options = (0, _merge2.default)(options, encodings[i].options);
(0, _fixOptions2.default)(encodings[i].options);
}
(0, _fixOptions2.default)(options);
renderer(renderProperties.element, encodings, options);
if (renderProperties.afterRender) {
renderProperties.afterRender();
}
}
// Export to browser
if (typeof window !== "undefined") {
window.JsBarcode = JsBarcode;
}
// Export to jQuery
if (typeof jQuery !== 'undefined') {
jQuery.fn.JsBarcode = function (content, options) {
var elementArray = [];
jQuery(this).each(function () {
elementArray.push(this);
});
return JsBarcode(elementArray, content, options);
};
}
// Export to commonJS
module.exports = JsBarcode;
// Takes an element and returns an object with information about how
// it should be rendered
// This could also return an array with these objects
// {
// element: The element that the renderer should draw on
// renderer: The name of the renderer
// afterRender (optional): If something has to done after the renderer
// completed, calls afterRender (function)
// options (optional): Options that can be defined in the element
// }
function getRenderProperies(element) {
// If the element is a string, query select call again
if (typeof element === "string") {
var selector = document.querySelectorAll(element);
if (selector.length === 0) {
throw new Error("No element found");
} else {
var returnArray = [];
for (var i = 0; i < selector.length; i++) {
returnArray.push(getRenderProperies(selector[i]));
}
return returnArray;
}
}
// If element is array. Recursivly call with every object in the array
else if (Array.isArray(element)) {
var returnArray = [];
for (var i = 0; i < element.length; i++) {
returnArray.push(getRenderProperies(element[i]));
}
return returnArray;
}
// If element, render on canvas and set the uri as src
else if (typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLImageElement) {
var canvas = document.createElement('canvas');
return {
element: canvas,
options: (0, _getOptionsFromElement2.default)(element, defaults),
renderer: "canvas",
afterRender: function afterRender() {
element.setAttribute("src", canvas.toDataURL());
}
};
}
// If SVG
else if (typeof SVGElement !== 'undefined' && element instanceof SVGElement) {
return {
element: element,
options: (0, _getOptionsFromElement2.default)(element, defaults),
renderer: "svg"
};
}
// If canvas (in browser)
else if (typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLCanvasElement) {
return {
element: element,
options: (0, _getOptionsFromElement2.default)(element, defaults),
renderer: "canvas"
};
}
// If canvas (in node)
else if (element.getContext) {
return {
element: element,
renderer: "canvas"
};
} else {
throw new Error("Not supported type to render on.");
}
}
var defaults = {
width: 2,
height: 100,
format: "auto",
displayValue: true,
fontOptions: "",
font: "monospace",
textAlign: "center",
textPosition: "bottom",
textMargin: 2,
fontSize: 20,
background: "#ffffff",
lineColor: "#000000",
margin: 10,
marginTop: undefined,
marginBottom: undefined,
marginLeft: undefined,
marginRight: undefined,
valid: function valid(_valid) {}
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CODE2 = __webpack_require__(2);
var _CODE3 = _interopRequireDefault(_CODE2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var CODE128A = function (_CODE) {
_inherits(CODE128A, _CODE);
function CODE128A(string) {
_classCallCheck(this, CODE128A);
return _possibleConstructorReturn(this, _CODE.call(this, String.fromCharCode(208) + string));
}
CODE128A.prototype.valid = function valid() {
return this.string.search(/^[\x00-\x5F\xC8-\xCF]+$/) !== -1;
};
return CODE128A;
}(_CODE3.default);
exports.default = CODE128A;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CODE2 = __webpack_require__(2);
var _CODE3 = _interopRequireDefault(_CODE2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var CODE128B = function (_CODE) {
_inherits(CODE128B, _CODE);
function CODE128B(string) {
_classCallCheck(this, CODE128B);
return _possibleConstructorReturn(this, _CODE.call(this, String.fromCharCode(209) + string));
}
CODE128B.prototype.valid = function valid() {
return this.string.search(/^[\x20-\x7F\xC8-\xCF]+$/) !== -1;
};
return CODE128B;
}(_CODE3.default);
exports.default = CODE128B;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CODE2 = __webpack_require__(2);
var _CODE3 = _interopRequireDefault(_CODE2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var CODE128C = function (_CODE) {
_inherits(CODE128C, _CODE);
function CODE128C(string) {
_classCallCheck(this, CODE128C);
return _possibleConstructorReturn(this, _CODE.call(this, String.fromCharCode(210) + string));
}
CODE128C.prototype.valid = function valid() {
return this.string.search(/^(\xCF*[0-9]{2}\xCF*)+$/) !== -1;
};
return CODE128C;
}(_CODE3.default);
exports.default = CODE128C;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CODE2 = __webpack_require__(2);
var _CODE3 = _interopRequireDefault(_CODE2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var CODE128AUTO = function (_CODE) {
_inherits(CODE128AUTO, _CODE);
function CODE128AUTO(string) {
_classCallCheck(this, CODE128AUTO);
// ASCII value ranges 0-127, 200-211
var _this = _possibleConstructorReturn(this, _CODE.call(this, string));
if (string.search(/^[\x00-\x7F\xC8-\xD3]+$/) !== -1) {
var _this = _possibleConstructorReturn(this, _CODE.call(this, autoSelectModes(string)));
} else {
var _this = _possibleConstructorReturn(this, _CODE.call(this, string));
}
return _possibleConstructorReturn(_this);
}
return CODE128AUTO;
}(_CODE3.default);
function autoSelectModes(string) {
// ASCII ranges 0-98 and 200-207 (FUNCs and SHIFTs)
var aLength = string.match(/^[\x00-\x5F\xC8-\xCF]*/)[0].length;
// ASCII ranges 32-127 and 200-207 (FUNCs and SHIFTs)
var bLength = string.match(/^[\x20-\x7F\xC8-\xCF]*/)[0].length;
// Number pairs or [FNC1]
var cLength = string.match(/^(\xCF*[0-9]{2}\xCF*)*/)[0].length;
var newString;
// Select CODE128C if the string start with enough digits
if (cLength >= 2) {
newString = String.fromCharCode(210) + autoSelectFromC(string);
}
// Select A/C depending on the longest match
else if (aLength > bLength) {
newString = String.fromCharCode(208) + autoSelectFromA(string);
} else {
newString = String.fromCharCode(209) + autoSelectFromB(string);
}
newString = newString.replace(/[\xCD\xCE]([^])[\xCD\xCE]/, function (match, char) {
return String.fromCharCode(203) + char;
});
return newString;
}
function autoSelectFromA(string) {
var untilC = string.match(/^([\x00-\x5F\xC8-\xCF]+?)(([0-9]{2}){2,})([^0-9]|$)/);
if (untilC) {
return untilC[1] + String.fromCharCode(204) + autoSelectFromC(string.substring(untilC[1].length));
}
var aChars = string.match(/^[\x00-\x5F\xC8-\xCF]+/);
if (aChars[0].length === string.length) {
return string;
}
return aChars[0] + String.fromCharCode(205) + autoSelectFromB(string.substring(aChars[0].length));
}
function autoSelectFromB(string) {
var untilC = string.match(/^([\x20-\x7F\xC8-\xCF]+?)(([0-9]{2}){2,})([^0-9]|$)/);
if (untilC) {
return untilC[1] + String.fromCharCode(204) + autoSelectFromC(string.substring(untilC[1].length));
}
var bChars = string.match(/^[\x20-\x7F\xC8-\xCF]+/);
if (bChars[0].length === string.length) {
return string;
}
return bChars[0] + String.fromCharCode(206) + autoSelectFromA(string.substring(bChars[0].length));
}
function autoSelectFromC(string) {
var cMatch = string.match(/^(\xCF*[0-9]{2}\xCF*)+/)[0];
var length = cMatch.length;
if (length === string.length) {
return string;
}
string = string.substring(length);
// Select A/B depending on the longest match
var aLength = string.match(/^[\x00-\x5F\xC8-\xCF]*/)[0].length;
var bLength = string.match(/^[\x20-\x7F\xC8-\xCF]*/)[0].length;
if (aLength >= bLength) {
return cMatch + String.fromCharCode(206) + autoSelectFromA(string);
} else {
return cMatch + String.fromCharCode(205) + autoSelectFromB(string);
}
}
exports.default = CODE128AUTO;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CODE128C = exports.CODE128B = exports.CODE128A = exports.CODE128 = undefined;
var _CODE128_AUTO = __webpack_require__(14);
var _CODE128_AUTO2 = _interopRequireDefault(_CODE128_AUTO);
var _CODE128A = __webpack_require__(11);
var _CODE128A2 = _interopRequireDefault(_CODE128A);
var _CODE128B = __webpack_require__(12);
var _CODE128B2 = _interopRequireDefault(_CODE128B);
var _CODE128C = __webpack_require__(13);
var _CODE128C2 = _interopRequireDefault(_CODE128C);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.CODE128 = _CODE128_AUTO2.default;
exports.CODE128A = _CODE128A2.default;
exports.CODE128B = _CODE128B2.default;
exports.CODE128C = _CODE128C2.default;
/***/ },
/* 16 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// Encoding documentation:
// https://en.wikipedia.org/wiki/Code_39#Encoding
var CODE39 = function () {
function CODE39(string, options) {
_classCallCheck(this, CODE39);
this.string = string.toUpperCase();
// Enable mod43 checksum?
this.mod43Enabled = options.mod43 || false;
// All characters. The position in the array is the (checksum) value
this.characters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "-", ".", " ", "$", "/", "+", "%", "*"];
// The decimal representation of the characters, is converted to the
// corresponding binary with the getEncoding function
this.encodings = [20957, 29783, 23639, 30485, 20951, 29813, 23669, 20855, 29789, 23645, 29975, 23831, 30533, 22295, 30149, 24005, 21623, 29981, 23837, 22301, 30023, 23879, 30545, 22343, 30161, 24017, 21959, 30065, 23921, 22385, 29015, 18263, 29141, 17879, 29045, 18293, 17783, 29021, 18269, 17477, 17489, 17681, 20753, 35770];
}
// Get the binary representation of a character by converting the encodings
// from decimal to binary
CODE39.prototype.getEncoding = function getEncoding(character) {
return this.getBinary(this.characterValue(character));
};
CODE39.prototype.getBinary = function getBinary(characterValue) {
return this.encodings[characterValue].toString(2);
};
CODE39.prototype.getCharacter = function getCharacter(characterValue) {
return this.characters[characterValue];
};
CODE39.prototype.characterValue = function characterValue(character) {
return this.characters.indexOf(character);
};
CODE39.prototype.encode = function encode() {
var string = this.string;
// First character is always a *
var result = this.getEncoding("*");
// Take every character and add the binary representation to the result
for (var i = 0; i < this.string.length; i++) {
result += this.getEncoding(this.string[i]) + "0";
}
// Calculate mod43 checksum if enabled
if (this.mod43Enabled) {
var checksum = 0;
for (var i = 0; i < this.string.length; i++) {
checksum += this.characterValue(this.string[i]);
}
checksum = checksum % 43;
result += this.getBinary(checksum) + "0";
string += this.getCharacter(checksum);
}
// Last character is always a *
result += this.getEncoding("*");
return {
data: result,
text: string
};
};
CODE39.prototype.valid = function valid() {
return this.string.search(/^[0-9A-Z\-\.\ \$\/\+\%]+$/) !== -1;
};
return CODE39;
}();
exports.CODE39 = CODE39;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ean_encoder = __webpack_require__(0);
var _ean_encoder2 = _interopRequireDefault(_ean_encoder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // Encoding documentation:
// https://en.wikipedia.org/wiki/International_Article_Number_(EAN)#Binary_encoding_of_data_digits_into_EAN-13_barcode
var EAN13 = function () {
function EAN13(string, options) {
_classCallCheck(this, EAN13);
// Add checksum if it does not exist
if (string.search(/^[0-9]{12}$/) !== -1) {
this.string = string + this.checksum(string);
} else {
this.string = string;
}
this.displayValue = options.displayValue;
// Define the EAN-13 structure
this.structure = ["LLLLLL", "LLGLGG", "LLGGLG", "LLGGGL", "LGLLGG", "LGGLLG", "LGGGLL", "LGLGLG", "LGLGGL", "LGGLGL"];
// Make sure the font is not bigger than the space between the guard bars
if (options.fontSize > options.width * 10) {
this.fontSize = options.width * 10;
} else {
this.fontSize = options.fontSize;
}
// Make the guard bars go down half the way of the text
this.guardHeight = options.height + this.fontSize / 2 + options.textMargin;
// Adds a last character to the end of the barcode
this.lastChar = options.lastChar;
}
EAN13.prototype.valid = function valid() {
return this.string.search(/^[0-9]{13}$/) !== -1 && this.string[12] == this.checksum(this.string);
};
EAN13.prototype.encode = function encode() {
var encoder = new _ean_encoder2.default();
var result = [];
var structure = this.structure[this.string[0]];
// Get the string to be encoded on the left side of the EAN code
var leftSide = this.string.substr(1, 6);
// Get the string to be encoded on the right side of the EAN code
var rightSide = this.string.substr(7, 6);
// Add the first digigt
if (this.displayValue) {
result.push({
data: "000000000000",
text: this.string[0],
options: { textAlign: "left", fontSize: this.fontSize }
});
}
// Add the guard bars
result.push({
data: "101",
options: { height: this.guardHeight }
});
// Add the left side
result.push({
data: encoder.encode(leftSide, structure),
text: leftSide,
options: { fontSize: this.fontSize }
});
// Add the middle bits
result.push({
data: "01010",
options: { height: this.guardHeight }
});
// Add the right side
result.push({
data: encoder.encode(rightSide, "RRRRRR"),
text: rightSide,
options: { fontSize: this.fontSize }
});
// Add the end bits
result.push({
data: "101",
options: { height: this.guardHeight }
});
if (this.lastChar && this.displayValue) {
result.push({ data: "00" });
result.push({
data: "00000",
text: this.lastChar,
options: { fontSize: this.fontSize }
});
}
return result;
};
// Calulate the checksum digit
// https://en.wikipedia.org/wiki/International_Article_Number_(EAN)#Calculation_of_checksum_digit
EAN13.prototype.checksum = function checksum(number) {
var result = 0;
var i;
for (i = 0; i < 12; i += 2) {
result += parseInt(number[i]);
}
for (i = 1; i < 12; i += 2) {
result += parseInt(number[i]) * 3;
}
return (10 - result % 10) % 10;
};
return EAN13;
}();
exports.default = EAN13;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ean_encoder = __webpack_require__(0);
var _ean_encoder2 = _interopRequireDefault(_ean_encoder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // Encoding documentation:
// https://en.wikipedia.org/wiki/EAN_2#Encoding
var EAN2 = function () {
function EAN2(string) {
_classCallCheck(this, EAN2);
this.string = string;
this.structure = ["LL", "LG", "GL", "GG"];
}
EAN2.prototype.valid = function valid() {
return this.string.search(/^[0-9]{2}$/) !== -1;
};
EAN2.prototype.encode = function encode() {
var encoder = new _ean_encoder2.default();
// Choose the structure based on the number mod 4
var structure = this.structure[parseInt(this.string) % 4];
// Start bits
var result = "1011";
// Encode the two digits with 01 in between
result += encoder.encode(this.string, structure, "01");
return {
data: result,
text: this.string
};
};
return EAN2;
}();
exports.default = EAN2;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ean_encoder = __webpack_require__(0);
var _ean_encoder2 = _interopRequireDefault(_ean_encoder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // Encoding documentation:
// https://en.wikipedia.org/wiki/EAN_5#Encoding
var EAN5 = function () {
function EAN5(string) {
_classCallCheck(this, EAN5);
this.string = string;
// Define the EAN-13 structure
this.structure = ["GGLLL", "GLGLL", "GLLGL", "GLLLG", "LGGLL", "LLGGL", "LLLGG", "LGLGL", "LGLLG", "LLGLG"];
}
EAN5.prototype.valid = function valid() {
return this.string.search(/^[0-9]{5}$/) !== -1;
};
EAN5.prototype.encode = function encode() {
var encoder = new _ean_encoder2.default();
var checksum = this.checksum();
// Start bits
var result = "1011";
// Use normal ean encoding with 01 in between all digits
result += encoder.encode(this.string, this.structure[checksum], "01");
return {
data: result,
text: this.string
};
};
EAN5.prototype.checksum = function checksum() {
var result = 0;
result += parseInt(this.string[0]) * 3;
result += parseInt(this.string[1]) * 9;
result += parseInt(this.string[2]) * 3;
result += parseInt(this.string[3]) * 9;
result += parseInt(this.string[4]) * 3;
return result % 10;
};
return EAN5;
}();
exports.default = EAN5;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ean_encoder = __webpack_require__(0);
var _ean_encoder2 = _interopRequireDefault(_ean_encoder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // Encoding documentation:
// http://www.barcodeisland.com/ean8.phtml
var EAN8 = function () {
function EAN8(string) {
_classCallCheck(this, EAN8);
// Add checksum if it does not exist
if (string.search(/^[0-9]{7}$/) !== -1) {
this.string = string + this.checksum(string);
} else {
this.string = string;
}
}
EAN8.prototype.valid = function valid() {
return this.string.search(/^[0-9]{8}$/) !== -1 && this.string[7] == this.checksum(this.string);
};
EAN8.prototype.encode = function encode() {
var encoder = new _ean_encoder2.default();
// Create the return variable
var result = "";
// Get the number to be encoded on the left side of the EAN code
var leftSide = this.string.substr(0, 4);
// Get the number to be encoded on the right side of the EAN code
var rightSide = this.string.substr(4, 4);
// Add the start bits
result += encoder.startBin;
// Add the left side
result += encoder.encode(leftSide, "LLLL");
// Add the middle bits
result += encoder.middleBin;
// Add the right side
result += encoder.encode(rightSide, "RRRR");
// Add the end bits
result += encoder.endBin;
return {
data: result,
text: this.string
};
};
// Calulate the checksum digit
EAN8.prototype.checksum = function checksum(number) {
var result = 0;
var i;
for (i = 0; i < 7; i += 2) {
result += parseInt(number[i]) * 3;
}
for (i = 1; i < 7; i += 2) {
result += parseInt(number[i]);
}
return (10 - result % 10) % 10;
};
return EAN8;
}();
exports.default = EAN8;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ean_encoder = __webpack_require__(0);
var _ean_encoder2 = _interopRequireDefault(_ean_encoder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // Encoding documentation:
// https://en.wikipedia.org/wiki/Universal_Product_Code#Encoding
var UPC = function () {
function UPC(string, options) {
_classCallCheck(this, UPC);
// Add checksum if it does not exist
if (string.search(/^[0-9]{11}$/) !== -1) {
this.string = string + this.checksum(string);
} else {
this.string = string;
}
this.displayValue = options.displayValue;
// Make sure the font is not bigger than the space between the guard bars
if (options.fontSize > options.width * 10) {
this.fontSize = options.width * 10;
} else {
this.fontSize = options.fontSize;
}
// Make the guard bars go down half the way of the text
this.guardHeight = options.height + this.fontSize / 2 + options.textMargin;
}
UPC.prototype.valid = function valid() {
return this.string.search(/^[0-9]{12}$/) !== -1 && this.string[11] == this.checksum(this.string);
};
UPC.prototype.encode = function encode() {
var encoder = new _ean_encoder2.default();
var result = [];
// Add the first digigt
if (this.displayValue) {
result.push({
data: "00000000",
text: this.string[0],
options: { textAlign: "left", fontSize: this.fontSize }
});
}
// Add the guard bars
result.push({
data: "101" + encoder.encode(this.string[0], "L"),
options: { height: this.guardHeight }
});
// Add the left side
result.push({
data: encoder.encode(this.string.substr(1, 5), "LLLLL"),
text: this.string.substr(1, 5),
options: { fontSize: this.fontSize }
});
// Add the middle bits
result.push({
data: "01010",
options: { height: this.guardHeight }
});
// Add the right side
result.push({
data: encoder.encode(this.string.substr(6, 5), "RRRRR"),
text: this.string.substr(6, 5),
options: { fontSize: this.fontSize }
});
// Add the end bits
result.push({
data: encoder.encode(this.string[11], "R") + "101",
options: { height: this.guardHeight }
});
// Add the last digit
if (this.displayValue) {
result.push({
data: "00000000",
text: this.string[11],
options: { textAlign: "right", fontSize: this.fontSize }
});
}
return result;
};
// Calulate the checksum digit
// https://en.wikipedia.org/wiki/International_Article_Number_(EAN)#Calculation_of_checksum_digit
UPC.prototype.checksum = function checksum(number) {
var result = 0;
var i;
for (i = 1; i < 11; i += 2) {
result += parseInt(number[i]);
}
for (i = 0; i < 11; i += 2) {
result += parseInt(number[i]) * 3;
}
return (10 - result % 10) % 10;
};
return UPC;
}();
exports.default = UPC;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UPC = exports.EAN2 = exports.EAN5 = exports.EAN8 = exports.EAN13 = undefined;
var _EAN = __webpack_require__(17);
var _EAN2 = _interopRequireDefault(_EAN);
var _EAN3 = __webpack_require__(20);
var _EAN4 = _interopRequireDefault(_EAN3);
var _EAN5 = __webpack_require__(19);
var _EAN6 = _interopRequireDefault(_EAN5);
var _EAN7 = __webpack_require__(18);
var _EAN8 = _interopRequireDefault(_EAN7);
var _UPC = __webpack_require__(21);
var _UPC2 = _interopRequireDefault(_UPC);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.EAN13 = _EAN2.default;
exports.EAN8 = _EAN4.default;
exports.EAN5 = _EAN6.default;
exports.EAN2 = _EAN8.default;
exports.UPC = _UPC2.default;
/***/ },
/* 23 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var GenericBarcode = function () {
function GenericBarcode(string) {
_classCallCheck(this, GenericBarcode);
this.string = string;
}
// Return the corresponding binary numbers for the data provided
GenericBarcode.prototype.encode = function encode() {
return {
data: "10101010101010101010101010101010101010101",
text: this.string
};
};
// Resturn true/false if the string provided is valid for this encoder
GenericBarcode.prototype.valid = function valid() {
return true;
};
return GenericBarcode;
}();
exports.GenericBarcode = GenericBarcode;
/***/ },
/* 24 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ITF = function () {
function ITF(string) {
_classCallCheck(this, ITF);
this.string = string;
this.binaryRepresentation = {
"0": "00110",
"1": "10001",
"2": "01001",
"3": "11000",
"4": "00101",
"5": "10100",
"6": "01100",
"7": "00011",
"8": "10010",
"9": "01010"
};
}
ITF.prototype.valid = function valid() {
return this.string.search(/^([0-9]{2})+$/) !== -1;
};
ITF.prototype.encode = function encode() {
// Always add the same start bits
var result = "1010";
// Calculate all the digit pairs
for (var i = 0; i < this.string.length; i += 2) {
result += this.calculatePair(this.string.substr(i, 2));
}
// Always add the same end bits
result += "11101";
return {
data: result,
text: this.string
};
};
// Calculate the data of a number pair
ITF.prototype.calculatePair = function calculatePair(numberPair) {
var result = "";
var number1Struct = this.binaryRepresentation[numberPair[0]];
var number2Struct = this.binaryRepresentation[numberPair[1]];
// Take every second bit and add to the result
for (var i = 0; i < 5; i++) {
result += number1Struct[i] == "1" ? "111" : "1";
result += number2Struct[i] == "1" ? "000" : "0";
}
return result;
};
return ITF;
}();
exports.ITF = ITF;
/***/ },
/* 25 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ITF14 = function () {
function ITF14(string) {
_classCallCheck(this, ITF14);
this.string = string;
// Add checksum if it does not exist
if (string.search(/^[0-9]{13}$/) !== -1) {
this.string += this.checksum(string);
}
this.binaryRepresentation = {
"0": "00110",
"1": "10001",
"2": "01001",
"3": "11000",
"4": "00101",
"5": "10100",
"6": "01100",
"7": "00011",
"8": "10010",
"9": "01010"
};
}
ITF14.prototype.valid = function valid() {
return this.string.search(/^[0-9]{14}$/) !== -1 && this.string[13] == this.checksum();
};
ITF14.prototype.encode = function encode() {
var result = "1010";
// Calculate all the digit pairs
for (var i = 0; i < 14; i += 2) {
result += this.calculatePair(this.string.substr(i, 2));
}
// Always add the same end bits
result += "11101";
return {
data: result,
text: this.string
};
};
// Calculate the data of a number pair
ITF14.prototype.calculatePair = function calculatePair(numberPair) {
var result = "";
var number1Struct = this.binaryRepresentation[numberPair[0]];
var number2Struct = this.binaryRepresentation[numberPair[1]];
// Take every second bit and add to the result
for (var i = 0; i < 5; i++) {
result += number1Struct[i] == "1" ? "111" : "1";
result += number2Struct[i] == "1" ? "000" : "0";
}
return result;
};
// Calulate the checksum digit
ITF14.prototype.checksum = function checksum() {
var result = 0;
for (var i = 0; i < 13; i++) {
result += parseInt(this.string[i]) * (3 - i % 2 * 2);
}
return 10 - result % 10;
};
return ITF14;
}();
exports.ITF14 = ITF14;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _MSI2 = __webpack_require__(1);
var _MSI3 = _interopRequireDefault(_MSI2);
var _checksums = __webpack_require__(3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MSI10 = function (_MSI) {
_inherits(MSI10, _MSI);
function MSI10(string) {
_classCallCheck(this, MSI10);
var _this = _possibleConstructorReturn(this, _MSI.call(this, string));
_this.string += (0, _checksums.mod10)(_this.string);
return _this;
}
return MSI10;
}(_MSI3.default);
exports.default = MSI10;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _MSI2 = __webpack_require__(1);
var _MSI3 = _interopRequireDefault(_MSI2);
var _checksums = __webpack_require__(3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MSI1010 = function (_MSI) {
_inherits(MSI1010, _MSI);
function MSI1010(string) {
_classCallCheck(this, MSI1010);
var _this = _possibleConstructorReturn(this, _MSI.call(this, string));
_this.string += (0, _checksums.mod10)(_this.string);
_this.string += (0, _checksums.mod10)(_this.string);
return _this;
}
return MSI1010;
}(_MSI3.default);
exports.default = MSI1010;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _MSI2 = __webpack_require__(1);
var _MSI3 = _interopRequireDefault(_MSI2);
var _checksums = __webpack_require__(3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MSI11 = function (_MSI) {
_inherits(MSI11, _MSI);
function MSI11(string) {
_classCallCheck(this, MSI11);
var _this = _possibleConstructorReturn(this, _MSI.call(this, string));
_this.string += (0, _checksums.mod11)(_this.string);
return _this;
}
return MSI11;
}(_MSI3.default);
exports.default = MSI11;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _MSI2 = __webpack_require__(1);
var _MSI3 = _interopRequireDefault(_MSI2);
var _checksums = __webpack_require__(3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MSI1110 = function (_MSI) {
_inherits(MSI1110, _MSI);
function MSI1110(string) {
_classCallCheck(this, MSI1110);
var _this = _possibleConstructorReturn(this, _MSI.call(this, string));
_this.string += (0, _checksums.mod11)(_this.string);
_this.string += (0, _checksums.mod10)(_this.string);
return _this;
}
return MSI1110;
}(_MSI3.default);
exports.default = MSI1110;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MSI1110 = exports.MSI1010 = exports.MSI11 = exports.MSI10 = exports.MSI = undefined;
var _MSI = __webpack_require__(1);
var _MSI2 = _interopRequireDefault(_MSI);
var _MSI3 = __webpack_require__(26);
var _MSI4 = _interopRequireDefault(_MSI3);
var _MSI5 = __webpack_require__(28);
var _MSI6 = _interopRequireDefault(_MSI5);
var _MSI7 = __webpack_require__(27);
var _MSI8 = _interopRequireDefault(_MSI7);
var _MSI9 = __webpack_require__(29);
var _MSI10 = _interopRequireDefault(_MSI9);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.MSI = _MSI2.default;
exports.MSI10 = _MSI4.default;
exports.MSI11 = _MSI6.default;
exports.MSI1010 = _MSI8.default;
exports.MSI1110 = _MSI10.default;
/***/ },
/* 31 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// Encoding documentation
// http://www.gomaro.ch/ftproot/Laetus_PHARMA-CODE.pdf
var pharmacode = function () {
function pharmacode(string) {
_classCallCheck(this, pharmacode);
this.number = parseInt(string, 10);
}
pharmacode.prototype.encode = function encode() {
var z = this.number;
var result = "";
// http://i.imgur.com/RMm4UDJ.png
// (source: http://www.gomaro.ch/ftproot/Laetus_PHARMA-CODE.pdf, page: 34)
while (!isNaN(z) && z != 0) {
if (z % 2 === 0) {
// Even
result = "11100" + result;
z = (z - 2) / 2;
} else {
// Odd
result = "100" + result;
z = (z - 1) / 2;
}
}
// Remove the two last zeroes
result = result.slice(0, -2);
return {
data: result,
text: this.number + ""
};
};
pharmacode.prototype.valid = function valid() {
return this.number >= 3 && this.number <= 131070;
};
return pharmacode;
}();
exports.pharmacode = pharmacode;
/***/ },
/* 32 */
/***/ function(module, exports) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = optionsFromStrings;
// Convert string to integers/booleans where it should be
function optionsFromStrings(options) {
var intOptions = ["width", "height", "textMargin", "fontSize", "margin", "marginTop", "marginBottom", "marginLeft", "marginRight"];
for (var intOption in intOptions) {
intOption = intOptions[intOption];
if (typeof options[intOption] === "string") {
options[intOption] = parseInt(options[intOption], 10);
}
}
if (typeof options["displayValue"] === "string") {
options["displayValue"] = options["displayValue"] != "false";
}
return options;
}
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _merge = __webpack_require__(4);
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = renderCanvas;
function renderCanvas(canvas, encodings, options) {
// Abort if the browser does not support HTML5 canvas
if (!canvas.getContext) {
throw new Error('The browser does not support canvas.');
}
prepareCanvas(canvas, options, encodings);
for (var i = 0; i < encodings.length; i++) {
var encodingOptions = (0, _merge2.default)(options, encodings[i].options);
drawCanvasBarcode(canvas, encodingOptions, encodings[i]);
drawCanvasText(canvas, encodingOptions, encodings[i]);
moveCanvasDrawing(canvas, encodings[i]);
}
restoreCanvas(canvas);
}
function prepareCanvas(canvas, options, encodings) {
// Get the canvas context
var ctx = canvas.getContext("2d");
ctx.save();
// Calculate total width
var totalWidth = 0;
var maxHeight = 0;
for (var i = 0; i < encodings.length; i++) {
var _options = (0, _merge2.default)(_options, encodings[i].options);
// Set font
ctx.font = _options.fontOptions + " " + _options.fontSize + "px " + _options.font;
// Calculate the width of the encoding
var textWidth = ctx.measureText(encodings[i].text).width;
var barcodeWidth = encodings[i].data.length * _options.width;
encodings[i].width = Math.ceil(Math.max(textWidth, barcodeWidth));
// Calculate the height of the encoding
var height = _options.height + (_options.displayValue && encodings[i].text.length > 0 ? _options.fontSize : 0) + _options.textMargin + _options.marginTop + _options.marginBottom;
var barcodePadding = 0;
if (_options.displayValue && barcodeWidth < textWidth) {
if (_options.textAlign == "center") {
barcodePadding = Math.floor((textWidth - barcodeWidth) / 2);
} else if (_options.textAlign == "left") {
barcodePadding = 0;
} else if (_options.textAlign == "right") {
barcodePadding = Math.floor(textWidth - barcodeWidth);
}
}
encodings[i].barcodePadding = barcodePadding;
if (height > maxHeight) {
maxHeight = height;
}
totalWidth += encodings[i].width;
}
canvas.width = totalWidth + options.marginLeft + options.marginRight;
canvas.height = maxHeight;
// Paint the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (options.background) {
ctx.fillStyle = options.background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.translate(options.marginLeft, 0);
}
function drawCanvasBarcode(canvas, options, encoding) {
// Get the canvas context
var ctx = canvas.getContext("2d");
var binary = encoding.data;
// Creates the barcode out of the encoded binary
var yFrom, yHeight;
if (options.textPosition == "top") {
yFrom = options.marginTop + options.fontSize + options.textMargin;
} else {
yFrom = options.marginTop;
}
yHeight = options.height;
ctx.fillStyle = options.lineColor;
for (var b = 0; b < binary.length; b++) {
var x = b * options.width + encoding.barcodePadding;
if (binary[b] === "1") {
ctx.fillRect(x, yFrom, options.width, options.height);
} else if (binary[b]) {
ctx.fillRect(x, yFrom, options.width, options.height * binary[b]);
}
}
}
function drawCanvasText(canvas, options, encoding) {
// Get the canvas context
var ctx = canvas.getContext("2d");
var font = options.fontOptions + " " + options.fontSize + "px " + options.font;
// Draw the text if displayValue is set
if (options.displayValue) {
var x, y;
if (options.textPosition == "top") {
y = options.marginTop + options.fontSize - options.textMargin;
} else {
y = options.height + options.textMargin + options.marginTop + options.fontSize;
}
ctx.font = font;
// Draw the text in the correct X depending on the textAlign option
if (options.textAlign == "left" || encoding.barcodePadding > 0) {
x = 0;
ctx.textAlign = 'left';
} else if (options.textAlign == "right") {
x = encoding.width - 1;
ctx.textAlign = 'right';
}
// In all other cases, center the text
else {
x = encoding.width / 2;
ctx.textAlign = 'center';
}
ctx.fillText(encoding.text, x, y);
}
}
function moveCanvasDrawing(canvas, encoding) {
var ctx = canvas.getContext("2d");
ctx.translate(encoding.width, 0);
}
function restoreCanvas(canvas) {
// Get the canvas context
var ctx = canvas.getContext("2d");
ctx.restore();
}
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _merge = __webpack_require__(4);
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = renderSVG;
var svgns = "http://www.w3.org/2000/svg";
function renderSVG(svg, encodings, options) {
var currentX = options.marginLeft;
prepareSVG(svg, options, encodings);
for (var i = 0; i < encodings.length; i++) {
var encodingOptions = (0, _merge2.default)(options, encodings[i].options);
var group = createGroup(currentX, encodingOptions.marginTop, svg);
setGroupOptions(group, encodingOptions, encodings[i]);
drawSvgBarcode(group, encodingOptions, encodings[i]);
drawSVGText(group, encodingOptions, encodings[i]);
currentX += encodings[i].width;
}
}
function prepareSVG(svg, options, encodings) {
// Clear the SVG
while (svg.firstChild) {
svg.removeChild(svg.firstChild);
}
var totalWidth = 0;
var maxHeight = 0;
for (var i = 0; i < encodings.length; i++) {
var _options = (0, _merge2.default)(_options, encodings[i].options);
// Calculate the width of the encoding
var textWidth = messureSVGtext(encodings[i].text, svg, _options);
var barcodeWidth = encodings[i].data.length * _options.width;
encodings[i].width = Math.ceil(Math.max(textWidth, barcodeWidth));
// Calculate the height of the encoding
var encodingHeight = _options.height + (_options.displayValue && encodings[i].text.length > 0 ? _options.fontSize : 0) + _options.textMargin + _options.marginTop + _options.marginBottom;
var barcodePadding = 0;
if (_options.displayValue && barcodeWidth < textWidth) {
if (_options.textAlign == "center") {
barcodePadding = Math.floor((textWidth - barcodeWidth) / 2);
} else if (_options.textAlign == "left") {
barcodePadding = 0;
} else if (_options.textAlign == "right") {
barcodePadding = Math.floor(textWidth - barcodeWidth);
}
}
encodings[i].barcodePadding = barcodePadding;
if (encodingHeight > maxHeight) {
maxHeight = encodingHeight;
}
totalWidth += encodings[i].width;
}
var width = totalWidth + options.marginLeft + options.marginRight;
var height = maxHeight;
svg.setAttribute("width", width + "px");
svg.setAttribute("height", height + "px");
svg.setAttribute("x", "0px");
svg.setAttribute("y", "0px");
svg.setAttribute("viewBox", "0 0 " + width + " " + height);
svg.setAttribute("xmlns", svgns);
svg.setAttribute("version", "1.1");
svg.style.transform = "translate(0,0)";
if (options.background) {
svg.style.background = options.background;
}
}
function drawSvgBarcode(parent, options, encoding) {
var binary = encoding.data;
// Creates the barcode out of the encoded binary
var yFrom, yHeight;
if (options.textPosition == "top") {
yFrom = options.fontSize + options.textMargin;
} else {
yFrom = 0;
}
yHeight = options.height;
var barWidth = 0;
for (var b = 0; b < binary.length; b++) {
var x = b * options.width + encoding.barcodePadding;
if (binary[b] === "1") {
barWidth++;
} else if (barWidth > 0) {
drawLine(x - options.width * barWidth, yFrom, options.width * barWidth, options.height, parent);
barWidth = 0;
}
}
// Last draw is needed since the barcode ends with 1
if (barWidth > 0) {
drawLine(x - options.width * (barWidth - 1), yFrom, options.width * barWidth, options.height, parent);
}
}
function drawSVGText(parent, options, encoding) {
var textElem = document.createElementNS(svgns, 'text');
// Draw the text if displayValue is set
if (options.displayValue) {
var x, y;
textElem.setAttribute("style", "font:" + options.fontOptions + " " + options.fontSize + "px " + options.font);
if (options.textPosition == "top") {
y = options.fontSize - options.textMargin;
} else {
y = options.height + options.textMargin + options.fontSize;
}
// Draw the text in the correct X depending on the textAlign option
if (options.textAlign == "left" || encoding.barcodePadding > 0) {
x = 0;
textElem.setAttribute("text-anchor", "start");
} else if (options.textAlign == "right") {
x = encoding.width - 1;
textElem.setAttribute("text-anchor", "end");
}
// In all other cases, center the text
else {
x = encoding.width / 2;
textElem.setAttribute("text-anchor", "middle");
}
textElem.setAttribute("x", x);
textElem.setAttribute("y", y);
textElem.appendChild(document.createTextNode(encoding.text));
parent.appendChild(textElem);
}
}
//
// Help functions
//
function messureSVGtext(string, svg, options) {
// Create text element
/* var text = document.createElementNS(svgns, 'text');
text.style.fontFamily = options.font;
text.setAttribute("style",
"font-family:" + options.font + ";" +
"font-size:" + options.fontSize + "px;"
);
var textNode = document.createTextNode(string);
text.appendChild(textNode);
svg.appendChild(text);
var size = text.getComputedTextLength();
svg.removeChild(text);
*/
// TODO: Use svg to messure the text width
// Set font
var ctx = document.createElement("canvas").getContext("2d");
ctx.font = options.fontOptions + " " + options.fontSize + "px " + options.font;
// Calculate the width of the encoding
var size = ctx.measureText(string).width;
return size;
}
function createGroup(x, y, svg) {
var group = document.createElementNS(svgns, 'g');
group.setAttribute("transform", "translate(" + x + ", " + y + ")");
svg.appendChild(group);
return group;
}
function setGroupOptions(group, options, encoding) {
group.setAttribute("style", "fill:" + options.lineColor + ";");
}
function drawLine(x, y, width, height, parent) {
var line = document.createElementNS(svgns, 'rect');
line.setAttribute("x", x);
line.setAttribute("y", y);
line.setAttribute("width", width);
line.setAttribute("height", height);
parent.appendChild(line);
}
/***/ }
/******/ ]);
|
ggt3/SLogo
|
src/errors/UnmatchedBracketException.java
|
<gh_stars>0
package errors;
/**
* Exception for different number of brackets
*
* @author <NAME>
*
*/
public class UnmatchedBracketException extends SLogoException {
private static final long serialVersionUID = 1L;
public UnmatchedBracketException() {
super(String.format("The number of '[' and ']' do not match."));
}
}
|
cmc333333/parsons
|
parsons/targetsmart/targetsmart_api.py
|
import requests
import petl
from parsons.etl.table import Table
from parsons.utilities import check_env
URI = 'https://api.targetsmart.com/'
class TargetSmartConnector(object):
def __init__(self, api_key):
self.uri = URI
self.api_key = check_env.check('TS_API_KEY', api_key)
self.headers = {'x-api-key': self.api_key}
def request(self, url, args=None, raw=False):
r = requests.get(url, headers=self.headers, params=args)
# This allows me to deal with data that needs to be munged.
if raw:
return r.json()
return Table(r.json()['output'])
class Person(object):
def __init__(self):
return None
def data_enhance(self, search_id, search_id_type='voterbase', state=None):
"""
Searches for a record based on an id or phone or email address
`Args:`
search_id: str
The primary key or email address or phone number
search_id_type: str
One of ``voterbase``, ``exacttrack``, ``abilitec_consumer_link``, ``phone``,
``email``, ``smartvan``, ``votebuilder``, ``voter``, ``household``.
state: str
Two character state code. Required if ``search_id_type`` of ``smartvan``,
``votebuilder`` or ``voter``.
`Returns`
Parsons Table
See :ref:`parsons-table` for output options.
"""
if search_id_type in ['smartvan', 'votebuilder', 'voter'] and state is None:
raise KeyError("Search ID type '{}' requires state kwarg".format(search_id_type))
if search_id_type not in ('voterbase', 'exacttrack', 'abilitec_consumer_link', 'phone',
'email', 'smartvan', 'votebuilder', 'voter', 'household'):
raise ValueError('Search_id_type is not valid')
url = self.connection.uri + 'person/data-enhance'
args = {'search_id': search_id,
'search_id_type': search_id_type,
'state': state
}
return self.connection.request(url, args=args)
def radius_search(self, first_name, last_name, middle_name=None, name_suffix=None,
latitude=None, longitude=None, address=None, radius_size=10,
radius_unit='miles', max_results=10, gender='a', age_min=None, age_max=None,
composite_score_min=1, composite_score_max=100, last_name_exact=True,
last_name_is_prefix=False, last_name_prefix_length=10):
"""
Search for a person based on a specified radius
`Args`:
first_name: str
One or more alpha characters
last_name: str
One or more alpha characters
middle_name: str
One or more alpha characters
name_suffix: str
One or more alpha characters
latitude: float
Floating point number (e.g. 33.738987255507)
longitude: float
Floating point number (e.g. -116.40833849559)
address: str
Any geocode-able address
address_type: str
``reg`` for registration (default) or ``tsmart`` for TargetSmart
radius_unit: str
One of ``meters``, ``feet``, ``miles`` (default), or ``kilometers``.
max_results: int
Default of ``10``. An integer in range [0 - 100]
gender: str
Default of ``a``. One of ``m``, ``f``, ``u``, ``a``.
age_min: int
A positive integer
age_max: int
A positive integer
composite_score_min: int
An integer in range [1 - 100]. Filter out results with composite score
less than this value.
composite_score_max: int
An integer in range [1 - 100]. Filter out results with composite score
greater than this value.
last_name_exact: boolean
By default, the full last name is used for finding matches if the length of the
last name is not longer than 10 characters. As an example, “anders” is less likely
to match to “anderson” with this enabled. Disable this option if you are using
either ``last_name_is_prefix`` or ``last_name_prefix_length``.
last_name_is_prefix: boolean
By default, the full last name is used for finding matches. Enable this parameter
if your search last name is truncated. This can be common for some client
applications that for various reasons do not have full last names. Use this
parameter along with ``last_name_prefix_length`` to configure the length of the last
name prefix. This parameter is ignored if ``last_name_exact`` is enabled.
last_name_prefix_length: int
By default, up to the first 10 characters of the search last name are used for
finding relative matches. This value must be between 3 and 10. This parameter is
ignored if last_name_exact is enabled.
`Returns`
Parsons Table
See :ref:`parsons-table` for output options.
"""
if (latitude is None or longitude is None) and address is None:
raise ValueError('Lat/Long or Address required')
# Convert booleans
for a in [last_name_exact, last_name_is_prefix]:
a = str(a)
url = self.connection.uri + 'person/radius-search'
args = {'first_name': first_name,
'last_name': last_name,
'middle_name': middle_name,
'name_suffix': name_suffix,
'latitude': latitude,
'longitude': longitude,
'address': address,
'radius_size': radius_size,
'radius_unit': radius_unit,
'max_results': max_results,
'gender': gender,
'age_min': age_min,
'age_max': age_max,
'composite_score_min': composite_score_min,
'composite_score_max': composite_score_max,
'last_name_exact': last_name_exact,
'last_name_is_prefix': last_name_is_prefix,
'last_name_prefix_length': last_name_prefix_length
}
r = self.connection.request(url, args=args, raw=True)
return Table([itm for itm in r['output']]).unpack_dict('data_fields', prepend=False)
def phone(self, table):
"""
Match based on a list of 500 phones numbers. Table
can contain up to 500 phone numbers to match
`Args:`
table: parsons table
See :ref:`parsons-table`. One row per phone number,
up to 500 phone numbers.
`Returns:`
See :ref:`parsons-table` for output options.
"""
url = self.connection.uri + 'person/phone-search'
args = {'phones': list(petl.values(table.table, 0))}
return Table(self.connection.request(url, args=args, raw=True)['result'])
class Service(object):
def __init__(self):
return None
def district(self, search_type='zip', address=None, zip5=None, zip4=None, state=None,
latitude=None, longitude=None):
"""
Return district information based on a geographic point. The method allows you to
search based on the following:
.. list-table::
:widths: 30 30 30
:header-rows: 1
* - Search Type
- Search Type Name
- Required kwarg(s)
* - Zip Code
- ``zip``
- ``zip5``, ``zip4``
* - Address
- ``address``
- ``address``
* - Point
- point
- ``latitude``, ``longitude``
`Args`:
search_type: str
The type of district search to perform. One of ``zip``, ``address``
or ``point``.
address: str
An uparsed full address
zip5: str
The USPS Zip5 code
zip4: str
The USPS Zip4 code
state: str
The two character state code
latitude: float or str
Valid latitude floating point
lontitude: float or str
Valid longitude floating point
`Returns`:
Parsons Table
See :ref:`parsons-table` for output options.
"""
if search_type == 'zip' and None in [zip5, zip4]:
raise ValueError("Search type 'zip' requires 'zip5' and 'zip4' arguments")
elif search_type == 'point' and None in [latitude, longitude]:
raise ValueError("Search type 'point' requires 'latitude' and 'longitude' arguments")
elif search_type == 'address' and None in [address]:
raise ValueError("Search type 'address' requires 'address' argument")
elif search_type not in ['zip', 'point', 'address']:
raise KeyError("Invalid 'search_type' provided. ")
else:
pass
url = self.connection.uri + 'service/district'
args = {'search_type': search_type,
'address': address,
'zip5': zip5,
'zip4': zip4,
'state': state,
'latitude': latitude,
'longitude': longitude
}
return Table([self.connection.request(url, args=args, raw=True)['match_data']])
class Voter(object):
def __init__(self, connection):
self.connection = connection
def voter_registration_check(self, first_name=None, last_name=None,
state=None, street_number=None,
street_name=None, city=None, zip_code=None,
age=None, dob=None, phone=None, email=None,
unparsed_full_address=None):
"""
Searches for a registered individual, returns matches.
A search must include the at minimum first name, last name and state.
`Args:`
first_name: str
Required; One or more alpha characters. Trailing wildcard allowed
last_name: str
Required; One or more alpha characters. Trailing wildcard allowed
state: str
Required; Two character state code (e.g. ``NY``)
street_number: str
Optional; One or more alpha characters. Trailing wildcard allowed
street_name: str
Optional; One or more alpha characters. Trailing wildcard allowed
city: str
Optional; The person's home city
zip_code: str
Optional; Numeric characters. Trailing wildcard allowed
age; int
Optional; One or more integers. Trailing wildcard allowed
dob; str
Numeric characters in YYYYMMDD format. Trailing wildcard allowed
phone; str
Integer followed by 0 or more * or integers
email: str
Alphanumeric character followed by 0 or more * or legal characters
(alphanumeric, @, -, .)
unparsed_full_address: str
One or more alphanumeric characters. No wildcards.
`Returns`
Parsons Table
See :ref:`parsons-table` for output options.
"""
url = self.connection.uri + 'voter/voter-registration-check'
if None in [first_name, last_name, state]:
raise ValueError("""Function must include at least first_name,
last_name, and state.""")
args = {'first_name': first_name,
'last_name': last_name,
'state': state,
'street_number': street_number,
'street_name': street_name,
'city': city,
'zip_code': zip_code,
'age': age,
'dob': dob,
'phone': phone,
'email': email,
'unparsed_full_address': unparsed_full_address
}
return self.connection.request(url, args=args, raw=True)
class TargetSmartAPI(Voter, Person, Service):
def __init__(self, api_key=None):
self.connection = TargetSmartConnector(api_key=api_key)
|
ihmcrobotics/ihmc-open-robotics-software
|
ihmc-quadruped/src/robotics/java/us/ihmc/quadrupedRobotics/controlModules/QuadrupedControlManagerFactory.java
|
package us.ihmc.quadrupedRobotics.controlModules;
import us.ihmc.commonWalkingControlModules.controllerCore.FeedbackControllerTemplate;
import us.ihmc.commonWalkingControlModules.controllerCore.command.feedbackController.FeedbackControlCommandList;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry;
import us.ihmc.quadrupedRobotics.controlModules.foot.QuadrupedFeetManager;
import us.ihmc.quadrupedRobotics.controller.QuadrupedControllerToolbox;
import us.ihmc.quadrupedRobotics.model.QuadrupedPhysicalProperties;
import us.ihmc.yoVariables.registry.YoRegistry;
public class QuadrupedControlManagerFactory
{
private final YoRegistry registry = new YoRegistry(getClass().getSimpleName());
private final QuadrupedPhysicalProperties physicalProperties;
private final QuadrupedControllerToolbox toolbox;
private final YoGraphicsListRegistry graphicsListRegistry;
private QuadrupedFeetManager feetManager;
private QuadrupedBodyOrientationManager bodyOrientationManager;
private QuadrupedBalanceManager balanceManager;
private QuadrupedJointSpaceManager jointSpaceManager;
public QuadrupedControlManagerFactory(QuadrupedControllerToolbox toolbox, QuadrupedPhysicalProperties physicalProperties,
YoGraphicsListRegistry graphicsListRegistry, YoRegistry parentRegistry)
{
this.toolbox = toolbox;
this.physicalProperties = physicalProperties;
this.graphicsListRegistry = graphicsListRegistry;
parentRegistry.addChild(registry);
}
public QuadrupedFeetManager getOrCreateFeetManager()
{
if (feetManager != null)
return feetManager;
feetManager = new QuadrupedFeetManager(toolbox, graphicsListRegistry, registry);
return feetManager;
}
public QuadrupedBodyOrientationManager getOrCreateBodyOrientationManager()
{
if (bodyOrientationManager != null)
return bodyOrientationManager;
bodyOrientationManager = new QuadrupedBodyOrientationManager(toolbox, registry);
return bodyOrientationManager;
}
public QuadrupedBalanceManager getOrCreateBalanceManager()
{
if (balanceManager != null)
return balanceManager;
balanceManager = new QuadrupedBalanceManager(toolbox, physicalProperties, registry, toolbox.getRuntimeEnvironment().getGraphicsListRegistry());
return balanceManager;
}
public QuadrupedJointSpaceManager getOrCreateJointSpaceManager()
{
if (jointSpaceManager != null)
return jointSpaceManager;
jointSpaceManager = new QuadrupedJointSpaceManager(toolbox, registry);
return jointSpaceManager;
}
public FeedbackControllerTemplate createFeedbackControlTemplate()
{
FeedbackControlCommandList ret = new FeedbackControlCommandList();
if (feetManager != null)
ret.addCommandList(feetManager.createFeedbackControlTemplate());
if (bodyOrientationManager != null)
ret.addCommand(bodyOrientationManager.createFeedbackControlTemplate());
if (jointSpaceManager != null)
ret.addCommand(jointSpaceManager.createFeedbackControlTemplate());
return new FeedbackControllerTemplate(ret);
}
}
|
egotter/egotter
|
app/javascript/packs/ad_block_detector.js
|
<filename>app/javascript/packs/ad_block_detector.js
class AdBlockDetector {
constructor(token) {
this.token = token;
}
detect(callback) {
if (window.adBlockerDetected || !document.getElementById(this.token)) {
logger.log('Blocking Ads: Yes', window.adBlockerDetected);
callback();
} else {
logger.log('Blocking Ads: No', window.adBlockerDetected);
}
}
}
window.AdBlockDetector = AdBlockDetector;
|
rnarla123/aliyun-openapi-java-sdk
|
aliyun-java-sdk-retailadvqa-public/src/main/java/com/aliyuncs/retailadvqa_public/model/v20200515/ListDatasetResponse.java
|
/*
* 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 com.aliyuncs.retailadvqa_public.model.v20200515;
import java.util.List;
import java.util.Map;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.retailadvqa_public.transform.v20200515.ListDatasetResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class ListDatasetResponse extends AcsResponse {
private String requestId;
private String errorDesc;
private String traceId;
private String errorCode;
private Boolean success;
private List<DataItem> data;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getErrorDesc() {
return this.errorDesc;
}
public void setErrorDesc(String errorDesc) {
this.errorDesc = errorDesc;
}
public String getTraceId() {
return this.traceId;
}
public void setTraceId(String traceId) {
this.traceId = traceId;
}
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public Boolean getSuccess() {
return this.success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<DataItem> getData() {
return this.data;
}
public void setData(List<DataItem> data) {
this.data = data;
}
public static class DataItem {
private Map<Object,Object> extMappingTypes;
private String uniqueFieldName;
private String gmtModified;
private String uniqueMappingType;
private String gmtCreate;
private String factTable;
private String name;
private Integer dataSetType;
private String id;
private ExtRFM extRFM;
private ExtLabel extLabel;
private ExtBehavior extBehavior;
public Map<Object,Object> getExtMappingTypes() {
return this.extMappingTypes;
}
public void setExtMappingTypes(Map<Object,Object> extMappingTypes) {
this.extMappingTypes = extMappingTypes;
}
public String getUniqueFieldName() {
return this.uniqueFieldName;
}
public void setUniqueFieldName(String uniqueFieldName) {
this.uniqueFieldName = uniqueFieldName;
}
public String getGmtModified() {
return this.gmtModified;
}
public void setGmtModified(String gmtModified) {
this.gmtModified = gmtModified;
}
public String getUniqueMappingType() {
return this.uniqueMappingType;
}
public void setUniqueMappingType(String uniqueMappingType) {
this.uniqueMappingType = uniqueMappingType;
}
public String getGmtCreate() {
return this.gmtCreate;
}
public void setGmtCreate(String gmtCreate) {
this.gmtCreate = gmtCreate;
}
public String getFactTable() {
return this.factTable;
}
public void setFactTable(String factTable) {
this.factTable = factTable;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDataSetType() {
return this.dataSetType;
}
public void setDataSetType(Integer dataSetType) {
this.dataSetType = dataSetType;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public ExtRFM getExtRFM() {
return this.extRFM;
}
public void setExtRFM(ExtRFM extRFM) {
this.extRFM = extRFM;
}
public ExtLabel getExtLabel() {
return this.extLabel;
}
public void setExtLabel(ExtLabel extLabel) {
this.extLabel = extLabel;
}
public ExtBehavior getExtBehavior() {
return this.extBehavior;
}
public void setExtBehavior(ExtBehavior extBehavior) {
this.extBehavior = extBehavior;
}
public static class ExtRFM {
private String tradeDateField;
private String dataFromType;
private String tradeFrequencyField;
private Integer tradeMoneyUnit;
private String frequencyScoreCompareValue;
private String monetaryScoreCompareValue;
private Integer period;
private String tradeMoneyField;
private Integer comparisonCalculateType;
private String recencyScoreCompareValue;
private List<FrequencyScoreConfigItem> frequencyScoreConfig;
private List<MonetaryScoreConfigItem> monetaryScoreConfig;
private List<RecencyScoreConfigItem> recencyScoreConfig;
public String getTradeDateField() {
return this.tradeDateField;
}
public void setTradeDateField(String tradeDateField) {
this.tradeDateField = tradeDateField;
}
public String getDataFromType() {
return this.dataFromType;
}
public void setDataFromType(String dataFromType) {
this.dataFromType = dataFromType;
}
public String getTradeFrequencyField() {
return this.tradeFrequencyField;
}
public void setTradeFrequencyField(String tradeFrequencyField) {
this.tradeFrequencyField = tradeFrequencyField;
}
public Integer getTradeMoneyUnit() {
return this.tradeMoneyUnit;
}
public void setTradeMoneyUnit(Integer tradeMoneyUnit) {
this.tradeMoneyUnit = tradeMoneyUnit;
}
public String getFrequencyScoreCompareValue() {
return this.frequencyScoreCompareValue;
}
public void setFrequencyScoreCompareValue(String frequencyScoreCompareValue) {
this.frequencyScoreCompareValue = frequencyScoreCompareValue;
}
public String getMonetaryScoreCompareValue() {
return this.monetaryScoreCompareValue;
}
public void setMonetaryScoreCompareValue(String monetaryScoreCompareValue) {
this.monetaryScoreCompareValue = monetaryScoreCompareValue;
}
public Integer getPeriod() {
return this.period;
}
public void setPeriod(Integer period) {
this.period = period;
}
public String getTradeMoneyField() {
return this.tradeMoneyField;
}
public void setTradeMoneyField(String tradeMoneyField) {
this.tradeMoneyField = tradeMoneyField;
}
public Integer getComparisonCalculateType() {
return this.comparisonCalculateType;
}
public void setComparisonCalculateType(Integer comparisonCalculateType) {
this.comparisonCalculateType = comparisonCalculateType;
}
public String getRecencyScoreCompareValue() {
return this.recencyScoreCompareValue;
}
public void setRecencyScoreCompareValue(String recencyScoreCompareValue) {
this.recencyScoreCompareValue = recencyScoreCompareValue;
}
public List<FrequencyScoreConfigItem> getFrequencyScoreConfig() {
return this.frequencyScoreConfig;
}
public void setFrequencyScoreConfig(List<FrequencyScoreConfigItem> frequencyScoreConfig) {
this.frequencyScoreConfig = frequencyScoreConfig;
}
public List<MonetaryScoreConfigItem> getMonetaryScoreConfig() {
return this.monetaryScoreConfig;
}
public void setMonetaryScoreConfig(List<MonetaryScoreConfigItem> monetaryScoreConfig) {
this.monetaryScoreConfig = monetaryScoreConfig;
}
public List<RecencyScoreConfigItem> getRecencyScoreConfig() {
return this.recencyScoreConfig;
}
public void setRecencyScoreConfig(List<RecencyScoreConfigItem> recencyScoreConfig) {
this.recencyScoreConfig = recencyScoreConfig;
}
public static class FrequencyScoreConfigItem {
private Integer start;
private Integer end;
private Integer score;
public Integer getStart() {
return this.start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return this.end;
}
public void setEnd(Integer end) {
this.end = end;
}
public Integer getScore() {
return this.score;
}
public void setScore(Integer score) {
this.score = score;
}
}
public static class MonetaryScoreConfigItem {
private String start;
private String end;
private String score;
public String getStart() {
return this.start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return this.end;
}
public void setEnd(String end) {
this.end = end;
}
public String getScore() {
return this.score;
}
public void setScore(String score) {
this.score = score;
}
}
public static class RecencyScoreConfigItem {
private Integer start;
private Integer end;
private Integer score;
public Integer getStart() {
return this.start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return this.end;
}
public void setEnd(Integer end) {
this.end = end;
}
public Integer getScore() {
return this.score;
}
public void setScore(Integer score) {
this.score = score;
}
}
}
public static class ExtLabel {
private List<DatasetLabelListItem> datasetLabelList;
public List<DatasetLabelListItem> getDatasetLabelList() {
return this.datasetLabelList;
}
public void setDatasetLabelList(List<DatasetLabelListItem> datasetLabelList) {
this.datasetLabelList = datasetLabelList;
}
public static class DatasetLabelListItem {
private String columnAlias;
private String columnName;
private String tableName;
private String colType;
private String labelSeparator;
private String remark;
public String getColumnAlias() {
return this.columnAlias;
}
public void setColumnAlias(String columnAlias) {
this.columnAlias = columnAlias;
}
public String getColumnName() {
return this.columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getTableName() {
return this.tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getColType() {
return this.colType;
}
public void setColType(String colType) {
this.colType = colType;
}
public String getLabelSeparator() {
return this.labelSeparator;
}
public void setLabelSeparator(String labelSeparator) {
this.labelSeparator = labelSeparator;
}
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
}
public static class ExtBehavior {
private String behaviorObjectTypeField;
private String behaviorDateField;
private String typeField;
private String behaviorChannelField;
private String behaviorTypeField;
private String channelDimTableName;
private String behaviorCountsField;
private String typeDimTableName;
private String behaviorObjectValueField;
private String channelField;
private Map<Object,Object> objectTypeContext;
private String behaviorAmountsField;
public String getBehaviorObjectTypeField() {
return this.behaviorObjectTypeField;
}
public void setBehaviorObjectTypeField(String behaviorObjectTypeField) {
this.behaviorObjectTypeField = behaviorObjectTypeField;
}
public String getBehaviorDateField() {
return this.behaviorDateField;
}
public void setBehaviorDateField(String behaviorDateField) {
this.behaviorDateField = behaviorDateField;
}
public String getTypeField() {
return this.typeField;
}
public void setTypeField(String typeField) {
this.typeField = typeField;
}
public String getBehaviorChannelField() {
return this.behaviorChannelField;
}
public void setBehaviorChannelField(String behaviorChannelField) {
this.behaviorChannelField = behaviorChannelField;
}
public String getBehaviorTypeField() {
return this.behaviorTypeField;
}
public void setBehaviorTypeField(String behaviorTypeField) {
this.behaviorTypeField = behaviorTypeField;
}
public String getChannelDimTableName() {
return this.channelDimTableName;
}
public void setChannelDimTableName(String channelDimTableName) {
this.channelDimTableName = channelDimTableName;
}
public String getBehaviorCountsField() {
return this.behaviorCountsField;
}
public void setBehaviorCountsField(String behaviorCountsField) {
this.behaviorCountsField = behaviorCountsField;
}
public String getTypeDimTableName() {
return this.typeDimTableName;
}
public void setTypeDimTableName(String typeDimTableName) {
this.typeDimTableName = typeDimTableName;
}
public String getBehaviorObjectValueField() {
return this.behaviorObjectValueField;
}
public void setBehaviorObjectValueField(String behaviorObjectValueField) {
this.behaviorObjectValueField = behaviorObjectValueField;
}
public String getChannelField() {
return this.channelField;
}
public void setChannelField(String channelField) {
this.channelField = channelField;
}
public Map<Object,Object> getObjectTypeContext() {
return this.objectTypeContext;
}
public void setObjectTypeContext(Map<Object,Object> objectTypeContext) {
this.objectTypeContext = objectTypeContext;
}
public String getBehaviorAmountsField() {
return this.behaviorAmountsField;
}
public void setBehaviorAmountsField(String behaviorAmountsField) {
this.behaviorAmountsField = behaviorAmountsField;
}
}
}
@Override
public ListDatasetResponse getInstance(UnmarshallerContext context) {
return ListDatasetResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
|
rayform/swell-js
|
test/page/actions/cart.js
|
<gh_stars>10-100
export default {
initCart() {
return async (dispatch, getState) => {
const { api } = getState();
const cart = await api.cart.get();
dispatch({
type: 'SET_CART',
payload: cart,
});
};
},
addItem(product) {
return async (dispatch, getState) => {
const { api } = getState();
const cart = await api.cart.addItem(product);
dispatch({
type: 'ADD_ITEM',
payload: cart,
});
};
},
removeItem(itemId) {
return async (dispatch, getState) => {
const { api } = getState();
const cart = await api.cart.removeItem(itemId);
dispatch({
type: 'REMOVE_ITEM',
payload: cart,
});
};
},
update(values) {
return async (dispatch, getState) => {
const { api } = getState();
const cart = await api.cart.update(values);
dispatch({
type: 'UPDATE_CART',
payload: cart,
});
};
},
submitOrder() {
return async (dispatch, getState) => {
dispatch({
type: 'SUBMIT_ORDER',
payload: null,
});
const { api } = getState();
const order = await api.cart.submitOrder();
return order;
};
},
};
|
MrJoy/surface_master
|
examples/system_monitor.rb
|
#!/usr/bin/env ruby
# require "bignum"
require "rubygems"
require "bundler/setup"
Bundler.require(:default, :development)
require "surface_master"
def goodbye(interaction)
data = []
(0..7).each do |x|
(0..7).each do |y|
data << { x: x, y: y, red: 0x00, green: 0x00, blue: 0x00 }
end
end
interaction.changes(data)
end
# Janky bar-graph widget.
class Bar
BLACK = { red: 0x00, green: 0x00, blue: 0x00 }.freeze
def initialize(interaction, x, color)
@interaction = interaction
@x = x
@color = color
end
def update(val)
data = []
(0..val).each do |y|
data << @color.merge(grid: [@x, y])
end
((val + 1)..7).each do |y|
data << BLACK.merge(grid: [@x, y])
end
@interaction.changes(data)
end
end
interaction = SurfaceMaster::Launchpad::Interaction.new
cpu_bar = Bar.new(interaction, 0, red: 0x3F, green: 0x00, blue: 0x00)
io_bar = Bar.new(interaction, 1, red: 0x00, green: 0x3F, blue: 0x00)
monitor = Thread.new do
loop do
fields = `iostat -c 2 disk0`.split(/\n/).last.strip.split(/\s+/)
cpu_pct = 100 - fields[-4].to_i
cpu_usage = ((cpu_pct / 100.0) * 8.0).round.to_i
disk_pct = ((fields[2].to_f / 750.0) * 100.0).round.to_i
disk_usage = ((disk_pct / 100.0) * 8.0).round.to_i
puts "I/O=#{disk_pct}%, CPU=#{cpu_pct}%"
# TODO: Network in/out...
# TODO: Make block I/O not be a bar but a fill, with scale indicated by color...
cpu_bar.update(cpu_usage)
io_bar.update(disk_usage)
end
end
interaction.response_to(:mixer, :down) do |_interaction, _action|
puts "Shutting down"
begin
monitor.kill
goodbye(interaction)
interaction.stop
rescue Exception => e
puts e.inspect
end
end
interaction.start
|
Akarin-project/Paper2Srg
|
src/main/java/net/minecraft/advancements/FunctionManager.java
|
package net.minecraft.advancements;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.command.FunctionObject;
import net.minecraft.command.ICommandManager;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ITickable;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
public class FunctionManager implements ITickable {
private static final Logger field_193067_a = LogManager.getLogger();
private final File field_193068_b;
private final MinecraftServer field_193069_c;
private final Map<ResourceLocation, FunctionObject> field_193070_d = Maps.newHashMap();
private String field_193071_e = "-";
private FunctionObject field_193072_f;
private final ArrayDeque<FunctionManager.a> field_194020_g = new ArrayDeque();
private boolean field_194021_h = false;
// CraftBukkit start
private final ICommandSender field_193073_g = new CustomFunctionListener();
public class CustomFunctionListener implements ICommandSender {
public org.bukkit.command.CommandSender sender = new org.bukkit.craftbukkit.command.CraftFunctionCommandSender(this);
// CraftBukkit end
@Override
public String func_70005_c_() {
return FunctionManager.this.field_193071_e;
}
@Override
public boolean func_70003_b(int i, String s) {
return i <= 2;
}
@Override
public World func_130014_f_() {
return FunctionManager.this.field_193069_c.worlds.get(0); // CraftBukkit
}
@Override
public MinecraftServer func_184102_h() {
return FunctionManager.this.field_193069_c;
}
};
public FunctionManager(@Nullable File file, MinecraftServer minecraftserver) {
this.field_193068_b = file;
this.field_193069_c = minecraftserver;
this.func_193059_f();
}
@Nullable
public FunctionObject func_193058_a(ResourceLocation minecraftkey) {
return this.field_193070_d.get(minecraftkey);
}
public ICommandManager func_193062_a() {
return this.field_193069_c.func_71187_D();
}
public int func_193065_c() {
return this.field_193069_c.worlds.get(0).func_82736_K().func_180263_c("maxCommandChainLength"); // CraftBukkit
}
public Map<ResourceLocation, FunctionObject> func_193066_d() {
return this.field_193070_d;
}
@Override
public void func_73660_a() {
String s = this.field_193069_c.worlds.get(0).func_82736_K().func_82767_a("gameLoopFunction"); // CraftBukkit
if (!s.equals(this.field_193071_e)) {
this.field_193071_e = s;
this.field_193072_f = this.func_193058_a(new ResourceLocation(s));
}
if (this.field_193072_f != null) {
this.func_194019_a(this.field_193072_f, this.field_193073_g);
}
}
public int func_194019_a(FunctionObject customfunction, ICommandSender icommandlistener) {
int i = this.func_193065_c();
if (this.field_194021_h) {
if (this.field_194020_g.size() < i) {
this.field_194020_g.addFirst(new FunctionManager.a(this, icommandlistener, new FunctionObject.d(customfunction)));
}
return 0;
} else {
int j;
try {
this.field_194021_h = true;
int k = 0;
FunctionObject.c[] acustomfunction_c = customfunction.a();
for (j = acustomfunction_c.length - 1; j >= 0; --j) {
this.field_194020_g.push(new FunctionManager.a(this, icommandlistener, acustomfunction_c[j]));
}
do {
if (this.field_194020_g.isEmpty()) {
j = k;
return j;
}
this.field_194020_g.removeFirst().a(this.field_194020_g, i);
++k;
} while (k < i);
j = k;
} finally {
this.field_194020_g.clear();
this.field_194021_h = false;
}
return j;
}
}
public void func_193059_f() {
this.field_193070_d.clear();
this.field_193072_f = null;
this.field_193071_e = "-";
this.func_193061_h();
}
private void func_193061_h() {
if (this.field_193068_b != null) {
this.field_193068_b.mkdirs();
Iterator iterator = FileUtils.listFiles(this.field_193068_b, new String[] { "mcfunction"}, true).iterator();
while (iterator.hasNext()) {
File file = (File) iterator.next();
String s = FilenameUtils.removeExtension(this.field_193068_b.toURI().relativize(file.toURI()).toString());
String[] astring = s.split("/", 2);
if (astring.length == 2) {
ResourceLocation minecraftkey = new ResourceLocation(astring[0], astring[1]);
try {
this.field_193070_d.put(minecraftkey, FunctionObject.func_193527_a(this, Files.readLines(file, StandardCharsets.UTF_8)));
} catch (Throwable throwable) {
FunctionManager.field_193067_a.error("Couldn\'t read custom function " + minecraftkey + " from " + file, throwable);
}
}
}
if (!this.field_193070_d.isEmpty()) {
FunctionManager.field_193067_a.info("Loaded " + this.field_193070_d.size() + " custom command functions");
}
}
}
public static class a {
private final FunctionManager a;
private final ICommandSender b;
private final FunctionObject.c c;
public a(FunctionManager customfunctiondata, ICommandSender icommandlistener, FunctionObject.c customfunction_c) {
this.a = customfunctiondata;
this.b = icommandlistener;
this.c = customfunction_c;
}
public void a(ArrayDeque<FunctionManager.a> arraydeque, int i) {
this.c.a(this.a, this.b, arraydeque, i);
}
@Override
public String toString() {
return this.c.toString();
}
}
}
|
maicadk/netlify-plugin
|
browserMonitoring/index.js
|
import { getErrorResponse, settings } from "../settings.js"
import { missingSettings, skipBrowserMonitoring } from "./utils.js"
import { insertBrowserMonitoring } from "./htmlInsertion.js"
export const injectBrowserMonitoring = async (pluginApi) => {
const { inputs, utils, constants } = pluginApi
const { build } = utils
const errorResponse = getErrorResponse(inputs, build)
return (
skipBrowserMonitoring(settings(inputs)) ||
missingSettings(settings(inputs), errorResponse) ||
(await insertBrowserMonitoring(pluginApi))
)
}
|
uk-gov-mirror/hmcts.probate-frontend
|
test/end-to-end/pages/summary/summary.js
|
'use strict';
const summaryContentEn = require('app/resources/en/translation/summary');
const summaryContentCy = require('app/resources/cy/translation/summary');
module.exports = async function(language = 'en', redirect) {
const I = this;
const summaryContent = language === 'en' ? summaryContentEn : summaryContentCy;
await I.checkPageUrl('app/steps/ui/summary', redirect);
await I.waitForText(summaryContent.heading);
const locator = {css: '#checkAnswerHref'};
await I.waitForElement(locator);
await I.downloadPdfIfNotIE11(locator);
await I.navByClick('.govuk-button');
};
|
GrinCash/Grinc-core
|
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/gui/painting/qwmatrix/tst_qwmatrix.cpp
|
<filename>depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/gui/painting/qwmatrix/tst_qwmatrix.cpp
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qmatrix.h>
#include <qmath.h>
#include <qpolygon.h>
class tst_QWMatrix : public QObject
{
Q_OBJECT
private slots:
void mapRect_data();
void mapToPolygon_data();
void mapRect();
void operator_star_qwmatrix();
void assignments();
void mapToPolygon();
void translate();
void scale();
void mapPolygon();
private:
void mapping_data();
};
void tst_QWMatrix::mapRect_data()
{
mapping_data();
}
void tst_QWMatrix::mapToPolygon_data()
{
mapping_data();
}
void tst_QWMatrix::mapping_data()
{
//create the testtable instance and define the elements
QTest::addColumn<QMatrix>("matrix");
QTest::addColumn<QRect>("src");
QTest::addColumn<QPolygon>("res");
//next we fill it with data
// identity
QTest::newRow( "identity" ) << QMatrix( 1, 0, 0, 1, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 10, 20, 30, 40 ) );
// scaling
QTest::newRow( "scale 0" ) << QMatrix( 2, 0, 0, 2, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 20, 40, 60, 80 ) );
QTest::newRow( "scale 1" ) << QMatrix( 10, 0, 0, 10, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 100, 200, 300, 400 ) );
// mirroring
QTest::newRow( "mirror 0" ) << QMatrix( -1, 0, 0, 1, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -40, 20, 30, 40 ) );
QTest::newRow( "mirror 1" ) << QMatrix( 1, 0, 0, -1, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 10, -60, 30, 40 ) );
QTest::newRow( "mirror 2" ) << QMatrix( -1, 0, 0, -1, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -40, -60, 30, 40 ) );
QTest::newRow( "mirror 3" ) << QMatrix( -2, 0, 0, -2, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -80, -120, 60, 80 ) );
QTest::newRow( "mirror 4" ) << QMatrix( -10, 0, 0, -10, 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -400, -600, 300, 400 ) );
QTest::newRow( "mirror 5" ) << QMatrix( -1, 0, 0, 1, 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -30, 0, 30, 40 ) );
QTest::newRow( "mirror 6" ) << QMatrix( 1, 0, 0, -1, 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( 0, -40, 30, 40 ) );
QTest::newRow( "mirror 7" ) << QMatrix( -1, 0, 0, -1, 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -30, -40, 30, 40 ) );
QTest::newRow( "mirror 8" ) << QMatrix( -2, 0, 0, -2, 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -60, -80, 60, 80 ) );
QTest::newRow( "mirror 9" ) << QMatrix( -10, 0, 0, -10, 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -300, -400, 300, 400 ) );
#if defined(Q_OS_WIN) && !defined(M_PI)
#define M_PI 3.14159265897932384626433832795f
#endif
// rotations
float deg = 0.;
QTest::newRow( "rot 0 a" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon ( QRect( 0, 0, 30, 40 ) );
deg = 0.00001f;
QTest::newRow( "rot 0 b" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon ( QRect( 0, 0, 30, 40 ) );
deg = 0.;
QTest::newRow( "rot 0 c" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon ( QRect( 10, 20, 30, 40 ) );
deg = 0.00001f;
QTest::newRow( "rot 0 d" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon ( QRect( 10, 20, 30, 40 ) );
#if 0
// rotations
deg = 90.;
QTest::newRow( "rotscale 90 a" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( 0, -299, 400, 300 ) );
deg = 90.00001;
QTest::newRow( "rotscale 90 b" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( 0, -299, 400, 300 ) );
deg = 90.;
QTest::newRow( "rotscale 90 c" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 200, -399, 400, 300 ) );
deg = 90.00001;
QTest::newRow( "rotscale 90 d" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 200, -399, 400, 300 ) );
deg = 180.;
QTest::newRow( "rotscale 180 a" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -299, -399, 300, 400 ) );
deg = 180.000001;
QTest::newRow( "rotscale 180 b" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -299, -399, 300, 400 ) );
deg = 180.;
QTest::newRow( "rotscale 180 c" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -399, -599, 300, 400 ) );
deg = 180.000001;
QTest::newRow( "rotscale 180 d" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -399, -599, 300, 400 ) );
deg = 270.;
QTest::newRow( "rotscale 270 a" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -399, 00, 400, 300 ) );
deg = 270.0000001;
QTest::newRow( "rotscale 270 b" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 30, 40 )
<< QPolygon( QRect( -399, 00, 400, 300 ) );
deg = 270.;
QTest::newRow( "rotscale 270 c" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -599, 100, 400, 300 ) );
deg = 270.000001;
QTest::newRow( "rotscale 270 d" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -599, 100, 400, 300 ) );
// rotations that are not multiples of 90 degrees. mapRect returns the bounding rect here.
deg = 45;
QTest::newRow( "rot 45 a" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 10, 10 )
<< QPolygon( QRect( 0, -7, 14, 14 ) );
QTest::newRow( "rot 45 b" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 21, -14, 49, 49 ) );
QTest::newRow( "rot 45 c" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 10, 10 )
<< QPolygon( QRect( 0, -70, 141, 141 ) );
QTest::newRow( "rot 45 d" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( 212, -141, 495, 495 ) );
deg = -45;
QTest::newRow( "rot -45 a" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 10, 10 )
<< QPolygon( QRect( -7, 0, 14, 14 ) );
QTest::newRow( "rot -45 b" ) << QMatrix( std::cos( M_PI*deg/180. ), -std::sin( M_PI*deg/180. ),
std::sin( M_PI*deg/180. ), std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -35, 21, 49, 49 ) );
QTest::newRow( "rot -45 c" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 0, 0, 10, 10 )
<< QPolygon( QRect( -70, 0, 141, 141 ) );
QTest::newRow( "rot -45 d" ) << QMatrix( 10*std::cos( M_PI*deg/180. ), -10*std::sin( M_PI*deg/180. ),
10*std::sin( M_PI*deg/180. ), 10*std::cos( M_PI*deg/180. ), 0, 0 )
<< QRect( 10, 20, 30, 40 )
<< QPolygon( QRect( -353, 212, 495, 495 ) );
#endif
}
void tst_QWMatrix::mapRect()
{
QFETCH( QMatrix, matrix );
QFETCH( QRect, src );
// qDebug( "got src: %d/%d (%d/%d), matrix=[ %f %f %f %f %f %f ]",
// src.x(), src.y(), src.width(), src.height(),
// matrix.m11(), matrix.m12(), matrix.m21(), matrix.m22(), matrix.dx(), matrix.dy() );
QTEST( QPolygon( matrix.mapRect(src) ), "res" );
}
void tst_QWMatrix::operator_star_qwmatrix()
{
QMatrix m1( 2, 3, 4, 5, 6, 7 );
QMatrix m2( 3, 4, 5, 6, 7, 8 );
QMatrix result1x2( 21, 26, 37, 46, 60, 74 );
QMatrix result2x1( 22, 29, 34, 45, 52, 68);
QMatrix product12 = m1*m2;
QMatrix product21 = m2*m1;
QVERIFY( product12==result1x2 );
QVERIFY( product21==result2x1 );
}
void tst_QWMatrix::assignments()
{
QMatrix m;
m.scale(2, 3);
m.rotate(45);
m.shear(4, 5);
QMatrix c1(m);
QCOMPARE(m.m11(), c1.m11());
QCOMPARE(m.m12(), c1.m12());
QCOMPARE(m.m21(), c1.m21());
QCOMPARE(m.m22(), c1.m22());
QCOMPARE(m.dx(), c1.dx());
QCOMPARE(m.dy(), c1.dy());
QMatrix c2 = m;
QCOMPARE(m.m11(), c2.m11());
QCOMPARE(m.m12(), c2.m12());
QCOMPARE(m.m21(), c2.m21());
QCOMPARE(m.m22(), c2.m22());
QCOMPARE(m.dx(), c2.dx());
QCOMPARE(m.dy(), c2.dy());
}
void tst_QWMatrix::mapToPolygon()
{
QFETCH( QMatrix, matrix );
QFETCH( QRect, src );
QFETCH( QPolygon, res );
QCOMPARE( matrix.mapToPolygon( src ), res );
}
void tst_QWMatrix::translate()
{
QMatrix m( 1, 2, 3, 4, 5, 6 );
QMatrix res2( m );
QMatrix res( 1, 2, 3, 4, 75, 106 );
m.translate( 10, 20 );
QVERIFY( m == res );
m.translate( -10, -20 );
QVERIFY( m == res2 );
}
void tst_QWMatrix::scale()
{
QMatrix m( 1, 2, 3, 4, 5, 6 );
QMatrix res2( m );
QMatrix res( 10, 20, 60, 80, 5, 6 );
m.scale( 10, 20 );
QVERIFY( m == res );
m.scale( 1./10., 1./20. );
QVERIFY( m == res2 );
}
void tst_QWMatrix::mapPolygon()
{
QPolygon poly;
poly << QPoint(0, 0) << QPoint(1, 1) << QPoint(100, 1) << QPoint(1, 100) << QPoint(-1, -1) << QPoint(-1000, 1000);
{
QMatrix m;
m.rotate(90);
// rotating 90 degrees four times should result in original poly
QPolygon mapped = m.map(m.map(m.map(m.map(poly))));
QCOMPARE(mapped, poly);
QMatrix m2;
m2.scale(10, 10);
QMatrix m3;
m3.scale(0.1, 0.1);
mapped = m3.map(m2.map(poly));
QCOMPARE(mapped, poly);
}
{
QMatrix m(1, 2, 3, 4, 5, 6);
QPolygon mapped = m.map(poly);
for (int i = 0; i < mapped.size(); ++i)
QCOMPARE(mapped.at(i), m.map(poly.at(i)));
}
}
QTEST_APPLESS_MAIN(tst_QWMatrix)
#include "tst_qwmatrix.moc"
|
nuggetwheat/study
|
src/cc/Books/CormenIntroductionToAlgorithms/Graph.hpp
|
#ifndef Books_CormenIntroductionToAlgorithms_Graph_hpp
#define Books_CormenIntroductionToAlgorithms_Graph_hpp
#include <cassert>
#include <iostream>
#include <list>
#include <map>
#include <ostream>
#include <set>
#include <utility>
#include <vector>
#include <Common/Graph.hpp>
namespace study {
template <typename T>
void bfs(Graph<T> &g, T root, std::map<T, T> &parent, std::map<T, int> &distance);
template <typename T>
void dfs(Graph<T> &g, std::map<T, T> &parent, std::map<T, std::pair<int,int>> &time);
template <typename T>
void topological_sort(Graph<T> &g, std::list<T> &order);
template <typename T>
void strongly_connected_components(Graph<T> &g, std::vector<std::set<T>> &components);
template <typename T, typename WT>
void mst_kruskal(const Graph<T> &g, std::map<Edge<T>, WT> &weight, Graph<T> &mst);
template <typename T, typename WT>
void mst_prim(const Graph<T> &g, T root, std::map<Edge<T>, WT> &weight, Graph<T> &mst);
template <typename T, typename DT>
void relax(T u, T v, std::map<Edge<T>, DT> &weight, std::map<T, T> &parent, std::map<T, DT> &distance);
template <typename T, typename DT>
void initialize_single_source(Graph<T> &g, T root, std::map<T, T> &parent, std::map<T, DT> &distance);
template <typename T, typename DT>
bool bellman_ford(Graph<T> &g, T root, std::map<Edge<T>, DT> &weight,
std::map<T, T> &parent, std::map<T, DT> &distance);
template <typename T, typename DT>
void dag_shortest_paths(Graph<T> &g, T root, std::map<Edge<T>, DT> &weight,
std::map<T, T> &parent, std::map<T, DT> &distance);
template <size_t N>
void display(int M[N][N]);
template <size_t N>
void extend_shortest_paths(int L[N][N], int W[N][N], int output[N][N]);
template <size_t N>
void slow_all_pairs_shortest_paths(int W[N][N], int output[N][N]);
template <size_t N>
void faster_all_pairs_shortest_paths(int W[N][N], int output[N][N]);
}
#include "Graph.cpp"
#endif // Books_CormenIntroductionToAlgorithms_Graph_hpp
|
windmaomao/adventofcode
|
problem/dynamic/min-number-coins.js
|
<gh_stars>0
const minNumberCoins = (n, denoms) => {
const res = new Array(n + 1).fill(-1)
res[0] = 0
let i = 0
while (i < denoms.length) {
const coin = denoms[i]
for (let k = 1; k < res.length; k++) {
if (k >= coin) {
const left = k - coin
if (res[left] >=0) {
const n = res[left] + 1
if (res[k] < 0 || res[k] > n) {
res[k] = n
}
}
}
}
console.log(res)
i++
}
return res
}
minNumberCoins(9, [3, 5])
|
innovator-zero/SJTU-OJ
|
1991/main.cpp
|
<gh_stars>0
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int k,n;
double x[100000],low,high,mid;
int judge(double r);
int main()
{
int i;
cin>>n>>k;
for(i=0; i<n; ++i)
{
cin>>x[i];
}
low=x[0];
high=x[n-1];
while((high-low)>=pow(10,-7))
{
mid=(high+low)/2;
if(judge(mid)==0)
{
cout<<fixed<<setprecision(6)<<mid;
return 0;
}
else if(judge(mid)==1)
{
high=mid;
}
else
{
low=mid;
}
}
cout<<fixed<<setprecision(6)<<mid;
return 0;
}
int judge(double r)
{
int i=0,j=0,p=0;
while(i<k)
{
while(x[p]<=x[j]+2*r)
{
p++;
if(p>=n&&x[n-1]==x[j]+2*r) return 0;
if(p>=n&&x[n-1]<x[j]+2*r) return 1;
}
j=p;
i++;
}
return -1;
}
|
hrist-dina/gifton
|
src/js/classes/FancyBox.js
|
<gh_stars>1-10
import $ from "jquery";
import fancybox from "@fancyapps/fancybox";
export class FancyBox {
constructor(selector = ".js-fancybox") {
this.selector = $(selector);
this.init();
}
init() {
this.bind();
}
bind() {
this.selector.fancybox();
}
}
|
henesy/plan9-1e
|
sys/src/cmd/acid/hobbit.c
|
<reponame>henesy/plan9-1e<gh_stars>0
#include <u.h>
#include <libc.h>
#include <bio.h>
#include <ctype.h>
#include <mach.h>
#define Extern extern
#include "acid.h"
#define STARTSYM "_main"
#define PROFSYM "_mainp"
#define FRAMENAME ".frame"
extern ulong hobbitfindframe(ulong);
extern void hobbitctrace(int);
extern void hobbitexcep(void);
extern int hobbitfoll(ulong, ulong*);
extern void hobbitprintins(Map *, char, int);
extern ulong hobbitbpfix(ulong);
extern void hobbitregfix(Reglist*);
static char *events[16] =
{
"syscall",
"exception",
"niladic trap",
"unimplemented instruction",
"non-maskable interrupt",
"interrupt 1",
"interrupt 2",
"interrupt 3",
"interrupt 4",
"interrupt 5",
"interrupt 6",
"timer 1 interrupt",
"timer 2 interrupt",
"FP exception",
"event 0x0E",
"event 0x0F",
};
static char *exceptions[16] =
{
"exception 0x00",
"integer zero-divide",
"trace",
"illegal instruction",
"alignment fault",
"privilege violation",
"unimplemented register",
"fetch fault",
"read fault",
"write fault",
"text fetch I/O bus error",
"data access I/O bus error",
"exception 0x0C",
"exception 0x0D",
"exception 0x0E",
"exception 0x0F",
};
Machdata hobbitmach =
{
{0x00, 0x00}, /* break point: KCALL $0 */
2, /* break point size */
0, /* init */
leswab, /* convert short to local byte order */
leswal, /* convert long to local byte order */
hobbitctrace, /* print C traceback */
hobbitfindframe, /* frame finder */
0, /* print fp registers */
hobbitregfix, /* fixup register address vars registers */
0, /* restore registers */
hobbitexcep, /* print exception */
hobbitbpfix, /* breakpoint fixup */
0,
0,
hobbitfoll, /* following addresses */
hobbitprintins, /* print instruction */
0, /* dissembler */
};
void
hobbitregfix(Reglist *rp)
{
Lsym *l;
while(rp->rname) {
l = look(rp->rname);
if(l == 0)
print("lost register %s\n", rp->rname);
else
l->v->ival = mach->kbase+rp->roffs;
rp++;
}
machdata->rsnarf = 0; /* Only need to fix once */
}
void
hobbitexcep(void)
{
ulong e;
e = strc.cause & 0x0F;
if (e == 1)
strc.excep = exceptions[rget("ID")&0x0F];
else
strc.excep = events[e];
}
ulong
hobbitbpfix(ulong bpaddr)
{
return bpaddr ^ 0x02;
}
ulong
hobbitfindframe(ulong addr)
{
ulong fp;
Symbol s, f;
fp = strc.sp;
while (findsym(strc.pc, CTEXT, &s)) {
if (strcmp(STARTSYM, s.name) == 0 || strcmp(PROFSYM, s.name) == 0)
break;
if (findlocal(&s, FRAMENAME, &f) == 0)
break;
fp += f.value - sizeof(long);
if (s.value == addr)
return fp;
if (get4(cormap, fp, SEGDATA, (long *)&strc.pc) == 0)
break;
}
return 0;
}
void
hobbitctrace(int modif)
{
int i;
Symbol s, f;
List **tail, *q, *l;
USED(modif);
strc.l = al(TLIST);
tail = &strc.l;
i = 0;
while (findsym(strc.pc, CTEXT, &s)) {
if(strcmp(STARTSYM, s.name) == 0 || strcmp(PROFSYM, 0) == 0)
break;
if (strc.pc != s.value) { /* not at first instruction */
if (findlocal(&s, FRAMENAME, &f) == 0)
break;
/* minus sizeof return addr */
strc.sp += f.value - mach->szaddr;
}
if(get4(cormap, strc.sp, SEGDATA, (long *)&strc.pc) == 0)
break;
q = al(TLIST);
*tail = q;
tail = &q->next;
l = al(TINT); /* Function address */
q->l = l;
l->ival = s.value;
l->fmt = 'X';
l->next = al(TINT); /* called from address */
l = l->next;
l->ival = strc.pc;
l->fmt = 'X';
l->next = al(TLIST); /* make list of params */
l = l->next;
l->l = listparams(&s, strc.sp);
l->next = al(TLIST); /* make list of locals */
l = l->next;
l->l = listlocals(&s, strc.sp);
if (++i > 40)
break;
}
if(i == 0)
error("no frames found");
}
|
jdenisgiguere/rasterframes
|
core/src/main/scala/astraea/spark/rasterframes/rules/SpatialFilterPushdownRules.scala
|
/*
* This software is licensed under the Apache 2 license, quoted below.
*
* Copyright 2018 Astraea. Inc.
*
* 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 astraea.spark.rasterframes.rules
import org.apache.spark.sql.catalyst.plans.logical.{Filter, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.rf.{FilterTranslator, VersionShims}
/**
* Logical plan manipulations to handle spatial queries on tile components.
*
* @since 12/21/17
*/
object SpatialFilterPushdownRules extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = {
plan.transformUp {
case f @ Filter(condition, lr @ SpatialRelationReceiver(sr: SpatialRelationReceiver[_] @unchecked)) ⇒
val preds = FilterTranslator.translateFilter(condition)
def foldIt[T <: SpatialRelationReceiver[T]](rel: T): T =
preds.foldLeft(rel)((r, f) ⇒ r.withFilter(f))
preds.filterNot(sr.hasFilter).map(p ⇒ {
val newRec = foldIt(sr)
Filter(condition, VersionShims.updateRelation(lr, newRec.asBaseRelation))
}).getOrElse(f)
}
}
}
|
steveuk/ham-and-jam
|
dlls/haj/haj_deployee.h
|
<reponame>steveuk/ham-and-jam
// haj_deployee.h
/////////////////////////////////////////////////////////////////////////////
#ifndef __INC_DEPLOYEE
#define __INC_DEPLOYEE
/////////////////////////////////////////////////////////////////////////////
// includes
#ifndef BASEANIMATING_H
#include "baseanimating.h"
#endif
/////////////////////////////////////////////////////////////////////////////
class CHajDeployee : public CBaseAnimating
{
public:
DECLARE_CLASS(CHajDeployee, CBaseAnimating);
DECLARE_DATADESC();
public:
// 'stuctors
CHajDeployee();
virtual ~CHajDeployee() {}
public:
virtual void Activate();
virtual void Spawn();
virtual void Precache();
virtual void Use(CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float value);
virtual int ObjectCaps( void ) { return BaseClass::ObjectCaps() | m_iCaps; }
private:
// entity data
string_t m_requiredPickup; // name of the required pickup item
// private data
EHANDLE m_hRequiredPickup;
int m_iCaps;
bool m_bDeployed;
};
/////////////////////////////////////////////////////////////////////////////
#endif
|
greenflute/noear_solon
|
_plugin/jap-solon-plugin/src/main/java/com/fujieid/jap/solon/integration/XPluginImpl.java
|
package com.fujieid.jap.solon.integration;
import com.fujieid.jap.solon.JapInitializer;
import com.fujieid.jap.solon.JapProps;
import org.noear.solon.SolonApp;
import org.noear.solon.core.Plugin;
/**
* @author noear
* @since 1.6
*/
public class XPluginImpl implements Plugin {
@Override
public void start(SolonApp app) {
app.beanMake(JapProps.class);
app.beanMake(JapInitializer.class);
}
}
|
matthew-dailey/playaround
|
accumulo/src/test/java/matt/PathAggregatorTest.java
|
package matt;
import org.junit.Test;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public class PathAggregatorTest {
@Test
public void removePath_test() {
Filterer.PathAggregator aggregator = new Filterer.PathAggregator(TestHelpers.inputPaths, TestHelpers.allExemplars);
Set<String> remaining = aggregator.getRemainingExemplars();
assertEquals(remaining, TestHelpers.allExemplars);
aggregator.removePath("ex1", "2004");
aggregator.removePath("ex1", "2000");
aggregator.removePath("ex1", "2001");
aggregator.removePath("ex1", "2002");
aggregator.removePath("ex1", "2003");
remaining = aggregator.getRemainingExemplars();
assertEquals(TestHelpers.allExemplars.size() - 1, remaining.size());
}
}
|
tiferrei/PEDASI
|
datasources/connectors/csv.py
|
<gh_stars>0
"""
Connectors for handling CSV data.
"""
import csv
import typing
from django.http import JsonResponse
import mongoengine
from mongoengine import context_managers
from .base import DataSetConnector, InternalDataConnector
class CsvConnector(DataSetConnector):
"""
Data connector for retrieving data from CSV files.
"""
def get_metadata(self,
params: typing.Optional[typing.Mapping[str, str]] = None):
"""
Return a JSON response from a CSV file.
:param params: Query params - ignored
:return: Metadata
"""
with open(self.location, 'r') as csvfile:
# Requires a header row
reader = csv.DictReader(csvfile)
return reader.fieldnames
def get_response(self,
params: typing.Optional[typing.Mapping[str, str]] = None):
"""
Return a JSON response from a CSV file.
CSV file must have a header row with column titles.
:param params: Optional query parameter filters
:return: Requested data
"""
try:
with open(self.location, 'r') as csvfile:
# Requires a header row
reader = csv.DictReader(csvfile)
if params is None:
params = {}
rows = []
for row in reader:
for key, value in params.items():
try:
if row[key].strip() != value.strip():
break
except KeyError:
# The filter field isn't in the data so no row can satisfy it
break
else:
# All filters match
rows.append(dict(row))
return JsonResponse({
'status': 'success',
'data': rows,
})
except UnicodeDecodeError:
return JsonResponse({
'status': 'error',
'message': 'Invalid CSV file',
}, status=500)
class CsvRow(mongoengine.DynamicDocument):
"""
MongoDB dynamic document to store CSV data.
Store in own database - distinct from PROV data.
Collection must be changed manually when managing CsvRows since all connectors use the same backing model.
"""
meta = {
'db_alias': 'internal_data',
}
def _type_convert(val):
"""
Attempt to convert a value into a numeric type.
:param val: Value to attempt to convert
:return: Converted value or unmodified value if conversion was not possible
"""
for conv in (int, float):
try:
return conv(val)
except ValueError:
pass
return val
class CsvToMongoConnector(InternalDataConnector, DataSetConnector):
"""
Data connector representing an internally hosted data source, backed by MongoDB.
This connector allows data to be pushed as well as retrieved.
"""
id_field_alias = '__id'
def clean_data(self, **kwargs):
index_fields = kwargs.get('index_fields', None)
if index_fields is None:
return
if isinstance(index_fields, str):
index_fields = [index_fields]
with context_managers.switch_collection(CsvRow, self.location) as collection:
for index_field in index_fields:
collection.create_index(index_field, background=True)
def clear_data(self):
with context_managers.switch_collection(CsvRow, self.location) as collection:
collection.objects.delete()
def post_data(self, data: typing.Union[typing.MutableMapping[str, str],
typing.List[typing.MutableMapping[str, str]]]):
def create_document(row: typing.MutableMapping[str, str]):
kwargs = {key: _type_convert(val) for key, val in row.items()}
# Can't store field 'id' in document - rename it
if 'id' in kwargs:
kwargs[self.id_field_alias] = kwargs.pop('id')
return kwargs
# Put data in collection belonging to this data source
with context_managers.switch_collection(CsvRow, self.location) as collection:
collection = collection._get_collection()
try:
# Data is a dictionary - a single row
collection.insert_one(create_document(data))
except AttributeError:
# Data is a list of dictionaries - multiple rows
documents = (create_document(row) for row in data)
collection.insert_many(documents)
def get_response(self,
params: typing.Optional[typing.Mapping[str, str]] = None):
# TODO accept parameters provided twice as an inclusive OR
if params is None:
params = {}
params = {key: _type_convert(val) for key, val in params.items()}
with context_managers.switch_collection(CsvRow, self.location) as collection:
records = collection.objects.filter(**params).exclude('_id')
data = list(records.as_pymongo())
# Couldn't store field 'id' in document - recover it
for item in data:
try:
item['id'] = item.pop(self.id_field_alias)
except KeyError:
pass
return JsonResponse({
'status': 'success',
'data': data,
})
|
lambdaxymox/barrelfish
|
include/dma/client/dma_client_channel.h
|
<gh_stars>100-1000
/*
* Copyright (c) 2014 ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Universitaetsstrasse 6, CH-8092 Zurich. Attn: Systems Group.
*/
#ifndef LIB_DMA_CLIENT_CHANNEL_H
#define LIB_DMA_CLIENT_CHANNEL_H
/**
* \brief pointer type conversion
*/
static inline struct dma_client_channel *dma_channel_to_client(struct dma_channel *chan)
{
return (struct dma_client_channel *)chan;
}
#endif /* LIB_DMA_CLIENT_CHANNEL_H */
|
arturolszak/hycube
|
src/main/java/net/hycube/maintenance/HyCubeRecoveryExtension.java
|
package net.hycube.maintenance;
import java.util.Arrays;
import net.hycube.core.InitializationException;
import net.hycube.core.NodeAccessor;
import net.hycube.environment.NodeProperties;
import net.hycube.extensions.Extension;
public class HyCubeRecoveryExtension implements Extension, HyCubeRecoveryExtensionEntryPoint {
public enum RecoveryExtensionEntryPointType {
RECOVER,
RECOVER_NS,
}
protected static final String PROP_KEY_RECOVERY_MANAGER = "RecoveryManager";
protected NodeAccessor nodeAccessor;
protected NodeProperties properties;
protected NodeProperties recoveryManagerProperties;
protected HyCubeRecoveryManager recoveryManager;
public HyCubeRecoveryManager getRecoveryManager() {
return recoveryManager;
}
@Override
public void initialize(NodeAccessor nodeAccessor, NodeProperties properties) throws InitializationException {
this.nodeAccessor = nodeAccessor;
this.properties = properties;
String recoveryManagerKey = properties.getProperty(PROP_KEY_RECOVERY_MANAGER);
if (recoveryManagerKey == null || recoveryManagerKey.trim().isEmpty()) throw new InitializationException(InitializationException.Error.INVALID_PARAMETER_VALUE, properties.getAbsoluteKey(PROP_KEY_RECOVERY_MANAGER), "Invalid parameter value: " + properties.getAbsoluteKey(PROP_KEY_RECOVERY_MANAGER));
recoveryManagerProperties = properties.getNestedProperty(PROP_KEY_RECOVERY_MANAGER, recoveryManagerKey);
recoveryManager = new HyCubeRecoveryManager();
}
@Override
public void postInitialize() throws InitializationException {
recoveryManager.initialize(this.nodeAccessor, this.recoveryManagerProperties);
}
@Override
public HyCubeRecoveryExtensionEntryPoint getExtensionEntryPoint() {
return (HyCubeRecoveryExtensionEntryPoint)this;
}
@Override
public Object call() {
throw new UnsupportedOperationException("The entry point method with 0 arguments is not implemented.");
}
@Override
public Object call(Object arg) {
return call(new Object[] {arg});
}
@Override
public Object call(Object entryPoint, Object[] args) {
if (entryPoint instanceof RecoveryExtensionEntryPointType) return callExtension((RecoveryExtensionEntryPointType)entryPoint, args);
else throw new IllegalArgumentException("Invalid argument. Cannot cast args[0] to RecoveryExtensionEntryPointType");
}
@Override
public Object call(Object[] args) {
if (args == null || args.length < 1) throw new IllegalArgumentException("The argument specified is null or empty.");
if (!(args[0] instanceof RecoveryExtensionEntryPointType)) throw new IllegalArgumentException("Invalid argument. Cannot cast args[0] to RecoveryExtensionEntryPointType");
RecoveryExtensionEntryPointType entryPoint = (RecoveryExtensionEntryPointType) args[0];
return callExtension(entryPoint, Arrays.copyOfRange(args, 1, args.length));
}
public Object callExtension(RecoveryExtensionEntryPointType entryPoint, Object[] args) {
switch (entryPoint) {
case RECOVER:
callRecover();
break;
case RECOVER_NS:
callRecoverNS();
break;
}
return null;
}
@Override
public void callRecover() {
recover();
}
protected void recover() {
recoveryManager.recover();
}
@Override
public void callRecoverNS() {
recoverNS();
}
protected void recoverNS() {
recoveryManager.recoverNS();
}
@Override
public void discard() {
recoveryManager.discard();
}
public static Object[] createRecoveryExtensionEntryPointArgs(RecoveryExtensionEntryPointType entryPoint) {
Object[] parameters = new Object[] {entryPoint};
return parameters;
}
}
|
sealuzh/termite-replication
|
manual-investigation/mosa/test-301.java
|
<reponame>sealuzh/termite-replication<filename>manual-investigation/mosa/test-301.java
public void test14() throws Throwable {
MockFile mockFile0 = new MockFile("", "");
FileIterator.FileIteratorBuilder fileIterator_FileIteratorBuilder0 = FileIterator.createDepthFirstFileIteratorBuilder(mockFile0);
File file0 = MockFile.createTempFile(" G!{", "", (File) mockFile0);
FileIterator fileIterator0 = fileIterator_FileIteratorBuilder0.build();
fileIterator0.setUpInitialState(file0);
assertTrue(file0.canExecute());
}
|
bombazook/prototok
|
spec/prototok/ciphers/V1/sign_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
RSpec.describe Prototok::Ciphers::V1::Sign do
end
|
ndoxx/wcore
|
hosts/surfaceplot/source/include/arguments.h
|
<reponame>ndoxx/wcore<gh_stars>0
#ifndef ARGUMENTS_H
#define ARGUMENTS_H
#include <cstdint>
namespace sandbox
{
extern void parse_program_arguments(int argc, char const *argv[]);
}
#endif // ARGUMENTS_H
|
featherfly/common
|
common-dozer/src/main/java/cn/featherfly/common/dozer/DozerBeanMapper.java
|
<reponame>featherfly/common
package cn.featherfly.common.dozer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.github.dozermapper.core.CustomConverter;
import com.github.dozermapper.core.CustomFieldMapper;
import com.github.dozermapper.core.Mapper;
import com.github.dozermapper.core.MapperModelContext;
import com.github.dozermapper.core.MappingException;
import com.github.dozermapper.core.builder.DestBeanBuilderCreator;
import com.github.dozermapper.core.cache.CacheManager;
import com.github.dozermapper.core.classmap.ClassMappings;
import com.github.dozermapper.core.classmap.Configuration;
import com.github.dozermapper.core.classmap.MappingFileData;
import com.github.dozermapper.core.classmap.generator.BeanMappingGenerator;
import com.github.dozermapper.core.config.BeanContainer;
import com.github.dozermapper.core.events.DefaultEventManager;
import com.github.dozermapper.core.events.EventListener;
import com.github.dozermapper.core.events.EventManager;
import com.github.dozermapper.core.factory.DestBeanCreator;
import com.github.dozermapper.core.metadata.DozerMappingMetadata;
import com.github.dozermapper.core.metadata.MappingMetadata;
import com.github.dozermapper.core.propertydescriptor.PropertyDescriptorFactory;
/**
* Public Dozer Mapper implementation. This should be used/defined as a
* singleton within your application. This class performs several one-time
* initializations and loads the custom xml mappings, so you will not want to
* create many instances of it for performance reasons. Typically a system will
* only have one DozerBeanMapper instance per VM. If you are using an IOC
* framework (i.e Spring), define the Mapper as singleton="true". If you are not
* using an IOC framework, a DozerBeanMapperSingletonWrapper convenience class
* has been provided in the Dozer jar.
* <p>
* It is technically possible to have multiple DozerBeanMapper instances
* initialized, but it will hinder internal performance optimizations such as
* caching.
*/
public class DozerBeanMapper implements Mapper, MapperModelContext {
private final BeanContainer beanContainer;
private final DestBeanCreator destBeanCreator;
private final DestBeanBuilderCreator destBeanBuilderCreator;
private final BeanMappingGenerator beanMappingGenerator;
private final PropertyDescriptorFactory propertyDescriptorFactory;
private final ClassMappings customMappings;
private final Configuration globalConfiguration;
private final List<String> mappingFiles;
private final List<CustomConverter> customConverters;
private final List<EventListener> eventListeners;
private final Map<String, CustomConverter> customConvertersWithId;
private CustomFieldMapper customFieldMapper;
// There are no global caches. Caches are per bean mapper instance
private final CacheManager cacheManager;
private EventManager eventManager;
// new feature by featherfly -----------------
private boolean isMapNull = true;
private boolean isMapEmptyString = true;
// new feature by featherfly -----------------
public DozerBeanMapper(List<String> mappingFiles, BeanContainer beanContainer, DestBeanCreator destBeanCreator,
DestBeanBuilderCreator destBeanBuilderCreator, BeanMappingGenerator beanMappingGenerator,
PropertyDescriptorFactory propertyDescriptorFactory, List<CustomConverter> customConverters,
List<MappingFileData> mappingsFileData, List<EventListener> eventListeners,
CustomFieldMapper customFieldMapper, Map<String, CustomConverter> customConvertersWithId,
ClassMappings customMappings, Configuration globalConfiguration, CacheManager cacheManager,
boolean isMapNull, boolean isMapEmptyString) {
this.beanContainer = beanContainer;
this.destBeanCreator = destBeanCreator;
this.destBeanBuilderCreator = destBeanBuilderCreator;
this.beanMappingGenerator = beanMappingGenerator;
this.propertyDescriptorFactory = propertyDescriptorFactory;
this.customConverters = new ArrayList<>(customConverters);
this.eventListeners = new ArrayList<>(eventListeners);
this.mappingFiles = new ArrayList<>(mappingFiles);
this.customFieldMapper = customFieldMapper;
this.customConvertersWithId = new HashMap<>(customConvertersWithId);
eventManager = new DefaultEventManager(eventListeners);
this.customMappings = customMappings;
this.globalConfiguration = globalConfiguration;
this.cacheManager = cacheManager;
this.isMapEmptyString = isMapEmptyString;
this.isMapNull = isMapNull;
}
/**
* {@inheritDoc}
*/
@Override
public void map(Object source, Object destination, String mapId) throws MappingException {
getMappingProcessor().map(source, destination, mapId);
}
/**
* {@inheritDoc}
*/
@Override
public <T> T map(Object source, Class<T> destinationClass, String mapId) throws MappingException {
return getMappingProcessor().map(source, destinationClass, mapId);
}
/**
* {@inheritDoc}
*/
@Override
public <T> T map(Object source, Class<T> destinationClass) throws MappingException {
return getMappingProcessor().map(source, destinationClass);
}
/**
* {@inheritDoc}
*/
@Override
public void map(Object source, Object destination) throws MappingException {
getMappingProcessor().map(source, destination);
}
protected Mapper getMappingProcessor() {
Mapper processor = new MappingProcessor(customMappings, globalConfiguration, cacheManager, customConverters,
eventManager, customFieldMapper, customConvertersWithId, beanContainer, destBeanCreator,
destBeanBuilderCreator, beanMappingGenerator, propertyDescriptorFactory, isMapNull, isMapEmptyString);
return processor;
}
/**
* {@inheritDoc}
*/
@Override
public MappingMetadata getMappingMetadata() {
return new DozerMappingMetadata(customMappings);
}
/**
* {@inheritDoc}
*/
@Override
public MapperModelContext getMapperModelContext() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getMappingFiles() {
return Collections.unmodifiableList(mappingFiles);
}
/**
* {@inheritDoc}
*/
@Override
public List<CustomConverter> getCustomConverters() {
return Collections.unmodifiableList(customConverters);
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, CustomConverter> getCustomConvertersWithId() {
return Collections.unmodifiableMap(customConvertersWithId);
}
/**
* {@inheritDoc}
*/
@Override
public List<? extends EventListener> getEventListeners() {
return Collections.unmodifiableList(eventListeners);
}
/**
* {@inheritDoc}
*/
@Override
public CustomFieldMapper getCustomFieldMapper() {
return customFieldMapper;
}
}
|
tgoprince/menthor-editor
|
net.menthor.ontouml2uml/src/net/menthor/ontouml2uml/OntoUML2UML.java
|
<reponame>tgoprince/menthor-editor<filename>net.menthor.ontouml2uml/src/net/menthor/ontouml2uml/OntoUML2UML.java<gh_stars>10-100
package net.menthor.ontouml2uml;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import net.menthor.common.file.FileUtil;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.uml2.uml.AggregationKind;
import RefOntoUML.parser.OntoUMLParser;
/**
* This class transforms OntoUML models into UML. It simply ignores the stereotypes of classes and relations.
* The user can optionally ignore the package hierarchy or the derivation relationship in the transformation.
*
* Furthermore, the user can additionally transform OntoUML into a Temporal UML model that includes UFO's
* branching time structure. In this temporal UML model, each association of the OntoUML model is reified into a class.
* This reified class in turn and every other top level class of the model is additionally linked to the worlds in which they exist.
* Moreover, several world operations and existence operations were added to classes. This conversion is useful for
* the Temporal OCL extension developed which uses this temporal UML model (in background) for manipulation of OCL constructs.
*
* @author <NAME>
*
*/
public class OntoUML2UML {
public static String log = new String();
private static OntoUML2UMLOption options = new OntoUML2UMLOption();
private static Transformator utransformer;
private static org.eclipse.uml2.uml.Package umlRoot;
private static String umlPath = new String();
private static Reificator tgenerator;
private static ProfileAplicator profileApplicator;
//*****************************
//Pure UML
//*****************************
public static Resource convertToUML (RefOntoUML.Package refmodel, String umlPath)
{
return convertToUML(refmodel, umlPath, options);
}
public static Resource convertToUML (OntoUMLParser refparser, String umlPath)
{
return convertToUML(refparser, umlPath, options);
}
public static Resource convertToUML (RefOntoUML.Package refmodel, String umlPath, OntoUML2UMLOption opt)
{
log="";
options=opt;
Resource umlResource = null;
OntoUMLParser refparser = new OntoUMLParser(refmodel);
utransformer = new Transformator(refparser,opt);
org.eclipse.uml2.uml.Package umlmodel = utransformer.run();
OntoUML2UML.umlPath=umlPath;
umlResource = OntoUML2UMLUtil.saveUML(umlPath,umlmodel);
return umlResource;
}
public static org.eclipse.uml2.uml.Package convertToUMLNoSaving (RefOntoUML.Package refmodel, String umlPath, OntoUML2UMLOption opt)
{
log="";
options=opt;
OntoUMLParser refparser = new OntoUMLParser(refmodel);
utransformer = new Transformator(refparser,opt);
org.eclipse.uml2.uml.Package umlmodel = utransformer.run();
OntoUML2UML.umlPath=umlPath;
return umlmodel;
}
public static Resource convertToUML (OntoUMLParser refparser, String umlPath, OntoUML2UMLOption opt)
{
log="";
options=opt;
Resource umlResource = null;
utransformer = new Transformator(refparser,opt);
org.eclipse.uml2.uml.Package umlmodel = utransformer.run();
OntoUML2UML.umlPath=umlPath;
umlResource = OntoUML2UMLUtil.saveUML(umlPath,umlmodel);
return umlResource;
}
public static org.eclipse.uml2.uml.Package convertToUMLNoSaving (OntoUMLParser refparser, String umlPath, OntoUML2UMLOption opt)
{
log="";
options=opt;
utransformer = new Transformator(refparser,opt);
org.eclipse.uml2.uml.Package umlmodel = utransformer.run();
OntoUML2UML.umlPath=umlPath;
return umlmodel;
}
//*****************************
//UML Profile
//*****************************
public static Resource convertToUMLProfile (OntoUMLParser refparser, String umlPath)
{
return convertToUMLProfile(refparser, umlPath, options);
}
public static Resource convertToUMLProfile (RefOntoUML.Package refmodel, String umlPath)
{
return convertToUMLProfile(refmodel, umlPath, options);
}
public static void turnIntoUMLProfile(org.eclipse.uml2.uml.Package umlRoot, String umlPath)
{
profileApplicator = new ProfileAplicator(umlRoot, umlPath, utransformer.getConverter().umap);
profileApplicator.apply();
try {
profileApplicator.save();
profileApplicator.resolveURIs();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Resource convertToUMLProfile (RefOntoUML.Package refmodel, String umlPath, OntoUML2UMLOption opt)
{
umlRoot = convertToUMLNoSaving(refmodel, umlPath, opt);
profileApplicator = new ProfileAplicator(umlRoot, umlPath, utransformer.getConverter().umap);
profileApplicator.apply();
log += profileApplicator.getLog();
try {
Resource result = profileApplicator.save();
profileApplicator.resolveURIs();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Resource convertToUMLProfile(OntoUMLParser refparser, String umlPath, OntoUML2UMLOption opt)
{
umlRoot = convertToUMLNoSaving(refparser, umlPath, opt);
profileApplicator = new ProfileAplicator(umlRoot, umlPath, utransformer.getConverter().umap);
profileApplicator.apply();
log += profileApplicator.getLog();
try {
Resource result = profileApplicator.save();
profileApplicator.resolveURIs();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//*****************************
//Temporal pure UML
//*****************************
public static Resource convertToTemporalUML (OntoUMLParser refparser, String umlPath, boolean simplifiedVersion)
{
return convertToTemporalUML(refparser, umlPath, options, simplifiedVersion);
}
public static Resource convertToTemporalUML (RefOntoUML.Package refmodel, String umlPath, boolean simplifiedVersion)
{
return convertToTemporalUML(refmodel, umlPath, options, simplifiedVersion);
}
public static Resource includeTemporalStructure(org.eclipse.uml2.uml.Package umlRoot, String umlPath, boolean simplifiedVersion)
{
if(!simplifiedVersion){
tgenerator = new CompleteReificator(umlRoot, utransformer.getConverter().ufactory, utransformer.getConverter().umap);
}else{
tgenerator = new SimplifiedReificator(umlRoot, utransformer.getConverter().ufactory, utransformer.getConverter().umap);
}
tgenerator.run();
log += tgenerator.getLog();
generateOCLFile(umlPath, umlRoot);
return OntoUML2UMLUtil.saveUML(umlPath,umlRoot);
}
public static org.eclipse.uml2.uml.Association includeHistoricalRelationship(org.eclipse.uml2.uml.Package umlRoot,
String sourceType, String relationshipName, String targetType,
String sourceEndName, String sourceMult, String targetEndName, String targetMult) throws ParseException
{
org.eclipse.uml2.uml.Type sourceClass= (org.eclipse.uml2.uml.Type) utransformer.getConverter().GetElement(sourceType);
org.eclipse.uml2.uml.Type targetClass = (org.eclipse.uml2.uml.Type)utransformer.getConverter().GetElement(targetType);
String end1Name = sourceEndName;
String end2Name = targetEndName;
int[] end1Mult = ElementConverter.multiplicityFromString(sourceMult);
int[] end2Mult = ElementConverter.multiplicityFromString(targetMult);
org.eclipse.uml2.uml.Association a2 = sourceClass.createAssociation(
true, AggregationKind.NONE_LITERAL, end1Name, end1Mult[0], end1Mult[1], targetClass,
true, AggregationKind.NONE_LITERAL, end2Name, end2Mult[0], end2Mult[1]
);
if(a2==null) new Exception("Could not create the historical relationship: "+relationshipName);
a2.setName(relationshipName);
a2.setIsDerived(false);
ElementConverter.outln("UML:Association :: name="+a2.getName()+", visibility="+a2.getVisibility().getName()+", isAbstract="+a2.isAbstract()+", isDerived="+a2.isDerived());
org.eclipse.uml2.uml.Property p2 = a2.getMemberEnds().get(0);
org.eclipse.uml2.uml.Property p1 = a2.getMemberEnds().get(1);
p1.setName(sourceEndName);
p2.setName(targetEndName);
utransformer.getConverter().setMultiplicityFromString(p1, sourceMult);
utransformer.getConverter().setMultiplicityFromString(p2, targetMult);
ElementConverter.outln("UML:Property :: "+"name="+p1.getName()+", isDerived="+p1.isDerived()+", lower="+p1.getLower()+", upper="+p1.getUpper()+
", isLeaf="+p1.isLeaf()+", isStatic="+p1.isStatic()+", isReadOnly="+p1.isReadOnly());
ElementConverter.outln("UML:Property :: "+"name="+p2.getName()+", isDerived="+p2.isDerived()+", lower="+p2.getLower()+", upper="+p2.getUpper()+
", isLeaf="+p2.isLeaf()+", isStatic="+p2.isStatic()+", isReadOnly="+p2.isReadOnly());
/** Operation Source -> Target */
EList<String> parameters = new BasicEList<String>();
EList<org.eclipse.uml2.uml.Type> typeParameters = new BasicEList<org.eclipse.uml2.uml.Type>();
org.eclipse.uml2.uml.Operation op = ((org.eclipse.uml2.uml.Class)sourceClass).createOwnedOperation(targetEndName, parameters, typeParameters, targetClass);
utransformer.getConverter().setMultiplicityFromString(op, targetMult);
ElementConverter.outln("UML:Operation :: "+"name="+op.getName()+", type="+op.getType().getName()+", lower="+op.getLower()+", upper="+op.getUpper()+"");
/** Operation Target -> Source */
parameters = new BasicEList<String>();
typeParameters = new BasicEList<org.eclipse.uml2.uml.Type>();
op = ((org.eclipse.uml2.uml.Class)targetClass).createOwnedOperation(sourceEndName, parameters, typeParameters, sourceClass);
utransformer.getConverter().setMultiplicityFromString(op, sourceMult);
ElementConverter.outln("UML:Operation :: "+"name="+op.getName()+", type="+op.getType().getName()+", lower="+op.getLower()+", upper="+op.getUpper()+"");
return a2;
}
public static Resource convertToTemporalUML (RefOntoUML.Package refmodel, String umlPath, OntoUML2UMLOption opt, boolean simplifiedVersion)
{
Resource umlResource = convertToUML(refmodel, umlPath, opt);
umlRoot = (org.eclipse.uml2.uml.Package)umlResource.getContents().get(0);
if(!simplifiedVersion){
tgenerator = new CompleteReificator(umlRoot, utransformer.getConverter().ufactory, utransformer.getConverter().umap);
}else{
tgenerator = new SimplifiedReificator(umlRoot, utransformer.getConverter().ufactory, utransformer.getConverter().umap);
}
tgenerator.run();
log += tgenerator.getLog();
generateOCLFile(umlPath,umlRoot);
umlResource = OntoUML2UMLUtil.saveUML(umlPath,umlRoot);
return umlResource;
}
public static Resource convertToTemporalUML(OntoUMLParser refparser, String umlPath, OntoUML2UMLOption opt, boolean simplifiedVersion)
{
Resource umlResource = convertToUML(refparser, umlPath, opt);
umlRoot = (org.eclipse.uml2.uml.Package)umlResource.getContents().get(0);
if(!simplifiedVersion){
tgenerator = new CompleteReificator(umlRoot, utransformer.getConverter().ufactory, utransformer.getConverter().umap);
}else{
tgenerator = new SimplifiedReificator(umlRoot, utransformer.getConverter().ufactory, utransformer.getConverter().umap);
}
tgenerator.run();
log += tgenerator.getLog();
generateOCLFile(umlPath,umlRoot);
umlResource = OntoUML2UMLUtil.saveUML(umlPath,umlRoot);
return umlResource;
}
private static void generateOCLFile(String umlPath, org.eclipse.uml2.uml.Package root)
{
File oclFile = FileUtil.createFile(umlPath.replace(".uml", ".ocl"));
int lastIndex = umlPath.lastIndexOf(File.separator)+1;
if(lastIndex<=0) lastIndex = umlPath.lastIndexOf("/")+1;
String fileName = umlPath.substring(lastIndex);
String header = new String("import '"+fileName+"'\n\n package _'"+root.getName()+"'\n\n");
String footer = new String("endpackage");
try {
FileUtil.writeToFile(header+tgenerator.getConstraints()+footer, oclFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
//******************************
// Getters
//******************************
public static HashMap <RefOntoUML.Element,org.eclipse.uml2.uml.Element> getStandardMap ()
{
return utransformer.getConverter().getMap();
}
public static HashMap<RefOntoUML.Element, List<org.eclipse.uml2.uml.Element>> getTemporalMap()
{
if (tgenerator !=null) return tgenerator.getMap();
else return null;
}
public static String getLog ()
{
return log;
}
public static org.eclipse.uml2.uml.Package getRoot()
{
return umlRoot;
}
public static String getUmlPath() {
return umlPath;
}
}
|
walison17/pulso-api
|
pulso/wsgi.py
|
<reponame>walison17/pulso-api
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pulso.settings")
application = get_wsgi_application()
|
jdamiani27/PyRaceView
|
pyraceview/messages/car_stats.py
|
from numpy import uint32
from ..messages import MsgBase
from ..util import BitBuffer, ByteArray
from ..percar import PerCarStatsData
from dataclasses import dataclass
from typing import List
TIMECODE_BITS = uint32(32)
NUM_CARS_BITS = uint32(8)
@dataclass
class MsgCarStats(MsgBase):
timecode: int
num_cars:int
car_data: List[PerCarStatsData]
def __init__(self, msg_bytes: bytes):
super().__init__(msg_bytes)
bit_buffer = BitBuffer(ByteArray(msg_bytes))
bit_buffer.set_position(7)
self.timecode = int(bit_buffer.get_bits(TIMECODE_BITS))
self.num_cars = int(bit_buffer.get_bits(NUM_CARS_BITS))
self.car_data = []
for _ in range(self.num_cars):
self.car_data.append(PerCarStatsData(bit_buffer))
|
mauro7x/AlgoCraft
|
src/modelo/herramientas/reglas/ReglasEstandarPico.java
|
package modelo.herramientas.reglas;
import modelo.recursos.BloqueDiamante;
import modelo.recursos.BloqueMadera;
import modelo.recursos.BloqueMetal;
import modelo.recursos.BloquePiedra;
public class ReglasEstandarPico implements ReglasDesgasteRecurso {
@Override
public void gastar(BloqueMetal metal, float fuerza) {
// no gasto metal con pico
}
@Override
public void gastar(BloqueMadera madera, float fuerza) {
// no gasto madera con pico
}
@Override
public void gastar(BloquePiedra piedra, float fuerza) {
piedra.gastar(fuerza);
}
@Override
public void gastar(BloqueDiamante diamante, float fuerza) {
// no gasto diamante con pico
}
}
|
cameljockey/ten-pin-bowling
|
src/main/java/com/bowling/round/Round.java
|
/*
* Copyright (C) 2014 <NAME>.
*
* 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 com.bowling.round;
/**
* <p>
* Interface created to Represent a full {@link com.bowling.round.Round}
* containing two {@link com.bowling.roll.Roll}s. However if its a Strike then
* only 1 {@link com.bowling.roll.Roll}. The interface is culmination of three
* other Interfaces designed on SOLID principles. This Interface provides all
* three as single representation to help in providing more extensibility.
* </p>
*
* @author <NAME>.
*/
public interface Round extends RoundBonus, RoundConsumed, RoundScore {
}
|
Uvacoder/html-demo-code-and-experiments
|
Node-FileUtils/examples/isFile.js
|
<filename>Node-FileUtils/examples/isFile.js
var File = require ("../build/file-utils").File;
new File ("../src").isFile (function (error, isFile){
console.log (isFile); //Prints: false
new File ("isFile.js").isFile (function (error, isFile){
console.log (isFile); //Prints: true
});
});
|
Bigfluf/BloodMagic
|
src/main/java/WayofTime/alchemicalWizardry/common/harvest/GourdHarvestHandler.java
|
<reponame>Bigfluf/BloodMagic
package WayofTime.alchemicalWizardry.common.harvest;
import WayofTime.alchemicalWizardry.api.harvest.IHarvestHandler;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
public class GourdHarvestHandler implements IHarvestHandler
{
public boolean canHandleBlock(Block block)
{
return block == Blocks.melon_block || block == Blocks.pumpkin;
}
@Override
public boolean harvestAndPlant(World world, int xCoord, int yCoord, int zCoord, Block block, int meta)
{
if (!this.canHandleBlock(block))
{
return false;
}
world.func_147480_a(xCoord, yCoord, zCoord, true);
return true;
}
}
|
equinor/lcm
|
api/tests/create_product_row_test.py
|
<filename>api/tests/create_product_row_test.py
import unittest
from tests.utils import read_file
from util.excel import excel_raw_file_to_sheet, sheet_to_bridge_dict
from util.azure_table import process_meta_blob
class CreateProductTableRow(unittest.TestCase):
@staticmethod
def test_create_row():
with open("test_data/metadata.csv") as meta_file:
productdata = process_meta_blob(meta_file)
product_bridge_file = read_file("test_data/flow-carb10.xlsx")
product_sheet = excel_raw_file_to_sheet(product_bridge_file)
product_data = sheet_to_bridge_dict(product_sheet)
productdata[0]["cumulative"] = product_data["cumulative"]
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/tree-ssa/pr21029.c
|
<reponame>best08618/asylo
/* { dg-do run } */
/* { dg-options "-O2 -fwrapv" } */
/* PR tree-optimization/21029
f() used to get optimized to an infinite loop by tree-vrp, because
j is assumed to be non-negative. Even though the conversion from
unsigned to signed has unspecified results if the expression value
is not representable in the signed type, the compiler itself (e.g.,
the Ada front end) depends on wrap-around behavior. */
unsigned int f(void) {
unsigned char i = 123;
signed char j;
do
if ((j = (signed char) i) < 0)
break;
else
i++;
while (1);
return i;
}
/* Now let's torture it a bit further. Narrowing conversions need
similar treatment. */
unsigned int f1 (void) {
unsigned short i = 123;
signed char j;
do
if ((j = (signed char) i) < 0)
break;
else
i++;
while (1);
return i;
}
/* And so do widening conversions. */
unsigned int f2 (void) {
unsigned char i = 123;
signed short j;
do
if ((j = (signed short) (signed char) i) < 0)
break;
else
i++;
while (1);
return i;
}
/* Check same-sign truncations with an increment that turns into
decrements. */
unsigned int f3 (void) {
signed short i = 5;
signed char j;
do
if ((j = (signed char) i) < 0)
break;
else
i += 255;
while (1);
return i;
}
/* Check that the truncation above doesn't confuse the result of the
test after a widening conversion. */
unsigned int f4 (void) {
signed short i = -123;
signed int j;
do
if ((j = (signed int) (signed char) i) > 0)
break;
else
i += 255;
while (1);
return i;
}
/* Even if we omit the widening truncation, the narrowing truncation
is implementation-defined. */
unsigned int f5 (void) {
signed long i = -123;
signed char j;
do
if ((j = (signed char) i) > 0)
break;
else
i += 255;
while (1);
return i;
}
int main (void) {
f ();
f1 ();
f2 ();
f3 ();
f4 ();
f5 ();
return 0;
}
|
dymmerufc/web-dymmer-backend
|
src/models/qualityMeasureDataset.js
|
const mongoose = require('../database/index');
const qualityMeasureDatasetSchema = new mongoose.Schema({
featureModel: {
type: mongoose.Schema.Types.ObjectId,
ref: 'FeatureModels',
required: true,
},
qualityMeasures: [{
qualityMeasureId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'QualityMeasure',
required: true,
},
qualityMeasureValue: {
type: Number,
required: true,
},
}],
updatedAt: {
type: Date,
default: Date.now,
required: true,
},
});
const QualityMeasureDataset = mongoose.model('QualityMeasureDataset', qualityMeasureDatasetSchema);
module.exports = QualityMeasureDataset;
|
gaoht/house
|
java/classes3/com/ziroom/ziroomcustomer/util/af.java
|
<reponame>gaoht/house
package com.ziroom.ziroomcustomer.util;
import android.content.Context;
import com.freelxl.baselibrary.f.g;
public class af
{
public static void showToast(Context paramContext, int paramInt)
{
showToast(paramContext, paramInt, 0);
}
public static void showToast(Context paramContext, int paramInt1, int paramInt2)
{
g.textToast(paramContext, paramInt1, paramInt2);
}
public static void showToast(Context paramContext, String paramString)
{
showToast(paramContext, paramString, 0);
}
public static void showToast(Context paramContext, String paramString, int paramInt)
{
g.textToast(paramContext, paramString, paramInt);
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes3-dex2jar.jar!/com/ziroom/ziroomcustomer/util/af.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
alexjung/ComputeLibrary
|
arm_compute/core/NEON/kernels/assembly/arm_gemm_compute_iface.hpp
|
<gh_stars>1-10
/*
* Copyright (c) 2020 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include "arm_compute/core/Window.h"
#include "arm_compute/core/Dimensions.h"
#include "arm_compute/core/NEON/kernels/arm_gemm/ndrange.hpp"
#include <cassert>
/* This file contains mapping between integral types used in arm_compute and arm_gemm
* These two codebases both require a degree of separation for the sake of modularity
* so maintain their own types which represent similar information.
*/
namespace arm_gemm {
//we want to unify the maximum number of dimensions used beween arm_gemm and arm compute library
constexpr std::size_t ndrange_max =
arm_compute::Dimensions<unsigned int>::num_max_dimensions;
using ndrange_t=NDRange<ndrange_max>;
using ndcoord_t=NDCoordinate<ndrange_max>;
/* Converts an `arm_gemm::ndrange_t` to a `arm_compute::Window`
*
* As `NDRange<T>` does not not encode start positions, we specify
* the start to be zero in the produced `arm_compute::Window`
*
* @param [ndr] the `arm_gemm::ndrange_t` we wish to convert into a `arm_compute::Window`
* @returns an `arm_compute::Window` representing the same dimensional ranges as `ndr`
*/
inline arm_compute::Window to_window(const ndrange_t& ndr) {
arm_compute::Window win;
for(unsigned int i = 0; i!=ndrange_max; ++i) {
//populate the window with the dimensions of the NDRange
win.set(i, arm_compute::Window::Dimension(0, ndr.get_size(i)));
}
return win;
}
/*
* Converts an `arm_gemm::ndcoord_t` to a `arm_compute::Window`
*
* @param [ndc] the `arm_gemm::ndcoord_t` we wish to convert into a `arm_compute::Window`
* @returns an `arm_compute::Window` representing the same dimensional ranges as `ndc`
*/
inline arm_compute::Window to_window(const ndcoord_t& ndc) {
arm_compute::Window win;
for(unsigned int i = 0; i!=ndrange_max; ++i) {
const auto start = ndc.get_position(i);
const auto size = ndc.get_size(i);
const auto stop = start + size;
//populate the window with the dimensions of the NDRange
win.set(i, arm_compute::Window::Dimension(start, stop));
}
return win;
}
/** Convert an `arm_compute::Window` to an `arm_gemm::NDRange` of the same max dimensions
*
* It should be noted that `arm_compute::Window` specifies a `start()` and an `end()`
* where as `arm_gemm::ndrange_t` only has a size, as a result we store the delta between the range
*
* @param [win] the `arm_compute::Window` we want to convert to `arm_gemm::ndrange_t`
* @return the resultant ndrange_t
*/
inline ndrange_t to_ndrange(const arm_compute::Window& win) {
return {
static_cast<unsigned int>(win[0].end() - win[0].start()),
static_cast<unsigned int>(win[1].end() - win[1].start()),
static_cast<unsigned int>(win[2].end() - win[2].start()),
static_cast<unsigned int>(win[3].end() - win[3].start()),
static_cast<unsigned int>(win[4].end() - win[4].start()),
static_cast<unsigned int>(win[5].end() - win[5].start())
};
}
/** Convert an `arm_compute::Window` to an `arm_gemm::NDCoord` of the same max dimensions
*
* @param [win] the `arm_compute::Window` we want to convert to `arm_gemm::ndcoord_t`
* @return the resultant ndcoord_t
*/
inline ndcoord_t to_ndcoord(const arm_compute::Window& win) {
return {
{ static_cast<unsigned int>(win[0].start()), static_cast<unsigned int>(win[0].end() - win[0].start()) },
{ static_cast<unsigned int>(win[1].start()), static_cast<unsigned int>(win[1].end() - win[1].start()) },
{ static_cast<unsigned int>(win[2].start()), static_cast<unsigned int>(win[2].end() - win[2].start()) },
{ static_cast<unsigned int>(win[3].start()), static_cast<unsigned int>(win[3].end() - win[3].start()) },
{ static_cast<unsigned int>(win[4].start()), static_cast<unsigned int>(win[4].end() - win[4].start()) },
{ static_cast<unsigned int>(win[5].start()), static_cast<unsigned int>(win[5].end() - win[5].start()) }
};
}
} //namespace arm_gemm
|
zanachka/webdext
|
chrome-debug/contentscript.js
|
<reponame>zanachka/webdext<gh_stars>10-100
var s = document.createElement('script');
s.src = chrome.extension.getURL('webdext.js');
(document.head||document.documentElement).appendChild(s);
|
RamilGauss/MMO-Framework
|
Source/Core/TornadoEngine/Modules/FeatureManager.h
|
<filename>Source/Core/TornadoEngine/Modules/FeatureManager.h
/*
Author: <NAME> a.k.a. Gauss
<NAME>
Contacts: [<EMAIL>, <EMAIL>]
See for more information LICENSE.md.
*/
#pragma once
#include <vector>
#include <ECS/include/Feature.h>
namespace nsTornadoEngine
{
class DllExport TFeatureManager
{
int mCurrentIndex = 0;
std::vector<nsECSFramework::TFeature*> mSlots;
public:
virtual ~TFeatureManager();
void Work();
// For current slot
void AddSystem(nsECSFramework::TSystem* p);
void RemoveSystem(nsECSFramework::TSystem* p);
bool HasSystem(nsECSFramework::TSystem* p);
nsECSFramework::TEntityManager* GetCurrentEntMng() const;
int GetSlotCount() const;
void SetCurrentSlotIndex(int index);
int GetCurrentSlotIndex() const;
int CreateSlot(nsECSFramework::TEntityManager* pEntMng);
void DestroyLastSlot();
void Clear();
private:
nsECSFramework::TFeature* GetCurrentSlot() const;
};
}
|
js-lib-com/wood
|
wood-core/src/main/java/js/wood/eval/Opcode.java
|
<reponame>js-lib-com/wood
package js.wood.eval;
/**
* Operator codes and factory for operator instances. This class provides implemented operator constants and related
* operator instances. For every opcode constant there is an {@link Operator} instance retrievable using
* {@link #instance()} getter.
* <p>
* Current implemented operators:
* <table>
* <tr>
* <td><b>Opcode
* <td><b>Operator Class
* <td><b>Description
* <td><b>Sample Syntax
* <tr>
* <td>{@link #ADD}
* <td>{@link AddOperatorTest}
* <td>Generic sum for numeric values, numeric with measurement units and string concatenation
* <td>(add 1 2 3)
* </table>
*
* @author <NAME>
* @since 1.0
*/
enum Opcode
{
/** Generic sum for numeric values, numeric with measurement units and string concatenation. */
ADD,
/** Arithmetic subtraction. */
SUB,
/** Arithmetic multiplication. */
MUL;
/** Current implemented operators. */
private static Operator[] OPERATORS = new Operator[]
{
// !!! order should match opcode constants
new AddOperator(), new SubOperator(), new MulOperator()
};
/**
* Get the instance of the operator designated by opcode constant.
*
* @return operator instance.
*/
public Operator instance()
{
return OPERATORS[ordinal()];
}
/** The length of the largest operator name. This values is initialized on the fly by {@link #maxLength()}. */
private static int maxLength;
/**
* Get the length of the largest operator name. Takes care to initialize {@link #maxLength} on the fly; for this
* traverses all opcode names and keep the maximum length.
*
* @return maximum length of operator name.
* @see #maxLength
*/
public static int maxLength()
{
if(maxLength == 0) {
for(Opcode opcode : Opcode.values()) {
if(maxLength < opcode.name().length()) {
maxLength = opcode.name().length();
}
}
}
return maxLength;
}
}
|
sarang-apps/darshan_browser
|
components/services/filesystem/directory_impl_unittest.cc
|
// Copyright 2015 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.
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <string>
#include "base/macros.h"
#include "base/stl_util.h"
#include "base/test/task_environment.h"
#include "components/services/filesystem/directory_test_helper.h"
#include "components/services/filesystem/public/mojom/directory.mojom.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace filesystem {
namespace {
class DirectoryImplTest : public testing::Test {
public:
DirectoryImplTest() = default;
mojo::Remote<mojom::Directory> CreateTempDir() {
return test_helper_.CreateTempDir();
}
private:
base::test::TaskEnvironment task_environment_;
DirectoryTestHelper test_helper_;
DISALLOW_COPY_AND_ASSIGN(DirectoryImplTest);
};
constexpr char kData[] = "one two three";
TEST_F(DirectoryImplTest, Read) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
// Make some files.
const struct {
const char* name;
uint32_t open_flags;
} files_to_create[] = {
{"my_file1", mojom::kFlagRead | mojom::kFlagWrite | mojom::kFlagCreate},
{"my_file2", mojom::kFlagWrite | mojom::kFlagCreate},
{"my_file3", mojom::kFlagAppend | mojom::kFlagCreate}};
for (size_t i = 0; i < base::size(files_to_create); i++) {
error = base::File::Error::FILE_ERROR_FAILED;
bool handled =
directory->OpenFile(files_to_create[i].name, mojo::NullReceiver(),
files_to_create[i].open_flags, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
}
// Make a directory.
error = base::File::Error::FILE_ERROR_FAILED;
bool handled = directory->OpenDirectory(
"my_dir", mojo::NullReceiver(),
mojom::kFlagRead | mojom::kFlagWrite | mojom::kFlagCreate, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
error = base::File::Error::FILE_ERROR_FAILED;
base::Optional<std::vector<mojom::DirectoryEntryPtr>> directory_contents;
handled = directory->Read(&error, &directory_contents);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
ASSERT_TRUE(directory_contents.has_value());
// Expected contents of the directory.
std::map<std::string, mojom::FsFileType> expected_contents;
expected_contents["my_file1"] = mojom::FsFileType::REGULAR_FILE;
expected_contents["my_file2"] = mojom::FsFileType::REGULAR_FILE;
expected_contents["my_file3"] = mojom::FsFileType::REGULAR_FILE;
expected_contents["my_dir"] = mojom::FsFileType::DIRECTORY;
// Note: We don't expose ".." or ".".
EXPECT_EQ(expected_contents.size(), directory_contents->size());
for (size_t i = 0; i < directory_contents->size(); i++) {
auto& item = directory_contents.value()[i];
ASSERT_TRUE(item);
auto it = expected_contents.find(item->name.AsUTF8Unsafe());
ASSERT_TRUE(it != expected_contents.end());
EXPECT_EQ(it->second, item->type);
expected_contents.erase(it);
}
}
// TODO(vtl): Properly test OpenFile() and OpenDirectory() (including flags).
TEST_F(DirectoryImplTest, BasicRenameDelete) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
// Create my_file.
error = base::File::Error::FILE_ERROR_FAILED;
bool handled =
directory->OpenFile("my_file", mojo::NullReceiver(),
mojom::kFlagWrite | mojom::kFlagCreate, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
// Opening my_file should succeed.
error = base::File::Error::FILE_ERROR_FAILED;
handled = directory->OpenFile("my_file", mojo::NullReceiver(),
mojom::kFlagRead | mojom::kFlagOpen, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
// Rename my_file to my_new_file.
handled = directory->Rename("my_file", "my_new_file", &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
// Opening my_file should fail.
error = base::File::Error::FILE_ERROR_FAILED;
handled = directory->OpenFile("my_file", mojo::NullReceiver(),
mojom::kFlagRead | mojom::kFlagOpen, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_ERROR_NOT_FOUND, error);
// Opening my_new_file should succeed.
error = base::File::Error::FILE_ERROR_FAILED;
handled = directory->OpenFile("my_new_file", mojo::NullReceiver(),
mojom::kFlagRead | mojom::kFlagOpen, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
// Delete my_new_file (no flags).
handled = directory->Delete("my_new_file", 0, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
// Opening my_new_file should fail.
error = base::File::Error::FILE_ERROR_FAILED;
handled = directory->OpenFile("my_new_file", mojo::NullReceiver(),
mojom::kFlagRead | mojom::kFlagOpen, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_ERROR_NOT_FOUND, error);
}
TEST_F(DirectoryImplTest, CantOpenDirectoriesAsFiles) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
{
// Create a directory called 'my_file'
mojo::Remote<mojom::Directory> my_file_directory;
error = base::File::Error::FILE_ERROR_FAILED;
bool handled = directory->OpenDirectory(
"my_file", my_file_directory.BindNewPipeAndPassReceiver(),
mojom::kFlagRead | mojom::kFlagWrite | mojom::kFlagCreate, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
}
{
// Attempt to open that directory as a file. This must fail!
mojo::Remote<mojom::File> file;
error = base::File::Error::FILE_ERROR_FAILED;
bool handled =
directory->OpenFile("my_file", file.BindNewPipeAndPassReceiver(),
mojom::kFlagRead | mojom::kFlagOpen, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_ERROR_NOT_A_FILE, error);
}
}
TEST_F(DirectoryImplTest, Clone) {
mojo::Remote<mojom::Directory> clone_one;
mojo::Remote<mojom::Directory> clone_two;
base::File::Error error;
{
mojo::Remote<mojom::Directory> directory = CreateTempDir();
directory->Clone(clone_one.BindNewPipeAndPassReceiver());
directory->Clone(clone_two.BindNewPipeAndPassReceiver());
// Original temporary directory goes out of scope here; shouldn't be
// deleted since it has clones.
}
std::vector<uint8_t> data(kData, kData + strlen(kData));
{
bool handled = clone_one->WriteFile("data", data, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
}
{
std::vector<uint8_t> file_contents;
bool handled = clone_two->ReadEntireFile("data", &error, &file_contents);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
EXPECT_EQ(data, file_contents);
}
}
TEST_F(DirectoryImplTest, WriteFileReadFile) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
std::vector<uint8_t> data(kData, kData + strlen(kData));
{
bool handled = directory->WriteFile("data", data, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
}
{
std::vector<uint8_t> file_contents;
bool handled = directory->ReadEntireFile("data", &error, &file_contents);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
EXPECT_EQ(data, file_contents);
}
}
TEST_F(DirectoryImplTest, ReadEmptyFileIsNotFoundError) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
{
std::vector<uint8_t> file_contents;
bool handled =
directory->ReadEntireFile("doesnt_exist", &error, &file_contents);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_ERROR_NOT_FOUND, error);
}
}
TEST_F(DirectoryImplTest, CantReadEntireFileOnADirectory) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
// Create a directory
{
mojo::Remote<mojom::Directory> my_file_directory;
error = base::File::Error::FILE_ERROR_FAILED;
bool handled = directory->OpenDirectory(
"my_dir", my_file_directory.BindNewPipeAndPassReceiver(),
mojom::kFlagRead | mojom::kFlagWrite | mojom::kFlagCreate, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
}
// Try to read it as a file
{
std::vector<uint8_t> file_contents;
bool handled = directory->ReadEntireFile("my_dir", &error, &file_contents);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_ERROR_NOT_A_FILE, error);
}
}
TEST_F(DirectoryImplTest, CantWriteFileOnADirectory) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
// Create a directory
{
mojo::Remote<mojom::Directory> my_file_directory;
error = base::File::Error::FILE_ERROR_FAILED;
bool handled = directory->OpenDirectory(
"my_dir", my_file_directory.BindNewPipeAndPassReceiver(),
mojom::kFlagRead | mojom::kFlagWrite | mojom::kFlagCreate, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
}
{
std::vector<uint8_t> data(kData, kData + strlen(kData));
bool handled = directory->WriteFile("my_dir", data, &error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_ERROR_NOT_A_FILE, error);
}
}
TEST_F(DirectoryImplTest, Flush) {
mojo::Remote<mojom::Directory> directory = CreateTempDir();
base::File::Error error;
{
bool handled = directory->Flush(&error);
ASSERT_TRUE(handled);
EXPECT_EQ(base::File::Error::FILE_OK, error);
}
}
} // namespace
} // namespace filesystem
|
botandrose/adva_cms
|
test/webrat/lib/webrat/sinatra.rb
|
<reponame>botandrose/adva_cms
require 'webrat/rack'
require 'sinatra'
require 'sinatra/test'
class Sinatra::Application
# Override this to prevent Sinatra from barfing on the options passed from RSpec
def self.load_default_options_from_command_line!
end
end
disable :run
disable :reload
module Webrat
class SinatraSession < RackSession #:nodoc:
include Sinatra::Test
attr_reader :request, :response
%w(get head post put delete).each do |verb|
alias_method "orig_#{verb}", verb
define_method(verb) do |*args| # (path, data, headers = nil)
path, data, headers = *args
data = data.inject({}) {|data, (key,value)| data[key] = Rack::Utils.unescape(value); data }
params = data.merge(:env => headers || {})
self.__send__("orig_#{verb}", path, params)
end
end
end
end
|
noahzhy/cpp_2018_fall
|
hw7-2/message_book.h
|
#ifndef __message_book__
#define __message_book__
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
class MessageBook {
public:
MessageBook();
~MessageBook();
void AddMessage(int number, const string& message);
void DeleteMessage(int number);
vector<int> GetNumbers() const;
const string& GetMessage(int number) const;
private:
map<int, string> messages_;
};
#endif
|
CSNW/d3.compose
|
src/helpers/get-unique-values.js
|
<gh_stars>100-1000
import isSeriesData from './is-series-data';
export default function getUniqueValues(data, fn, compare) {
if (!isSeriesData(data)) {
return data.map(fn);
}
var values = data.reduce(function(memo, series) {
var unique = series.values
.map(fn)
.filter(function(value) { return memo.indexOf(value) < 0; });
return memo.concat(unique);
}, []);
var sorted = values.sort(compare);
return sorted;
}
|
chris-twiner/aalto-xml
|
src/main/java/com/fasterxml/aalto/in/MergedStream.java
|
<filename>src/main/java/com/fasterxml/aalto/in/MergedStream.java
package com.fasterxml.aalto.in;
import java.io.*;
/**
* Simple {@link InputStream} implementation that is used to "unwind" some
* data previously read from an input stream; so that as long as some of
* that data remains, it's returned; but as long as it's read, we'll
* just use data from the underlying original stream.
* This is similar to {@link java.io.PushbackInputStream}, but here there's
* only one implicit pushback, when instance is constructed.
*/
public final class MergedStream
extends InputStream
{
final ReaderConfig mConfig;
final InputStream mIn;
byte[] mData;
int mPtr;
final int mEnd;
public MergedStream(ReaderConfig cfg,
InputStream in, byte[] buf, int start, int end)
{
mConfig = cfg;
mIn = in;
mData = buf;
mPtr = start;
mEnd = end;
}
public int available()
throws IOException
{
if (mData != null) {
return mEnd - mPtr;
}
return mIn.available();
}
public void close()
throws IOException
{
freeBuffers();
mIn.close();
}
public void mark(int readlimit)
{
if (mData == null) {
mIn.mark(readlimit);
}
}
public boolean markSupported()
{
// Only supports marks past the initial rewindable section...
return (mData == null) && mIn.markSupported();
}
public int read()
throws IOException
{
if (mData != null) {
int c = mData[mPtr++] & 0xFF;
if (mPtr >= mEnd) {
freeBuffers();
}
return c;
}
return mIn.read();
}
public int read(byte[] b)
throws IOException
{
return read(b, 0, b.length);
}
public int read(byte[] b, int off, int len)
throws IOException
{
if (mData != null) {
int avail = mEnd - mPtr;
if (len > avail) {
len = avail;
}
System.arraycopy(mData, mPtr, b, off, len);
mPtr += len;
if (mPtr >= mEnd) {
freeBuffers();
}
return len;
}
return mIn.read(b, off, len);
}
public void reset()
throws IOException
{
if (mData == null) {
mIn.reset();
}
}
public long skip(long n)
throws IOException
{
long count = 0L;
if (mData != null) {
int amount = mEnd - mPtr;
if (amount > n) { // all in pushed back segment?
mPtr += (int) n;
return n;
}
freeBuffers();
count += amount;
n -= amount;
}
if (n > 0) {
count += mIn.skip(n);
}
return count;
}
/*
/////////////////////////////////////////
// Internal methods
/////////////////////////////////////////
*/
private void freeBuffers()
{
if (mData != null) {
byte[] data = mData;
mData = null;
if (mConfig != null) {
mConfig.freeFullBBuffer(data);
}
}
}
}
|
tuhrig/functional-interpreter
|
src/de/tuhrig/thofu/Interpreter.java
|
<filename>src/de/tuhrig/thofu/Interpreter.java
package de.tuhrig.thofu;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import de.tuhrig.thofu.interfaces.EnvironmentListener;
import de.tuhrig.thofu.interfaces.HistoryListener;
import de.tuhrig.thofu.interfaces.IInterpreter;
import de.tuhrig.thofu.interfaces.IJava;
import de.tuhrig.thofu.interfaces.Parser;
import de.tuhrig.thofu.java.LJClass;
import de.tuhrig.thofu.java.LJObject;
import de.tuhrig.thofu.java.LJava;
import de.tuhrig.thofu.parser.DefaultParser;
import de.tuhrig.thofu.types.LBoolean;
import de.tuhrig.thofu.types.LException;
import de.tuhrig.thofu.types.LLambda;
import de.tuhrig.thofu.types.LList;
import de.tuhrig.thofu.types.LNull;
import de.tuhrig.thofu.types.LObject;
import de.tuhrig.thofu.types.LOperation;
import de.tuhrig.thofu.types.LSymbol;
/**
* The interpreter class itself. This class...
*
* - ...adds all build-in operations and variables
* - ...holds the root environment
* - ...can take a command and evaluate it
*
* @author <NAME> (tuhrig.de)
*/
public class Interpreter implements IInterpreter, IJava {
private static Logger logger = Logger.getLogger(Interpreter.class);
private final Environment root = new Environment(null);
private final List<EnvironmentListener> environmentListeners = new ArrayList<>();
private final List<HistoryListener> historyListeners = new ArrayList<>();
private Parser parser = new DefaultParser();
private StringBuilder builder = new StringBuilder();
/**
* Creates a new interpreter. Also, all built-in operations and
* variables will be created.
*/
public Interpreter() {
/**
* Build-in operations
*/
logger.info("adding operations");
// (load file)
root.put(LSymbol.get("load"), new LOperation("load") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
String path = ((LList) tokens).get(0).toString();
final File file = new File(path);
try {
String content = new Util().read(file);
String commands = parser.format(content);
List<LObject> objects = parser.parseAll(commands);
LObject result = LNull.NULL;
for(LObject object: objects) {
result = execute(object, environment);
}
return result;
}
catch (IOException e) {
throw new LException("[file not found] - " + path + " can't be resolved", e);
}
}
});
// (resource name)
root.put(LSymbol.get("resource"), new LOperation("resource") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
String rs = ((LList) tokens).get(0).toString();
String content = new Util().read(getClass(), rs);
String commands = parser.format(content.toString());
List<LObject> objects = parser.parseAll(commands);
LObject result = LNull.NULL;
for(LObject object: objects) {
result = execute(object, environment);
}
return result;
}
});
// (instance? object class)
root.put(LSymbol.get("instance?"), new LOperation("instance?") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList list = (LList) tokens;
LObject first = list.get(0).run(environment, tokens);
LJClass second = (LJClass) list.get(1).run(environment, tokens);
return LBoolean.get(((Class<?>) second.getJObject()).isInstance(first));
}
});
// (try (expression) (exception (expression)))
root.put(LSymbol.get("try"), new LOperation("try") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList list = (LList) tokens;
LObject first = list.get(0);
LObject second = list.get(1);
try {
return first.run(environment, first);
}
catch(Exception e) {
logger.info("Caught exception", e);
LList tmp = (LList) second;
LObject name = tmp.getFirst();
LObject expression = tmp.getRest();
environment.put(LSymbol.get(name), new LJObject(e));
return expression.run(environment, expression);
}
}
});
// (begin (expression1) (expression2) ...)
root.put(LSymbol.get("begin"), new LOperation("begin") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject result = LNull.NULL;
LList list = (LList) tokens;
for (LObject object: list) {
result = object.run(environment, tokens);
}
return result;
}
});
// (let (parameters) body)
root.put(LSymbol.get("let"), new LOperation("let") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList parameters = (LList) ((LList) tokens).getFirst();
LObject body = ((LList) tokens).getRest();
Environment innerEnvironment = new Environment(environment);
for (LObject tmp: parameters) {
LList parameter = (LList) tmp;
LSymbol symbol = LSymbol.get(parameter.get(0));
LObject object = parameter.get(1).run(innerEnvironment, tokens);
innerEnvironment.put(symbol, object);
}
return body.run(innerEnvironment, tokens);
}
});
// (+ token..)
root.put(LSymbol.get("+"), new LOperation("+") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject n = null;
for (LObject token : (LList) tokens) {
if (n == null) {
n = token.run(environment, token);
}
else {
n = n.sum(token.run(environment, token));
}
}
return n;
}
});
// (- token..)
root.put(LSymbol.get("-"), new LOperation("-") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject n = null;
for (LObject token : (LList) tokens) {
if (n == null) {
n = token.run(environment, token);
}
else {
n = n.subtract(token.run(environment, token));
}
}
return n;
}
});
// (* token..)
root.put(LSymbol.get("*"), new LOperation("*") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject n = null;
for (LObject token : (LList) tokens) {
if (n == null) {
n = token.run(environment, token);
}
else {
n = n.multiply(token.run(environment, token));
}
}
return n;
}
});
// (/ token..)
root.put(LSymbol.get("/"), new LOperation("/") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject n = null;
for (LObject token : (LList) tokens) {
if (n == null) {
n = token.run(environment, token);
}
else {
n = n.divide(token.run(environment, token));
}
}
return n;
}
});
// (define name expression)
root.put(LSymbol.get("define"), new LOperation("define") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject name = ((LList) tokens).get(0);
LObject expression = LNull.NULL;
// We have the second version of define, if name is a list.
// e.g.: (define (dec2 (n)) (- n 1))
//
// If so, we create a common define-lambda list. So we have just implemented a
// short-cut and the actual definition of a lambda still resists in a single function.
if (name instanceof List) {
LList list = (LList) name;
name = list.get(0);
if(name instanceof LOperation) {
name = ((LOperation) name).getName();
}
LList parameters;
// enables two ways of specifing the parameters:
// (1) (define (dec2 (n)) (- n 1))
// (2) (define (dec2 n) (- n 1))
if (list.get(1) instanceof LList) {
parameters = (LList) list.get(1);
}
else {
parameters = new LList();
parameters.addAll(list.subList(1, list.size()));
}
LList body = (LList) ((LList) tokens).getRest();
LList lambdaList = new LList();
lambdaList.add(LSymbol.get("lambda"));
lambdaList.add(parameters);
for (int i = 0; i < body.size(); i++) {
lambdaList.add(body.get(i));
}
expression = lambdaList.run(environment, lambdaList);
}
else {
LObject second = ((LList) tokens).get(1);
if(second instanceof LOperation)
expression = second; //.run(environment, tokens);
else
expression = second.run(environment, tokens);
}
// if we have a lambda (not an other variable) we can name it
if (expression instanceof LLambda)
((LLambda) expression).setName(name.toString());
environment.put(LSymbol.get(name), expression);
callEnvironmentListeners();
return expression;
}
});
// (set! value)
root.put(LSymbol.get("set!"), new LOperation("set!") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject name = ((LList) tokens).get(0);
if (name instanceof List) {
name = ((LList) name).get(0);
}
if (!environment.contains(LSymbol.get(name)))
throw new LException(name + " is undefined");
LObject second = ((LList) tokens).get(1);
second = second.run(environment, tokens);
environment.set(LSymbol.get(name), second);
return second;
}
});
// (print value)
root.put(LSymbol.get("print"), new LOperation("print") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject object = ((LList) tokens).get(0);
if(!(object instanceof LOperation))
object = object.run(environment, tokens);
builder.append(object.toString());
return object;
}
});
// (lambda (parameters) body)
root.put(LSymbol.get("lambda"), new LOperation("lambda") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList parameters = (LList) ((LList) tokens).getFirst();
LList body = (LList) ((LList) tokens).getRest();
return new LLambda(parameters, body, environment);
}
});
// (if condition ifExpression elseExpression)
root.put(LSymbol.get("if"), new LOperation("if") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LObject condition = ((LList) tokens).get(0);
LObject result = condition.run(environment, tokens);
if (result.equals(LBoolean.TRUE)) {
LObject ifExpression = ((LList) tokens).get(1);
return ifExpression.run(environment, tokens);
}
else {
LObject elseExpression = ((LList) tokens).get(2);
return elseExpression.run(environment, tokens);
}
}
});
// (for (define i 0) (< i 5) (set! i (+ i 1)) (print i))
root.put(LSymbol.get("for"), new LOperation("for") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList define = (LList) ((LList) tokens).get(0);
LList condition = (LList) ((LList) tokens).get(1);
LList increment = (LList) ((LList) tokens).get(2);
LList block = (LList) ((LList) tokens).get(3);
Environment innerEnvironment = new Environment(environment);
define.evaluate(innerEnvironment, tokens);
LObject result = LNull.NULL;
while(condition.evaluate(innerEnvironment, tokens) == LBoolean.TRUE) {
result = block.evaluate(innerEnvironment, tokens);
increment.evaluate(innerEnvironment, tokens);
}
return result;
}
});
// (while (true) (print i))
root.put(LSymbol.get("while"), new LOperation("while") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList condition = (LList) ((LList) tokens).get(0);
LList block = (LList) ((LList) tokens).get(1);
LObject result = LNull.NULL;
while(condition.evaluate(environment, tokens) == LBoolean.TRUE) {
result = block.evaluate(environment, tokens);
}
return result;
}
});
// (do (true) (print i))
root.put(LSymbol.get("do"), new LOperation("do") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList condition = (LList) ((LList) tokens).get(0);
LList block = (LList) ((LList) tokens).get(1);
LObject result = LNull.NULL;
do {
result = block.evaluate(environment, tokens);
}while(condition.evaluate(environment, tokens) == LBoolean.TRUE);
return result;
}
});
/**
* Java functions
*/
// (import "name")
root.put(LSymbol.get("import"), new LOperation("import") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList list = (LList) tokens;
for (LObject object: list) {
String tmp = object.toString();
System.out.println("import " + tmp);
if(tmp.endsWith("*")) {
System.out.println("package");
LJava.importPackage(tmp.substring(0, tmp.length()-2));
}
else {
System.out.println("class");
LJava.importClass(tmp);
}
}
return LBoolean.TRUE;
}
});
// (interface Interface.class object)
root.put(LSymbol.get("interface"), new LOperation("interface") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList list = (LList) tokens;
LObject c = list.get(0).run(environment, tokens);
LLambda lambda = (LLambda) list.get(1).run(environment, tokens);
LJClass cl = (LJClass) c.run(environment, tokens);
return LJava.createInterface((Class<?>) cl.getJObject(), lambda, environment);
}
});
// (class Class.class object)
root.put(LSymbol.get("class"), new LOperation("class") {
@Override
public LObject evaluate(Environment environment, LObject tokens) {
LList list = (LList) tokens;
LObject c = list.get(0).run(environment, tokens);
LLambda lambda = (LLambda) list.get(1).run(environment, tokens);
LJClass cl = (LJClass) c.run(environment, tokens);
return LJava.createClass((Class<?>) cl.getJObject(), lambda, environment);
}
});
/**
* Build-in lambdas from initiation file (init.txt)
*/
logger.info("loading initiation file");
execute("(resource \"init.txt\")");
// TODO
//just for the moment a simple implementation
//this.parser = new ProceduralParser();
}
/*
* (non-Javadoc)
* @see de.tuhrig.thofu.interfaces.IInterpreter#execute(java.lang.String)
*/
@Override
public String execute(String expression) {
try {
parser.validate(expression);
LList tokens = parser.parse(expression);
LObject result = execute(tokens, root);
return result.toString();
}
catch (LException e) {
logger.warn(e.getMessage(), e);
return e.getMessage();
}
catch (Exception e) {
logger.error("[interpreter exception] - " + e.getMessage(), e);
return "[interpreter exception] - " + e.getMessage();
}
}
/*
* (non-Javadoc)
* @see de.tuhrig.thofu.interfaces.IInterpreter#execute(de.tuhrig.thofu.types.LObject)
*/
@Override
public String execute(LObject tokens) {
try {
LObject result = execute(tokens, root);
return result.toString();
}
catch (LException e) {
logger.warn(e.getMessage(), e);
return e.getMessage();
}
catch (Exception e) {
logger.error("[interpreter exception] - " + e.getMessage(), e);
return "[interpreter exception] - " + e.getMessage();
}
}
private LObject execute(LObject tokens, Environment environment) {
// This method is an experiment, it doesn't work. Therefore,
// it's commented our. It can be commented in and tested with
// the JUnit tests.
// tokens = parser.replace(tokens, environment);
Date before = new Date();
LObject result = tokens.run(environment, tokens);
Date after = new Date();
if(tokens instanceof LList)
archive((LList) tokens, before, after);
return result;
}
/*
* (non-Javadoc)
* @see de.tuhrig.thofu.interfaces.IInterpreter#addEnvironmentListener(de.tuhrig.thofu.interfaces.EnvironmentListener)
*/
@Override
public void addEnvironmentListener(EnvironmentListener listener) {
this.environmentListeners.add(listener);
}
/*
* (non-Javadoc)
* @see de.tuhrig.thofu.interfaces.IInterpreter#addHistoryListener(de.tuhrig.thofu.interfaces.HistoryListener)
*/
@Override
public void addHistoryListener(HistoryListener listener) {
this.historyListeners.add(listener);
}
/*
* (non-Javadoc)
* @see de.tuhrig.thofu.interfaces.IInterpreter#getEnvironment()
*/
@Override
public Environment getEnvironment() {
return root;
}
/**
* Calls all registered environment listeners.
*/
private void callEnvironmentListeners() {
for (EnvironmentListener listener : environmentListeners)
listener.update(root);
}
/**
* Calls all registered history listeners.
*/
private void archive(LList tokens, Date started, Date ended) {
for (HistoryListener listener : historyListeners)
listener.update(tokens, started, ended);
}
/*
* (non-Javadoc)
* @see de.tuhrig.thofu.interfaces.IInterpreter#setParser(de.tuhrig.thofu.interfaces.Parser)
*/
@Override
public void setParser(Parser parser) {
this.parser = parser;
}
@Override
public Parser getParser() {
return parser;
}
@Override
public void setStringBuilder(StringBuilder builder) {
this.builder = builder;
}
@Override
public StringBuilder getStringBuilder() {
return builder;
}
}
|
mattermost/awat
|
test/e2e/users_test.go
|
<reponame>mattermost/awat
// Copyright (c) 2020-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
//+build e2e
package e2e
var correctSlackUsers map[string]string = map[string]string{
"<EMAIL>": "j",
"<EMAIL>": "james",
"<EMAIL>": "l<PASSWORD>say2",
"<EMAIL>": "lindsay",
"<EMAIL>": "l<PASSWORD>say3",
"<EMAIL>": "lindsay.b",
"<EMAIL>": "linds.b",
"<EMAIL>": "linds.abc",
"<EMAIL>": "jason-guest",
"<EMAIL>": "lindsay.test",
"<EMAIL>": "guest3",
"<EMAIL>": "linds.123",
"<EMAIL>": "jason2",
"<EMAIL>": "mike",
"<EMAIL>": "asaadmahmood",
"<EMAIL>": "asaad",
"<EMAIL>": "jason_7",
"<EMAIL>": "jason_3",
"<EMAIL>": "jason_15",
"<EMAIL>": "jason_2",
"<EMAIL>": "jason_8",
"<EMAIL>": "jason_13",
"<EMAIL>": "jason_12",
"<EMAIL>": "jason_14",
"<EMAIL>o.ooo": "jason_10",
"<EMAIL>": "jason_5",
"<EMAIL>": "jason_16",
"<EMAIL>": "jason_4",
"<EMAIL>": "jason_11",
"<EMAIL>": "jason_6",
"<EMAIL>": "jason_17",
"<EMAIL>": "jason_24",
"<EMAIL>": "blaisjc",
"<EMAIL>": "michaelandrewgamble",
"<EMAIL>": "kwiersgalla",
"<EMAIL>": "katie",
"<EMAIL>": "mike_test3",
"<EMAIL>": "katie_test2",
"<EMAIL>": "christopher_slack",
"<EMAIL>": "mike_test7",
"<EMAIL>": "mike_test20",
"<EMAIL>": "mike_guest",
"<EMAIL>": "mike_guest1",
"<EMAIL>": "mike529",
"<EMAIL>": "mike974",
"<EMAIL>": "mike670",
"<EMAIL>": "mike_test9",
"<EMAIL>": "mike_fulluser",
"<EMAIL>": "mike_guestuser",
}
var correctMattermostUsers map[string]string = map[string]string{
"<EMAIL>": "aaron.medina",
"user-<EMAIL>": "aaron.peterson",
"<EMAIL>": "anne.stone",
"appsbot@localhost": "appsbot",
"<EMAIL>": "ashley.berry",
"channelexport@localhost": "channelexport",
"<EMAIL>": "christina.wilson",
"<EMAIL>": "craig.reed",
"<EMAIL>": "diana.wells",
"<EMAIL>": "emily.meyer",
"<EMAIL>": "guest",
"<EMAIL>": "jack.wheeler",
"<EMAIL>": "karen.austin",
"mattermost-advisor@localhost": "mattermost-advisor",
"playbook@localhost": "playbook",
"<EMAIL>": "robert.ward",
"<EMAIL>": "samuel.palmer",
"<EMAIL>": "samuel.tucker",
"surveybot@localhost": "surveybot",
"<EMAIL>": "sysadmin",
"<EMAIL>": "user-1",
}
|
aibrahimRS/geowave
|
extensions/cli/redis-embed/src/main/java/org/locationtech/geowave/datastore/redis/cli/RunRedisServerOptions.java
|
<gh_stars>0
/**
* Copyright (c) 2013-2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.datastore.redis.cli;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.Parameter;
import redis.embedded.RedisExecProvider;
import redis.embedded.RedisServer;
import redis.embedded.RedisServerBuilder;
public class RunRedisServerOptions {
private static final Logger LOGGER = LoggerFactory.getLogger(RunRedisServerOptions.class);
@Parameter(
names = {"--port", "-p"},
description = "Select the port for Redis to listen on (default is port 6379)")
private Integer port = 6379;
@Parameter(
names = {"--directory", "-d"},
description = "The directory to use for Redis. If set, the data will be persisted and durable. If none, it will use a temp directory and delete when complete")
private String directory = null;
@Parameter(
names = {"--maxMemory", "-m"},
description = "The maximum memory to use (in the form such as 512M)")
private String memory = "512M";
@Parameter(
names = {"--setting", "-s"},
description = "A setting to apply to Redis in the form of <name>=<value>")
private List<String> settings = new ArrayList<>();
public RedisServer getServer() throws IOException {
final RedisServerBuilder bldr = RedisServer.builder().port(port).setting("bind 127.0.0.1"); // secure
boolean appendOnlySet = false;
for (final String s : settings) {
final String[] kv = s.split("=");
if (kv.length == 2) {
if (kv[0].equalsIgnoreCase("appendonly")) {
appendOnlySet = true;
}
bldr.setting(kv[0] + " " + kv[1]);
}
}
if ((directory != null) && (directory.trim().length() > 0)) {
final File f = RedisExecProvider.defaultProvider().get();
final File directoryFile = new File(directory);
if (!directoryFile.exists() && !directoryFile.mkdirs()) {
LOGGER.warn("Unable to create directory '" + directory + "'");
}
final File newExecFile = new File(directoryFile, f.getName());
FileUtils.moveFile(f, newExecFile);
if (!appendOnlySet) {
bldr.setting("appendonly yes");
bldr.setting("appendfsync everysec");
}
}
bldr.setting("maxmemory " + memory.trim());
return bldr.build();
}
}
|
tstephen/DTRules
|
dtrules-engine/src/main/java/com/dtrules/mapping/XMLTag.java
|
/**
* Copyright 2004-2011 DTRules.com, Inc.
*
* See http://DTRules.com for updates and documentation for the DTRules Rules Engine
*
* 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 com.dtrules.mapping;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This object represents an XML tag, but I avoid serializaiton under
* the assumption that any conversion to a string would have been
* undone by a conversion from a string back to the object anyway. I
* also use the same structure for both tagged data and a tag holding
* tags.
*
* @author <NAME>
* Sep 24, 2007
*
*/
public class XMLTag implements XMLNode {
private String tag;
private HashMap<String, Object> _attribs = null;
private ArrayList<XMLNode> _tags = null;
private Object body = null;
private XMLNode parent;
public XMLTag(String tag, XMLNode parent){
if(tag==null)tag = "root";
this.tag = tag;
this.parent = parent;
}
public String toString(){
String r = "<"+tag;
if(_attribs != null) for(String key : _attribs.keySet()){
r +=" "+key +"='"+_attribs.get(key).toString()+"'";
}
if(body != null){
String b = body.toString();
if(b.length()>20){
b = b.substring(0,18)+"...";
}
r +=">"+b+"</"+tag+">";
}else if( _tags == null || _tags.size()==0 ){
r += "/>";
}else{
r += ">";
}
return r;
}
@Override
public int childCount() {
// TODO Auto-generated method stub
if(_tags == null) return 0;
return _tags.size();
}
/* (non-Javadoc)
* @see com.dtrules.mapping.XMLNode#addChild(com.dtrules.mapping.XMLNode)
*/
@Override
public void addChild(XMLNode node) {
if(_tags == null){
_tags = new ArrayList<XMLNode>(5);
}
_tags.add(node);
}
/* (non-Javadoc)
* @see com.dtrules.mapping.XMLNode#remove(com.dtrules.mapping.XMLNode)
*/
@Override
public void remove(XMLNode node){
if(_tags!= null){
_tags.remove(node);
}
}
/**
* @return the tag
*/
public String getTag() {
return tag;
}
/**
* @param tag the tag to set
*/
public void setTag(String tag) {
this.tag = tag;
}
/**
* @return the tags
*/
public ArrayList<XMLNode> getTags() {
return _tags;
}
/**
* @param tags the tags to set
*/
public void setTags(ArrayList<XMLNode> tags) {
this._tags = tags;
}
/**
* @return the body
*/
public Object getBody() {
return body;
}
/**
* @param body the body to set
*/
public void setBody(Object body) {
this.body = body;
}
/**
* @return the parent
*/
public XMLNode getParent() {
return parent;
}
/**
* @param parent the parent to set
*/
public void setParent(XMLTag parent) {
if(this.parent != null){
this.parent.remove(this);
}
this.parent = parent;
}
public Type type(){ return Type.TAG; }
@Override
public Object getAttrib(String key) {
if (_attribs == null) return null;
return _attribs.get(key);
}
@Override
public void setAttrib(String key, Object value) {
if(_attribs == null){
_attribs = new HashMap<String,Object>(2,1.0f);
}
_attribs.put(key,value);
}
public HashMap<String,Object> getAttribs(){
if(_attribs == null){
_attribs = new HashMap<String,Object>(2,1.0f);
}
return _attribs;
}
@Override
public void clearRef() {
if(_attribs != null && _attribs.size()==0){
_attribs = null;
}
if(_tags !=null && _tags.size() == 0){
_tags = null;
}
}
}
|
alexgo1/fuse-med-ml
|
fuse/eval/metrics/detection/metrics_detection_common.py
|
from functools import partial
from typing import Dict, List, Optional
from fuse.eval.metrics.libs.instance_segmentation import MetricsInstanceSegmentaion
import numpy as np
from fuse.eval.metrics.metrics_common import MetricPerSampleDefault
def calculate_precision(metric_result : List[float], threshold : float = 0.5) -> float:
"""
Calculates average precision under threshold for detection
:param metric_result: matrix of similarity score between prediction and target , (axis 0 is number of annotations, axis 1 is number of targets)
:param threshold: a number which determines the metric value of which above we consider for detection
it's purpouse to ignore misdetected instances , 0.5 is the common threshold on iou metric
:return: average result over images
"""
per_instane_results = []
for res in metric_result :
metric_maximum = res.max(axis = 0)
metric_maximum = metric_maximum[metric_maximum > threshold]
precision = float(len(metric_maximum))/float( res.shape[0])
per_instane_results.append(precision)
result = np.mean(per_instane_results)
return result
def calculate_recall(metric_result : List[float], threshold : float = 0.5) -> float:
"""
Calculates average recall under threshold for detection
:param metric_result: matrix of similarity score between prediction and target , (axis 0 is number of annotations, axis 1 is number of targets)
:param threshold: a number which determines the metric value of which above we consider for detection
it's purpouse to ignore misdetected instances , 0.5 is the common threshold on iou metric
:return: average result over images
"""
per_instane_results = []
for res in metric_result :
metric_maximum = res.max(axis = 0)
metric_maximum = metric_maximum[metric_maximum > threshold]
recall = float(len(metric_maximum))/float( res.shape[1])
per_instane_results.append(recall)
result = np.mean(per_instane_results)
return result
class MetricDetectionPrecision(MetricPerSampleDefault):
"""
Compute detection precision based on IOU Jaccard score for binary instance segmentation input
"""
def __init__(self, pred: str, target: str, segmentation_pred_type: str, segmentation_target_type: str,height : str ,width: str ,threshold :Optional[float] =0.5, **kwargs):
"""
See super class for the missing params, to read more about the segmentation types go to class MetricsInstanceSegmentaion
:param segmentation_pred_type: input pred format - pixel_map , uncompressed_RLE , compressed_RLE , polygon , bbox
:param segmentation_target_type: input target format - pixel_map , uncompressed_RLE , compressed_RLE , polygon , bbox
:param height: height of the original image ( y axis)
:param width: width of the original image ( x axis)
:param threshold: a number which determines the metric value of which above we consider for detection
it's purpouse to ignore misdetected instances , 0.5 is the common threshold on iou metric
"""
iou = partial(MetricsInstanceSegmentaion.iou_jaccard, segmentation_pred_type=segmentation_pred_type, segmentation_target_type=segmentation_target_type)
precision = partial(calculate_precision, threshold=threshold)
super().__init__(pred=pred, target=target, height=height ,width=width , metric_per_sample_func=iou, result_aggregate_func = precision , **kwargs)
class MetricDetectionRecall(MetricPerSampleDefault):
"""
Compute detection recall based on IOU Jaccard score for binary instance segmentation input
"""
def __init__(self, pred: str, target: str, segmentation_pred_type: str, segmentation_target_type: str,height : str ,width: str , threshold :Optional[float] =0.5, **kwargs):
"""
See super class for the missing params, to read more about the segmentation types go to class MetricsInstanceSegmentaion
:param segmentation_pred_type: input pred format - pixel_map , uncompressed_RLE , compressed_RLE , polygon , bbox
:param segmentation_target_type: input target format - pixel_map , uncompressed_RLE , compressed_RLE , polygon , bbox
:param height: height of the original image ( y axis)
:param width: width of the original image ( x axis)
:param threshold: a number which determines the metric value of which above we consider for detection
it's purpouse to ignore misdetected instances , 0.5 is the common threshold on iou metric
"""
iou = partial(MetricsInstanceSegmentaion.iou_jaccard, segmentation_pred_type=segmentation_pred_type, segmentation_target_type=segmentation_target_type)
recall = partial(calculate_recall, threshold=threshold)
super().__init__(pred=pred, target=target, height=height ,width=width , metric_per_sample_func=iou, result_aggregate_func = recall , **kwargs)
|
kanish671/goalert
|
validation/validate/labelkey_test.go
|
package validate
import "testing"
func TestLabelKey(t *testing.T) {
check := func(valid bool, values ...string) {
for _, val := range values {
t.Run(val, func(t *testing.T) {
err := LabelKey("", val)
if valid && err != nil {
t.Errorf("got %v; want nil", err)
} else if !valid && err == nil {
t.Errorf("got nil; want err")
}
})
}
}
check(true,
"foo/bar", "bin.baz/abc", "0123/abc", "foo-bar/abc",
)
check(false,
"test", "Foo/bar", "-test/ok", "a/b", "foo/ok", "foo'/bar", " ", "", "foo /bar",
"/", "//", "/foo/", "/foo/bar", "foo/",
)
}
|
txiang61-benchmarks/react
|
annotated/com/flowpowered/react/engine/Island.java
|
<gh_stars>0
/*
* This file is part of React, licensed under the MIT License (MIT).
*
* Copyright (c) 2013 Flow Powered <https://flowpowered.com/>
* Original ReactPhysics3D C++ library by <NAME> <http://danielchappuis.ch>
* React is re-licensed with permission from ReactPhysics3D author.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.flowpowered.react.engine;
import units.qual.Dimensionless;
import com.flowpowered.react.body.RigidBody;
import com.flowpowered.react.constraint.Joint;
/**
* An island represent an isolated group of awake bodies that are connected with each other by some constraints (contacts or joints).
*/
public class Island {
private @Dimensionless RigidBody @Dimensionless [] mBodies;
private @Dimensionless ContactManifold @Dimensionless [] mContactManifolds;
private @Dimensionless Joint @Dimensionless [] mJoints;
private @Dimensionless int mNbBodies;
private @Dimensionless int mNbContactManifolds;
private @Dimensionless int mNbJoints;
/**
* Constructs a new island from the maximum number of bodies, the maximum number of contact manifolds and the maximum number of joints.
*
* @param nbMaxBodies The maximum number of bodies
* @param nbMaxContactManifolds The maximum number of contact manifolds
* @param nbMaxJoints The maximum number of joints
*/
public Island(@Dimensionless int nbMaxBodies, @Dimensionless int nbMaxContactManifolds, @Dimensionless int nbMaxJoints) {
mNbBodies = ((@Dimensionless int) (0));
mNbContactManifolds = ((@Dimensionless int) (0));
mNbJoints = ((@Dimensionless int) (0));
mBodies = new @Dimensionless RigidBody @Dimensionless [nbMaxBodies];
mContactManifolds = new @Dimensionless ContactManifold @Dimensionless [nbMaxContactManifolds];
mJoints = new @Dimensionless Joint @Dimensionless [nbMaxJoints];
}
/**
* Adds a body into the island
*
* @param body The body
*/
public void addBody(@Dimensionless Island this, @Dimensionless RigidBody body) {
if (body.isSleeping()) {
throw new @Dimensionless IllegalArgumentException("Body to add is sleeping");
}
mBodies[mNbBodies] = body;
mNbBodies++;
}
/**
* Adds a contact manifold into the island
*
* @param contactManifold The contact manifold
*/
public void addContactManifold(@Dimensionless Island this, @Dimensionless ContactManifold contactManifold) {
mContactManifolds[mNbContactManifolds] = contactManifold;
mNbContactManifolds++;
}
/**
* Adds a joint into the island.
*
* @param joint The joint
*/
public void addJoint(@Dimensionless Island this, @Dimensionless Joint joint) {
mJoints[mNbJoints] = joint;
mNbJoints++;
}
/**
* Returns the number of bodies in the island.
*
* @return The number of bodies
*/
public int getNbBodies(@Dimensionless Island this) {
return mNbBodies;
}
/**
* Returns the number of contact manifolds in the island.
*
* @return The number of contact manifolds
*/
public @Dimensionless int getNbContactManifolds(@Dimensionless Island this) {
return mNbContactManifolds;
}
/**
* Returns the number of joints in the island.
*
* @return The number of joints
*/
public int getNbJoints(@Dimensionless Island this) {
return mNbJoints;
}
/**
* Returns the array of bodies.
*
* @return The array of bodies
*/
public @Dimensionless RigidBody @Dimensionless [] getBodies(@Dimensionless Island this) {
return mBodies;
}
/**
* Returns the array of contact manifolds.
*
* @return The array of contact manifold
*/
public @Dimensionless ContactManifold @Dimensionless [] getContactManifolds(@Dimensionless Island this) {
return mContactManifolds;
}
/**
* Returns the array of joints.
*
* @return The array of joints
*/
public Joint[] getJoints(@Dimensionless Island this) {
return mJoints;
}
}
|
jeffmasty/fullnodej
|
src/main/java/org/fullnodej/data/TxOut.java
|
package org.fullnodej.data;
import java.math.BigDecimal;
import lombok.Data;
@Data
public class TxOut {
/** header hash of local best block including this tx in hex. not mined=empty*/
String bestblock;
int confirmations;
BigDecimal value;
ScriptPubKey scriptPubKey;
int version;
boolean coinbase;
}
|
azhao96/simple-logo
|
src/model/MakeVariable.java
|
<reponame>azhao96/simple-logo
package model;
import java.util.List;
/**
* MakeVariable function to implement Make.
* Created by blakekaplan
*/
public class MakeVariable extends Node {
private static final String MAKE = "MakeVariable ";
private static final int VARIABLE_NAME = 0;
private static final int EXPRESSION = 1;
private String name;
/**
* Updates the entry in the variable dictionary to the new value.
*/
@Override
public double interpret(CommandDictionary commandDict, VariableDictionary varDict) throws ClassNotFoundException {
List<IFunctions> children = getChildren();
String key = children.get(VARIABLE_NAME).toString();
double value = children.get(EXPRESSION).interpret(commandDict, varDict);
varDict.makeVariable(key, value);
return value;
}
/**
* Gets the variable name.
* @return variable name.
*/
public String getName() {
return name;
}
/**
* Sets a variable's name to a new name.
* @param newName: new name for variable.
*/
public void setName(String newName) {
name = newName;
}
/**
* Returns the class name and its children.
*/
@Override
public String toString() {
return MAKE + childrenToString();
}
}
|
zuoyebushiwo/elasticsearch-1.5.0
|
src/test/java/org/xbib/elasticsearch/river/jdbc/util/IndexableObjectTests.java
|
<reponame>zuoyebushiwo/elasticsearch-1.5.0<gh_stars>0
package org.xbib.elasticsearch.river.jdbc.util;
import org.testng.annotations.Test;
import org.xbib.elasticsearch.plugin.jdbc.util.IndexableObject;
import org.xbib.elasticsearch.plugin.jdbc.util.PlainIndexableObject;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
public class IndexableObjectTests {
@Test
public void testIndexableObject() {
PlainIndexableObject a = new PlainIndexableObject();
PlainIndexableObject b = new PlainIndexableObject();
assertEquals(a, b);
}
@Test
public void testPlainIndexableObject() {
IndexableObject a = new PlainIndexableObject()
.index("index")
.type("type")
.id("id");
IndexableObject b = new PlainIndexableObject()
.index("index")
.type("type")
.id("id");
assertEquals(a, b);
}
@Test
public void testNotEqualsPlainIndexableObject() {
IndexableObject a = new PlainIndexableObject()
.index("index1")
.type("type1")
.id("id1");
IndexableObject b = new PlainIndexableObject()
.index("index2")
.type("type2")
.id("id2");
assertNotEquals(a, b);
}
/**
* Issue #487
*/
@Test
public void testHashCodePlainIndexableObject() {
IndexableObject a = new PlainIndexableObject()
.index("my_index")
.type("Employee")
.id("12055T");
IndexableObject b = new PlainIndexableObject()
.index("my_index")
.type("Employee")
.id("120565");
assertNotEquals(a, b);
}
}
|
maryrosecook/codewithisla
|
src/demos/planets.js
|
<filename>src/demos/planets.js
;(function(exports) {
var EnvStore, demoUtils, Isla;
if(typeof module !== 'undefined' && module.exports) { // node
EnvStore = require('../env-store.js').EnvStore;
demoUtils = require('../demo-utils.js').demoUtils;
Isla = require('../../node_modules/isla/src/isla.js').Isla;
} else { // browser
EnvStore = window.EnvStore;
demoUtils = window.demoUtils;
Isla = window.Isla;
}
function Planets(canvasCtx, demoTalker) {
if (canvasCtx == null) {
throw "You must provide a canvas context to draw to.";
}
if (demoTalker == null) {
throw "You must provide a demo talker to communicate with.";
}
if (canvasCtx.fillRect === undefined) {
throw "The variable you passed does not seem to be a canvas context.";
}
var _currentCtx;
var currentCtx = function(inCtx) {
if (inCtx !== undefined) {
_currentCtx = inCtx;
demoTalker.emit("demo:ctx:new", _currentCtx);
} else {
return _currentCtx;
}
};
var _indications = {};
this.indications = function(inIndications) {
if (inIndications !== undefined) {
_indications = inIndications;
} else {
return _indications;
}
};
//////////////////////////////////////!!!!!!!!!!!!!!!!!!!!
// add annotations in _meta to explain what attrs do
///////////////////////////////
setupHelp(demoTalker, this);
// main draw loop
this._draw = function() {
drawBackground(canvasCtx);
if (currentCtx() !== undefined) { // no ctx until sent 1st one by runner
currentCtx(move(currentCtx()));
drawBodies(canvasCtx, currentCtx(), this.indications());
}
};
var isThereAlreadyAStar = function() {
var ctx = currentCtx();
for(var i in ctx) {
if (demoUtils.isIslaType(ctx[i], "star")) {
return true;
}
}
return false;
};
// sets up cb to take latest Isla ctx, process planets and issue update
demoTalker.on(this, "isla:ctx:new", function(ctx) {
try {
var gotStar = isThereAlreadyAStar();
for (var i in ctx) {
if (demoUtils.isIslaType(ctx[i], "planet")) {
ctx[i] = planetDefaults(canvasCtx, ctx[i]);
} else if (demoUtils.isIslaType(ctx[i], "star")) {
ctx[i] = starDefaults(canvasCtx, ctx[i], gotStar);
}
}
currentCtx(ctx);
} catch(e) {
console.log(e.message);
throw e;
}
});
// set draw loop going
var self = this;
this.interval = setInterval(function() {
self._draw();
}, 33);
}
Planets.prototype = {
getTutorSteps: function() {
return STEPS;
},
// stop drawing
end: function() {
clearInterval(this.interval);
},
init: function() {},
intro: function() {
return [
// "sun is a star",
// "a is a planet",
// "b is a planet",
// "c is a planet"
];
}
};
var pf = parseFloat;
var drawBackground = function(canvasCtx) {
canvasCtx.fillStyle = "#000";
canvasCtx.fillRect(0, 0, canvasCtx.canvas.width, canvasCtx.canvas.height);
};
var drawBodies = function(canvasCtx, ctx, indications) {
for (var i in ctx) {
if (demoUtils.isIslaType(ctx[i], "planet") || demoUtils.isIslaType(ctx[i], "star")) {
drawBody(canvasCtx, ctx[i], indications[i]);
}
}
};
// returns mass for object of density and radius
var mass = function(density, radius) {
return density * Math.pow(radius, 3) * Math.PI;
};
// returns the gravitational force between body1 and body2
var gravitationalForce = function(body1, body2) {
var m1 = mass(density(body1.density), size(body1.size) / 2);
var m2 = mass(density(body2.density), size(body2.size) / 2);
var r2 = Math.pow(demoUtils.absMax(body2._x - body1._x, 50), 2) +
Math.pow(demoUtils.absMax(body2._y - body1._y, 50), 2);
return (6.673e-11 * m1 * m2) / r2;
};
// returns the horizontal and vertical pull of body2 on body1
var gravitationalVector = function(body1, body2) {
var force = gravitationalForce(body1, body2);
return {
x: (body2._x - body1._x) * force,
y: (body2._y - body1._y) * force
};
};
var move = function(ctx) {
// build list of gravitational pulls on bodies
var m = [];
for (var i in ctx) {
for (var j in ctx) {
if ((ctx[i] !== ctx[j] && demoUtils.isIslaType(ctx[i], "planet")) &&
(demoUtils.isIslaType(ctx[j], "planet") || demoUtils.isIslaType(ctx[j], "star"))) {
m.push({
bodyId: i,
vec: gravitationalVector(ctx[i], ctx[j])
})
}
}
}
// apply m to speed, and move
for (var i = 0; i < m.length; i++) {
var b = ctx[m[i].bodyId];
b._xSpeed = (pf(b._xSpeed)) + m[i].vec.x;
b._ySpeed = (pf(b._ySpeed)) + m[i].vec.y;
b._x = pf(b._x) + pf(b._xSpeed);
b._y = pf(b._y) + pf(b._ySpeed);
}
// to string all vals for Isla
for (var i in ctx) {
if (demoUtils.isIslaType(ctx[i], "planet")) {
var b = ctx[i];
b._xSpeed = b._xSpeed.toString();
b._ySpeed = b._ySpeed.toString();
b._x = b._x.toString();
b._y = b._y.toString();
}
}
return ctx;
};
var drawBody = function(canvasCtx, body, indicate) {
var bodySize = size(body.size);
canvasCtx.strokeStyle = demoUtils.color(body.color);
canvasCtx.beginPath();
canvasCtx.arc(body._x, body._y, bodySize / 2, 0, Math.PI * 2, true);
canvasCtx.closePath();
if (indicate === true) {
canvasCtx.lineWidth = 4;
} else {
canvasCtx.lineWidth = 1;
}
canvasCtx.stroke();
};
var setupHelp = function(demoTalker, demo) {
demoTalker.on(this, "isla:mouse:mouseover", function(data) {
if (data.thing === "token" && data.syntaxNode.syntax === "variable") {
var indications = Isla.Library.clone(demo.indications());
indications[data.syntaxNode.code] = true;
demo.indications(indications);
}
});
demoTalker.on(this, "isla:mouse:mouseout", function() {
demo.indications({});
});
};
var clearHelp = function() {
indicate("clear");
};
var indicate = function(event, data) {
consoleIndicator.write({ event: event, data: data, id: id});
};
var SIZES = { small:20, medium:30, big:40, huge:80 };
var DENSITIES = { low:2, medium:4, high:6 };
var size = function(sizeStr) {
return demoUtils.translateNumberWord(sizeStr, SIZES);
};
var density = function(densityStr) {
return demoUtils.translateNumberWord(densityStr, DENSITIES);
};
// don't spawn too near to, or far from, the centre
var getRandomBodyCoords = function(canvasCtx) {
return {
x: demoUtils.plusMinus(canvasCtx.canvas.width / 8 +
demoUtils.random(canvasCtx.canvas.width / 6)) +
canvasCtx.canvas.width / 2,
y: demoUtils.plusMinus(canvasCtx.canvas.height / 8 +
demoUtils.random(canvasCtx.canvas.height / 6)) +
canvasCtx.canvas.height / 2
};
};
var planetDefaults = function(canvasCtx, planet) {
var retPlanet = planet;
retPlanet.size = retPlanet.size ||
demoUtils.random(demoUtils.edit(SIZES, ["huge"]));
retPlanet.color = retPlanet.color ||
demoUtils.random(demoUtils.edit(demoUtils.COLORS, ["yellow"]));
retPlanet.density = retPlanet.density || demoUtils.random(DENSITIES);
retPlanet._xSpeed = retPlanet._xSpeed || demoUtils.random(0.2) - 0.1;
retPlanet._ySpeed = retPlanet._ySpeed || demoUtils.random(0.2) - 0.1;
if (retPlanet._x === undefined) {
var coords = getRandomBodyCoords(canvasCtx);
retPlanet._x = coords.x;
retPlanet._y = coords.y;
}
return retPlanet;
};
var starDefaults = function(canvasCtx, star, gotStar) {
var retStar = star;
retStar.size = retStar.size || "huge";
retStar.color = retStar.color || "yellow";
retStar.density = retStar.density || 'high';
if (gotStar) {
var coords = getRandomBodyCoords(canvasCtx);
retStar._x = retStar._x || coords.x;
retStar._y = retStar._y || coords.y;
} else {
retStar._x = retStar._x || canvasCtx.canvas.width / 2;
retStar._y = retStar._y || canvasCtx.canvas.height / 2;
}
return retStar;
};
var STEPS = [
"sun is a star",
"mars is a planet",
"mars color is 'red'",
"mars size is 'medium'",
"jupiter is a planet",
"jupiter color is 'orange'",
"jupiter size is 'big'"
];
exports.Planets = Planets;
})(typeof exports === 'undefined' ? this : exports)
|
decomp/experimental
|
cmd/bin2c/main.go
|
// bin2c is a tool which converts binary executables to equivalent C source
// code.
package main
import (
"debug/pe"
"flag"
"fmt"
"go/printer"
"go/token"
"log"
"os"
"strconv"
"strings"
"github.com/mewkiz/pkg/errutil"
)
func usage() {
const use = `
Usage: bin2c -addr ADDRESS [OPTION]... FILE
Convert binary executables to equivalent C source code.
Flags:
`
fmt.Fprint(os.Stderr, use[1:])
flag.PrintDefaults()
}
// Command line flags.
var (
// flagVerbose specifies whether verbose output is enabled.
flagVerbose bool
)
// Base address of the ".text" section.
const baseAddr = 0x00401000
func main() {
// Parse command line arguments.
var (
// addr specifies the address to decompile.
addr address
)
flag.BoolVar(&flagVerbose, "v", false, "Enable verbose output.")
flag.Var(&addr, "addr", "Address of function to decompile.")
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
path := flag.Arg(0)
if addr == 0 {
flag.Usage()
os.Exit(1)
}
// Parse ".text" section.
text, err := parseText(path)
if err != nil {
log.Fatal(err)
}
// Sanity check.
offset := int(addr - baseAddr)
if offset < 0 || offset >= len(text) {
log.Fatalf("invalid address; expected >= 0x%X and < 0x%X, got 0x%X", baseAddr, baseAddr+len(text), addr)
}
// Parse basic blocks.
//blocks, err := parseBlocks(text, offset)
//if err != nil {
// log.Fatal(err)
//}
// Convert the given function to C source code.
fn, err := parseFunc(text, offset)
if err != nil {
log.Fatal(err)
}
printer.Fprint(os.Stdout, token.NewFileSet(), fn)
}
// parseText parses and returns the ".text" section of the given binary
// executable.
func parseText(path string) (text []byte, err error) {
f, err := pe.Open(path)
if err != nil {
return nil, errutil.Err(err)
}
defer f.Close()
sect := f.Section(".text")
if sect == nil {
return nil, errutil.Newf(`unable to locate ".text" section in %q`, path)
}
return sect.Data()
}
// address implements the flag.Value interface and allows addresses to be
// specified in hexadecimal format.
type address uint64
// String returns the hexadecimal string representation of v.
func (v *address) String() string {
return fmt.Sprintf("0x%X", uint64(*v))
}
// Set sets v to the numberic value represented by s.
func (v *address) Set(s string) error {
base := 10
if strings.HasPrefix(s, "0x") || strings.HasPrefix(s, "0X") {
s = s[2:]
base = 16
}
x, err := strconv.ParseUint(s, base, 64)
if err != nil {
return errutil.Err(err)
}
*v = address(x)
return nil
}
|
mohajain/GDevelop
|
Extensions/ParticleSystem/SPARK/include/Core/SPK_RegWrapper.h
|
<filename>Extensions/ParticleSystem/SPARK/include/Core/SPK_RegWrapper.h
//////////////////////////////////////////////////////////////////////////////////
// SPARK particle engine //
// Copyright (C) 2008-2009 - <NAME> - <EMAIL> //
// //
// This software is provided 'as-is', without any express or implied //
// warranty. In no event will the authors be held liable for any damages //
// arising from the use of this software. //
// //
// Permission is granted to anyone to use this software for any purpose, //
// including commercial applications, and to alter it and redistribute it //
// freely, subject to the following restrictions: //
// //
// 1. The origin of this software must not be misrepresented; you must not //
// claim that you wrote the original software. If you use this software //
// in a product, an acknowledgment in the product documentation would be //
// appreciated but is not required. //
// 2. Altered source versions must be plainly marked as such, and must not be //
// misrepresented as being the original software. //
// 3. This notice may not be removed or altered from any source distribution. //
//////////////////////////////////////////////////////////////////////////////////
#ifndef H_SPK_REGWRAPPER
#define H_SPK_REGWRAPPER
#include "Core/SPK_DEF.h"
#include "Core/SPK_Registerable.h"
namespace SPK
{
/**
* @class RegWrapper
* @brief A Wrapper class that allows to use any type of object as a Registerable
*
* It simply encapsulates an object of type defined at compilation time.<br>
* It allows to define the behavior of these Group attributes when a copy of the Group occurs.<br>
* <br>
* The user can use it to define an attribute of a custom Registerable child class that needs to act as a Registerable.<br>
* <br>
* WARNING : T must obviously not be itself a Registerable.
*
* @since 1.03.00
*/
template<class T>
class RegWrapper : public Registerable
{
SPK_IMPLEMENT_REGISTERABLE(RegWrapper<T>)
public :
//////////////////
// Constructors //
//////////////////
/**
* @brief Default constructor of RegWrapper
* @param object : the inner object
*/
RegWrapper<T>(const T& object = T());
/**
* @brief Creates and registers a new RegWrapper
* @param object : the inner object
* @return A new registered RegWrapper
* @since 1.04.00
*/
static RegWrapper<T>* create(const T& object = T());
/////////////
// Getters //
/////////////
/**
* @brief Gets a reference on the inner object
* @return a reference on the inner object
*/
T& get();
/**
* @brief Gets a constant reference on the inner object
* @return a constant reference on the inner object
*/
const T& get() const;
private :
T object;
};
template<class T>
inline RegWrapper<T>* RegWrapper<T>::create(const T& object)
{
RegWrapper<T>* obj = new RegWrapper<T>(object);
registerObject(obj);
return obj;
}
template<class T>
inline T& RegWrapper<T>::get()
{
return object;
}
template<class T>
inline const T& RegWrapper<T>::get() const
{
return object;
}
}
#endif
|
swenker/studio
|
python/cloud/alioss/test_oss_browser.py
|
<reponame>swenker/studio
__author__ = 'samsung'
import unittest
import base64
import sha
import hmac
import oss_browser
class TestOSSService(unittest.TestCase):
@unittest.skip("this get passed")
def test_list_buckets(self):
oss = oss_browser.OSSService()
oss.list_buckets()
#<EMAIL>("")
def test_list_service(self):
oss = oss_browser.OSSService()
oss.list_objects()
@unittest.skip("")
def test_gen_signature(self):
oss = oss_browser.OSSService()
print oss.gen_signature("OtxrzxIsfpFjA7SwPzILwy8Bw21TLhquhboDYROV",
"PUT","c8fdb181845a4ca6b8fec737b3581d76","text/html","Thu, 17 Nov 2005 18:49:58 GMT","x-oss-magic:abracadabra\nx-oss-meta-author:<EMAIL>\n","/oss-example/nelson")
@unittest.skip("")
def test_gen_signature2(self):
h=hmac.new("OtxrzxIsfpFjA7SwPzILwy8Bw21TLhquhboDYROV",
"PUT\nc8fdb181845a4ca6b8fec737b3581d76\ntext/html\nThu, 17 Nov 2005 18:49:58 GMT\nx-oss-magic:abracadabra\nx-oss-meta-author:<EMAIL>\n/oss-example/nelson", sha)
print "|"+base64.encodestring(h.digest()).strip()+"|"
if __name__=="__main__":
unittest.main()
|
ampsight/mage-server
|
public/app/admin/events/event.access.controller.js
|
var _ = require('underscore');
module.exports = AdminEventAccessController;
AdminEventAccessController.$inject = ['$scope', '$location', '$routeParams', '$q', '$filter', 'Event', 'EventAccess', 'UserService'];
function AdminEventAccessController($scope, $location, $routeParams, $q, $filter, Event, EventAccess, UserService) {
var users = [];
$scope.member = {};
$scope.roles = [{
name: 'GUEST',
title: 'Guest',
description: 'Read only access to this event.'
},{
name: 'MANAGER',
title: 'Manager',
description: 'Read and Update access to this event.'
},{
name: 'OWNER',
title: 'Owner',
description: 'Read, Update and Delete access to this event.'
}];
$q.all({users: UserService.getAllUsers(), event: Event.get({id: $routeParams.eventId, populate: false}).$promise}).then(function(result) {
users = result.users;
$scope.role = {
selected: $scope.roles[0]
};
refreshMembers(result.event);
});
function refreshMembers(event) {
$scope.event = event;
var usersById = _.indexBy(users, 'id');
$scope.eventMembers = _.map($scope.event.acl, function(access, userId) {
var member = _.pick(usersById[userId], 'displayName', 'avatarUrl', 'lastUpdated');
member.id = userId;
member.role = {
selected: _.find($scope.roles, function(role) { return role.name === access.role; })
};
return member;
});
$scope.nonMembers = _.reject(users, function(user) {
return _.where($scope.eventMembers, {id: user.id}).length > 0;
});
$scope.owners = owners();
}
function owners() {
return _.filter($scope.eventMembers, function(member) {
return member.role.selected.name === 'OWNER';
});
}
$scope.addMember = function(member, role) {
EventAccess.update({
eventId: $scope.event.id,
userId: member.id,
role: role.name
}, function(event) {
delete $scope.member.selected;
refreshMembers(event);
});
};
$scope.removeMember = function(member) {
EventAccess.delete({
eventId: $scope.event.id,
userId: member.id
}, function(event) {
refreshMembers(event);
});
};
$scope.updateRole = function(member, role) {
EventAccess.update({
eventId: $scope.event.id,
userId: member.id,
role: role.name
}, function(event) {
refreshMembers(event);
});
};
$scope.gotoUser = function(member) {
$location.path('/admin/users/' + member.id);
};
$scope.filterMembers = function(member) {
var filteredMembers = $filter('filter')([member], $scope.memberSearch);
return filteredMembers && filteredMembers.length;
};
}
|
kevinpeterson/lexevs-service
|
src/test/java/edu/mayo/cts2/framework/plugin/service/lexevs/service/association/AssociationQueryImpl.java
|
<gh_stars>1-10
/*
* Copyright: (c) Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/lexevs-service/LICENSE.txt for details.
*/
package edu.mayo.cts2.framework.plugin.service.lexevs.service.association;
import java.util.Set;
import edu.mayo.cts2.framework.model.command.ResolvedFilter;
import edu.mayo.cts2.framework.model.command.ResolvedReadContext;
import edu.mayo.cts2.framework.model.service.core.Query;
import edu.mayo.cts2.framework.service.command.restriction.AssociationQueryServiceRestrictions;
import edu.mayo.cts2.framework.service.profile.association.AssociationQuery;
public class AssociationQueryImpl implements AssociationQuery {
private Query query;
private Set<ResolvedFilter> filterComponent;
private ResolvedReadContext readContext;
private AssociationQueryServiceRestrictions restrictions;
public AssociationQueryImpl() {
super();
}
public AssociationQueryImpl(Query query,
Set<ResolvedFilter> filterComponent,
ResolvedReadContext readContext,
AssociationQueryServiceRestrictions restrictions) {
super();
this.query = query;
this.filterComponent = filterComponent;
this.readContext = readContext;
this.restrictions = restrictions;
}
@Override
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
@Override
public Set<ResolvedFilter> getFilterComponent() {
return filterComponent;
}
public void setFilterComponent(Set<ResolvedFilter> filterComponent) {
this.filterComponent = filterComponent;
}
@Override
public ResolvedReadContext getReadContext() {
return readContext;
}
public void setReadContext(ResolvedReadContext readContext) {
this.readContext = readContext;
}
@Override
public AssociationQueryServiceRestrictions getRestrictions() {
return restrictions;
}
public void setRestrictions(AssociationQueryServiceRestrictions restrictions) {
this.restrictions = restrictions;
}
}
|
Dzenly/tia
|
other/tmp-light-utils/index.js
|
<filename>other/tmp-light-utils/index.js
'use strict';
let util = require('util');
let fileUtils = require('dz-file-utils');
let dirUtils = require('dz-dir-utils');
let timer = require('dz-timer-utils');
let dateUtils = require('dz-date-utils');
process.env.FORCE_COLOR = '1';
let chalk = require('chalk');
let cfg = {
throwAtFail: false,
colorsEnabled: false,
passStr: 'PASS',
failStr: 'FAIL',
logMsg: function (msg) {
console.log(msg);
},
logErr: function (msg) {
console.error(msg); // OK with console.error. Tmp utils.
},
indent: ' '
};
let inner = {
passCnt: 0,
failCnt: 0
};
inner.logDiff = function (actVal, expVal) {
cfg.logErr('Act. value: ' + util.inspect(actVal) + ', Exp. value: ' + expVal + '\n');
};
exports.eq = function (actVal, expVal, msg, colorFunc) {
let res = actVal === expVal;
if (res) {
exports.pass(msg, colorFunc);
return true;
} else {
inner.logDiff(actVal, expVal);
exports.fail(msg);
return false;
}
};
exports.eqDays = function (date1, date2, msg) {
return exports.eq(dateUtils.trunkDateToDay(date1), dateUtils.trunkDateToDay(date2), msg);
};
exports.eqObjects = function (obj1, obj2, msg) {
let aProps = Object.getOwnPropertyNames(obj1);
let bProps = Object.getOwnPropertyNames(obj2);
if (aProps.length != bProps.length) {
exports.fail(msg + ': Objects comparison: different property counts');
return false;
}
for (let i = 0; i < aProps.length; i++) {
let propName = aProps[i];
if (obj1[propName] !== obj2[propName]) {
exports.fail(msg + ': Objects comparison: different values for property: ' + propName +
', "' + obj1[propName] + '", vs "' + obj2[propName]);
return false;
}
}
exports.pass(msg);
return true;
};
// Returns value, returned by the func, or undefined (it function throws an error).
exports.doesThrow = function (func, msg, arrArg) {
let res;
try {
res = func.apply(null, arrArg);
exports.fail(msg + ' Unexpected no throw.');
return res;
} catch (e) {
exports.pass(msg + ' Expected throw from function: ' + e.message);
}
};
// Returns value, returned by the func, or undefined (it function throws an error).
exports.doesNotThrow = function (func, msg, arrArg) {
let res;
try {
res = func.apply(null, arrArg);
exports.pass(msg + ' Expected no throw.');
return res;
} catch (e) {
exports.fail(msg + ' Unexpected throw from function: ' + e.message);
}
};
exports.checkSubstr = function (str, substr, msg) {
cfg.logMsg(cfg.indent + 'Checking for substring: "' + substr + '"');
let ind = str.search(substr);
if (ind === -1) {
cfg.logErr('No expression: "' + substr + '" found in string: \n' + str);
exports.fail(msg);
return false;
} else {
exports.pass(msg);
return true;
}
};
// Отличается от eq только цветом.
// Подразумевается, что так проверяется, что сгенерирована правильная ошибка.
exports.eqErr = function (actVal, expVal, msg) {
return exports.eq(actVal, expVal, msg, chalk.yellow);
};
exports.checkAssertion = function (e, msg) {
exports.eq(e.name, 'AssertionError', msg, chalk.yellow);
cfg.logMsg(cfg.indent + 'Ass. Msg: ' + e.message);
};
exports.section = function (msg) {
exports.sep();
exports.msg(msg);
};
exports.msg = function (msg) {
cfg.logMsg(cfg.indent + msg);
};
exports.msgErr = function (msg) {
cfg.logErr(cfg.indent + msg);
};
exports.msgBold = function (msg) {
cfg.logMsg(chalk.bold(cfg.indent + msg));
};
exports.sep = function () {
cfg.logMsg(/*cfg.indent + */' ================');
};
exports.fail = function (msg) {
msg = colorMsg(chalk.red, msg);
cfg.logErr(cfg.failStr + ': ' + msg);
inner.failCnt++;
if (cfg.throwAtFail) {
throw new Error('Stop tests at first fail, according to settings');
}
};
exports.pass = function (msg, colorFunc) {
msg = colorMsg(colorFunc ? colorFunc : chalk.green, msg);
cfg.logMsg(cfg.passStr + ': ' + msg);
inner.passCnt++;
};
exports.total = function () {
cfg.logMsg('=================');
let msg = 'Passes: ' + inner.passCnt + ', Fails: ' + inner.failCnt;
msg = colorMsg(inner.failCnt > 0 ? chalk.red : chalk.green, msg);
let timeMsg = timer.timeDiffStr(inner.totStartTime);
cfg.logMsg(msg + ', Duration: ' + timeMsg);
};
function timeDiffStr(startTime) {
return colorMsg(chalk.cyan, timer.timeDiffStr(startTime));
}
exports.startTimer = function (msg) {
return timer.startTimer(msg);
};
exports.stopTimer = function (timerObj) {
if (!timerObj) {
return;
}
let msg = timer.stopTimer(timerObj, true);
cfg.logMsg(colorMsg(chalk.blue, cfg.indent + msg));
};
// ====
exports.checkFileExist = function (file) {
exports.eq(fileUtils.checkFileExists(file), true, 'File "' + file + '" exists');
};
exports.checkFilesExist = function (files) {
for (let i = 0, len = files.length; i < len; i++) {
exports.checkFileExist(files[i]);
}
};
// ====
exports.checkFileExistAndNonEmpty = function (file) {
exports.eq(fileUtils.checkFileExistsAndNonEmpty(file), true, 'File "' + file + '" exists');
};
exports.checkFilesExistAndNonEmpty = function (files) {
for (let i = 0, len = files.length; i < len; i++) {
exports.checkFileExistAndNonEmpty(files[i]);
}
};
// ====
exports.checkFileAbsent = function (file) {
exports.eq(fileUtils.checkFileExists(file), false, 'File "' + file + '" absent');
};
exports.checkFilesAbsent = function (files) {
for (let i = 0, len = files.length; i < len; i++) {
exports.checkFileAbsent(files[i]);
}
};
// ====
exports.checkDirExist = function (dir) {
exports.eq(dirUtils.checkDirExists(dir), true, 'Dir "' + dir + '" exists');
};
exports.checkDirsExist = function (dirs) {
for (let i = 0, len = dirs.length; i < len; i++) {
exports.checkDirExist(dirs[i]);
}
};
// ====
exports.checkDirAbsent = function (dir) {
exports.eq(dirUtils.checkDirExists(dir), false, 'Dir "' + dir + '" absent');
};
exports.checkDirsAbsent = function (dirs) {
for (let i = 0, len = dirs.length; i < len; i++) {
exports.checkDirAbsent(dirs[i]);
}
};
// ====
// Resets total timer.
exports.init = function (throwAtFail, colorsEnabled) {
if (typeof throwAtFail !== 'undefined') {
cfg.throwAtFail = throwAtFail;
}
if (typeof colorsEnabled !== 'undefined') {
cfg.colorsEnabled = colorsEnabled;
}
inner.totStartTime = process.hrtime();
};
function colorMsg(func, msg) {
if (cfg.colorsEnabled) {
return func(msg);
}
return msg;
}
exports.init();
|
dima-vm/private-VictoriaMetrics
|
vendor/google.golang.org/grpc/xds/internal/server/rds_handler.go
|
/*
*
* Copyright 2021 gRPC 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.
*
*/
package server
import (
"sync"
"google.golang.org/grpc/xds/internal/xdsclient"
)
// rdsHandlerUpdate wraps the full RouteConfigUpdate that are dynamically
// queried for a given server side listener.
type rdsHandlerUpdate struct {
updates map[string]xdsclient.RouteConfigUpdate
err error
}
// rdsHandler handles any RDS queries that need to be started for a given server
// side listeners Filter Chains (i.e. not inline).
type rdsHandler struct {
xdsC XDSClient
mu sync.Mutex
updates map[string]xdsclient.RouteConfigUpdate
cancels map[string]func()
// For a rdsHandler update, the only update wrapped listener cares about is
// most recent one, so this channel will be opportunistically drained before
// sending any new updates.
updateChannel chan rdsHandlerUpdate
}
// newRDSHandler creates a new rdsHandler to watch for RDS resources.
// listenerWrapper updates the list of route names to watch by calling
// updateRouteNamesToWatch() upon receipt of new Listener configuration.
func newRDSHandler(xdsC XDSClient, ch chan rdsHandlerUpdate) *rdsHandler {
return &rdsHandler{
xdsC: xdsC,
updateChannel: ch,
updates: make(map[string]xdsclient.RouteConfigUpdate),
cancels: make(map[string]func()),
}
}
// updateRouteNamesToWatch handles a list of route names to watch for a given
// server side listener (if a filter chain specifies dynamic RDS configuration).
// This function handles all the logic with respect to any routes that may have
// been added or deleted as compared to what was previously present.
func (rh *rdsHandler) updateRouteNamesToWatch(routeNamesToWatch map[string]bool) {
rh.mu.Lock()
defer rh.mu.Unlock()
// Add and start watches for any routes for any new routes in
// routeNamesToWatch.
for routeName := range routeNamesToWatch {
if _, ok := rh.cancels[routeName]; !ok {
func(routeName string) {
rh.cancels[routeName] = rh.xdsC.WatchRouteConfig(routeName, func(update xdsclient.RouteConfigUpdate, err error) {
rh.handleRouteUpdate(routeName, update, err)
})
}(routeName)
}
}
// Delete and cancel watches for any routes from persisted routeNamesToWatch
// that are no longer present.
for routeName := range rh.cancels {
if _, ok := routeNamesToWatch[routeName]; !ok {
rh.cancels[routeName]()
delete(rh.cancels, routeName)
delete(rh.updates, routeName)
}
}
// If the full list (determined by length) of updates are now successfully
// updated, the listener is ready to be updated.
if len(rh.updates) == len(rh.cancels) && len(routeNamesToWatch) != 0 {
drainAndPush(rh.updateChannel, rdsHandlerUpdate{updates: rh.updates})
}
}
// handleRouteUpdate persists the route config for a given route name, and also
// sends an update to the Listener Wrapper on an error received or if the rds
// handler has a full collection of updates.
func (rh *rdsHandler) handleRouteUpdate(routeName string, update xdsclient.RouteConfigUpdate, err error) {
if err != nil {
drainAndPush(rh.updateChannel, rdsHandlerUpdate{err: err})
return
}
rh.mu.Lock()
defer rh.mu.Unlock()
rh.updates[routeName] = update
// If the full list (determined by length) of updates have successfully
// updated, the listener is ready to be updated.
if len(rh.updates) == len(rh.cancels) {
drainAndPush(rh.updateChannel, rdsHandlerUpdate{updates: rh.updates})
}
}
func drainAndPush(ch chan rdsHandlerUpdate, update rdsHandlerUpdate) {
select {
case <-ch:
default:
}
ch <- update
}
// close() is meant to be called by wrapped listener when the wrapped listener
// is closed, and it cleans up resources by canceling all the active RDS
// watches.
func (rh *rdsHandler) close() {
rh.mu.Lock()
defer rh.mu.Unlock()
for _, cancel := range rh.cancels {
cancel()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.