file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
day18.rs | ;
for i in 0..4 {
if i == 0 {
xd = -1; yd = 0;
} else if i == 1 {
xd = 1; yd = 0;
} else if i == 2 {
xd = 0; yd = 1;
} else if i == 3 {
xd = 0; yd = -1;
}
let x1 = (*node).x as i64 + xd;
let y1 = (*node).y as i64 + yd;
if x1 < 0 || x1 >= (*maze).width as i64 ... | {
for y in 0..vec.len() {
let mut line = String::from("");
let bytes = vec[y].as_bytes();
for x in 0..vec[y].len() {
if (x == ox - 1 && y == oy - 1) ||
(x == ox + 1 && y == oy - 1) ||
(x == ox - 1 && y == oy + 1) ||
(x == ox + 1 && y == oy + 1) {
line.push('@');
} else if (x == o... | conditional_block | |
day18.rs | rontier.clear();
for key in frontier_next.keys() {
let node = frontier_next.get(key).unwrap();
let node2 = (*node).clone();
frontier.insert(key.to_string(), node2);
}
frontier_next.clear();
for key in frontier.keys() {
//println!("Key {}", key);
let node = frontier.get(key).unwrap();
if (*n... | for key in frontier.keys() {
let node = frontier.get(key).unwrap();
let exploredindex1 = exploredindex(maze, (*node).x, (*node).y);
if explored.contains_key(&exploredindex1) {
let last_dist = explored.get(&exploredindex1).unwrap().dist;
if (*node).dist < last_dist {
let node2 = explored.get_mut(... | {
let mut explored:HashMap<usize, DNode> = HashMap::new();
let mut frontier:HashMap<usize,DNode> = HashMap::new();
let mut frontier_next:HashMap<usize,DNode> = HashMap::new();
frontier_next.insert(exploredindex(maze, start_x, start_y), DNode{x:start_x, y:start_y, dist:0, parent_x:start_x, parent_y:start_y});
... | identifier_body |
day18.rs | rontier.clear();
for key in frontier_next.keys() {
let node = frontier_next.get(key).unwrap();
let node2 = (*node).clone();
frontier.insert(key.to_string(), node2);
}
frontier_next.clear();
for key in frontier.keys() {
//println!("Key {}", key);
let node = frontier.get(key).unwrap();
if (*n... | } else if i == 3 {
xd = 0; yd = -1;
}
let x1 = (*node).x as i64 + xd;
let y1 = (*node).y as i64 + yd;
if x1 < 0 || x1 >= (*maze).width as i64 || y1 < 0 || y1 >= (*maze).height as i64 {
continue;
}
else {
if (*maze).grid[y1 as usize][x1 as usize].obstacle {
continu... | } else if i == 1 {
xd = 1; yd = 0;
} else if i == 2 {
xd = 0; yd = 1; | random_line_split |
day18.rs | {
x: usize,
y: usize,
dist: usize,
parent_x:usize,
parent_y:usize
}
#[derive(Clone)]
struct DNodeB {
at:Vec<usize>,
keys:Vec<usize>,
dist:usize
}
fn intersect_count (vec_a:&Vec<usize>, vec_b:&Vec<usize>)->usize {
let mut count = 0;
for i in 0..vec_a.len() {
for j in 0..vec_b.len() {
if vec_b[j] == vec... | DNode | identifier_name | |
mtaresolver.go | resolvePath(path string, parts ...string) string {
absolutePath := path
if !filepath.IsAbs(path) {
absolutePath = filepath.Join(append(parts, absolutePath)...)
}
return absolutePath
}
// ResolveProperties is the main function to trigger the resolution
func (m *MTAResolver) ResolveProperties(module *mta.Module, ... | {
if source != nil {
// See if the value was configured externally first (in VCAP_SERVICES, env var etc)
// The source can be a module or a resource
module, found := m.context.modules[source.Name]
if found {
paramValStr, ok := module[paramName]
if ok {
return paramValStr
}
}
resource, found :... | identifier_body | |
mtaresolver.go | ([]map[string]interface{})
envVar[requires.Group] = append(groupArray, propMap)
} else {
envVar[requires.Group] = []map[string]interface{}{propMap}
}
}
}
//serialize
return serializePropertiesAsEnvVars(envVar)
}
func serializePropertiesAsEnvVars(envVar map[string]interface{}) (map[string]string, er... | propValue := m.resolve(module, nil, value)
module.Properties[key] = m.resolvePlaceholders(module, nil, nil, propValue)
}
//required properties:
for _, req := range module.Requires {
requiredSource := m.findProvider(req.Name)
for propName, PropValue := range req.Properties {
resolvedValue := m.resolve(mod... | for key, value := range module.Properties {
//no expected variables | random_line_split |
mtaresolver.go | map[string]interface{})
envVar[requires.Group] = append(groupArray, propMap)
} else {
envVar[requires.Group] = []map[string]interface{}{propMap}
}
}
}
//serialize
return serializePropertiesAsEnvVars(envVar)
}
func serializePropertiesAsEnvVars(envVar map[string]interface{}) (map[string]string, error... | (path string, parts ...string) string {
absolutePath := path
if !filepath.IsAbs(path) {
absolutePath = filepath.Join(append(parts, absolutePath)...)
}
return absolutePath
}
// ResolveProperties is the main function to trigger the resolution
func (m *MTAResolver) ResolveProperties(module *mta.Module, envFilePath ... | resolvePath | identifier_name |
mtaresolver.go | )
}
return valueObj
case []interface{}:
for i, v := range valueObj {
valueObj[i] = m.resolve(sourceModule, requires, v)
}
return valueObj
case string:
return m.resolveString(sourceModule, requires, valueObj)
default:
//if the value is not a string but a leaf, just return it
return valueObj
}
}
... | {
if curr == value {
return true
}
} | conditional_block | |
stlib.py | 'script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
return True
def text_from_html(body):
soup = bs(body, 'html.parser')
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return u" ".join(t.str... | list_len_tup_clean.sort(key = lambda item: item[1], reverse=True)
top_urls = [url for url, length in list_len_tup_clean[:2]]
if len(top_urls) > 1:
print(f"""
We found something sketchy. You might want to check these links:
- {top_urls[0]}
- ... | return (url, length) if length != 0 else None
def most_warnings(urls, look_for):
list_len_tup = list(map(warnings_count, urls))
list_len_tup_clean = list(filter(lambda item: item != None, list_len_tup)) | random_line_split |
stlib.py | _tup))
list_len_tup_clean.sort(key = lambda item: item[1], reverse=True)
top_urls = [url for url, length in list_len_tup_clean[:2]]
if len(top_urls) > 1:
print(f"""
We found something sketchy. You might want to check these links:
- {top_urls[0]}
... | find_companies_by_size | identifier_name | |
stlib.py | script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
return True
def text_from_html(body):
soup = bs(body, 'html.parser')
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return u" ".join(t.strip... |
# Look for data about sector
def category(sector, investments):
# Gather tweets
public_tweets = api.search(sector)
# Gather news
public_news = newsapi.get_everything(q=sector,sources=news_sources,language='en')
# Prepare the data for the sector
investments = investments.dropna(su... | news_list = []
for piece in range(len(public_news['articles'])):
news_list.append(TextBlob(public_news['articles'][piece]['title']).sentiment[0])
news_list.append(TextBlob(public_news['articles'][piece]['description']).sentiment[0])
if sum(news_list)>0:
news_sent = 'Positive'
elif s... | identifier_body |
stlib.py | script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
return True
def text_from_html(body):
soup = bs(body, 'html.parser')
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return u" ".join(t.strip... |
def retrieve_sector(my_sector, investments):
investments = investments.dropna(subset=['raised_amount_usd', 'company_category_list'])
sector_list0 = []
sector_list = []
for item in investments['company_category_list']:
if ',' in item:
sector_list0.append(item.split(sep=', '))
... | action = input("Did you mean %s instead? [y or n]: " % get_close_matches(my_name, companies_list)[0])
if (action == "y"):
return get_close_matches(my_name, companies_list)[0]
elif (action == "n"):
return my_name
else:
return("we don't understand you. Apologies... | conditional_block |
train.py | , \
restore_checkpoint, print_para, restore_best_checkpoint
import logging
from tensorboardX import SummaryWriter
import json
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=logging.DEBUG)
# This is needed to make the imports work
from allennlp.models import Model
import ... | enate(val_labels, 0)
val_probs = np.concatenate(val_probs, 0)
val_loss_avg = val_loss_sum / val_labels.shape[0]
val_metric_per_epoch.append(float(np.mean(val_labels == val_probs.argmax(1))))
if scheduler:
scheduler.step(val_metric_per_epoch[-1 | batch = _to_gpu(batch)
output_dict = model(**batch)
val_probs.append(output_dict['label_probs'].detach().cpu().numpy())
val_labels.append(batch['label'].detach().cpu().numpy())
val_loss_sum += output_dict['loss'].mean().item() * batch['label'].shape[0]
... | conditional_block |
train.py | , \
restore_checkpoint, print_para, restore_best_checkpoint
import logging
from tensorboardX import SummaryWriter
import json
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=logging.DEBUG)
# This is needed to make the imports work
from allennlp.models import Model
import ... | return td
for k in td:
if k != 'metadata':
td[k] = {k2: v.cuda(non_blocking=True) for k2, v in td[k].items()} if isinstance(td[k], dict) else td[
k].cuda(
non_blocking=True)
return td
# num_workers = (8 * NUM_GPUS if NUM_CPUS == 32 else 2 * NUM_GPUS)
... | > 1:
| identifier_name |
train.py | , \
restore_checkpoint, print_para, restore_best_checkpoint
import logging
from tensorboardX import SummaryWriter
import json
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=logging.DEBUG)
# This is needed to make the imports work
from allennlp.models import Model
import ... | GPUS if NUM_CPUS == 32 else 2 * NUM_GPUS)
num_workers = 8
print(f"Using {num_workers} workers out of {NUM_CPUS} possible", flush=True)
loader_params = {'batch_size': batch_size, 'num_workers': num_workers, "pin_memory": True}
# train_loader = DataLoader(train, shuffle=True, collate_fn=collate_fn, drop_last=True, batch_... | urn td
for k in td:
if k != 'metadata':
td[k] = {k2: v.cuda(non_blocking=True) for k2, v in td[k].items()} if isinstance(td[k], dict) else td[
k].cuda(
non_blocking=True)
return td
# num_workers = (8 * NUM_ | identifier_body |
train.py | _norm, \
restore_checkpoint, print_para, restore_best_checkpoint
import logging
from tensorboardX import SummaryWriter
import json
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=logging.DEBUG)
# This is needed to make the imports work
from allennlp.models import Model
im... | NUM_CPUS = multiprocessing.cpu_count() # NUM_CPUS = 32
if NUM_GPUS == 0:
raise ValueError("you need gpus!")
def _to_gpu(td):
if NUM_GPUS > 1:
return td
for k in td:
if k != 'metadata':
td[k] = {k2: v.cuda(non_blocking=True) for k2, v in td[k].items()} if isinstance(td[k], dict... | only_use_relevant_dets)) ########################这个地方我改成了false,使用全部的box
# NUM_GPUS = torch.cuda.device_count() # NUM_GPUS = 4
NUM_GPUS = 1 | random_line_split |
lab.py | ]['lon'] = node['lon']
return nodes
class Heap:
def __init__(self, prop, start=None, start_item=None):
self.property = 'min' if (prop == 'min') else 'max' # Heap property
self.heap = [] # List representation of the heap
self.items = [] # A list of the items corresponding to each i... | rn the shortest path between the two locations
Parameters:
aux_structures: the result of calling build_auxiliary_structures
loc1: tuple of 2 floats: (latitude, longitude), representing the start
location
loc2: tuple of 2 floats: (latitude, longitude), representing the end
... | identifier_body | |
lab.py | so we always maintain our heap property
# at every index after i
self.heapify_down(i)
elif start is not None:
self.add(start, start_item)
self.size = 1
def parent(self, i):
# Returns the index of i's parent if it has one
return (i + 1... | st(data, ids): | identifier_name | |
lab.py |
def build_auxiliary_structures(nodes_filename, ways_filename):
"""
Create any auxiliary structures you are interested in, by reading the data
from the given filenames (using read_osm_data)
"""
nodes = {}
for way in read_osm_data(ways_filename):
highway_type = way['tags'].get('highway',... | random_line_split | ||
lab.py | # If this isn't a oneway way, we can build the data structure for the next node as well
build_data(right, left)
elif right == nodes_along_way[-1]:
# In non-oneway ways, the above build_data(right, left) call creates the data structure
... | nodes_along_way[i]
right = nodes_along_way[i + 1]
default_speed_limit = DEFAULT_SPEED_LIMIT_MPH[highway_type]
# If this way doesn't have a speed limit tag, we use the default value based on highway type
speed_limit = way['tags'].get('maxspeed_mph', defaul... | conditional_block | |
cassandra.go | _ orm.Connector = (*cassandraConnector)(nil)
// getGocqlErrorTag gets a error tag for metrics based on gocql error
// We cannot just use err.Error() as a tag because it contains invalid
// characters like = : etc. which will be rejected by M3
func getGocqlErrorTag(err error) string {
if yarpcerrors.IsAlreadyExists(e... | if err != nil {
return nil, err
}
return c.Session.Query(stmt, keyColValues...).WithContext(ctx), nil
}
// Get fetches a record from DB using primary keys
func (c *cassandraConnector) Get(
ctx context.Context,
e *base.Definition,
keyCols []base.Column,
colNamesToRead ...string,
) ([]base.Column, error) {
if... | Conditions(keyColNames),
) | random_line_split |
cassandra.go | _ orm.Connector = (*cassandraConnector)(nil)
// getGocqlErrorTag gets a error tag for metrics based on gocql error
// We cannot just use err.Error() as a tag because it contains invalid
// characters like = : etc. which will be rejected by M3
func getGocqlErrorTag(err error) string {
if yarpcerrors.IsAlreadyExists(e... | (
e *base.Definition, columnNames []string, columnVals []interface{},
) []base.Column {
row := make([]base.Column, 0, len(columnNames))
for i, columnName := range columnNames {
// construct a list of column objects from the lists of column names
// and values that were returned by the cassandra query
column ... | getRowFromResult | identifier_name |
cassandra.go | _ orm.Connector = (*cassandraConnector)(nil)
// getGocqlErrorTag gets a error tag for metrics based on gocql error
// We cannot just use err.Error() as a tag because it contains invalid
// characters like = : etc. which will be rejected by M3
func getGocqlErrorTag(err error) string {
if yarpcerrors.IsAlreadyExists(e... | case **[]byte:
column.Value = *rv
default:
// This should only happen if we start using a new cassandra type
// without adding to the translation layer
log.WithFields(log.Fields{
"data": columnVals[i],
"column": columnName}).Infof("type not found")
}
row = append(row, column)
}
return r... | {
// construct a list of column objects from the lists of column names
// and values that were returned by the cassandra query
column := base.Column{
Name: columnName,
}
switch rv := columnVals[i].(type) {
case **int:
column.Value = *rv
case **int64:
column.Value = *rv
case **string:
column... | conditional_block |
cassandra.go | _ orm.Connector = (*cassandraConnector)(nil)
// getGocqlErrorTag gets a error tag for metrics based on gocql error
// We cannot just use err.Error() as a tag because it contains invalid
// characters like = : etc. which will be rejected by M3
func getGocqlErrorTag(err error) string {
if yarpcerrors.IsAlreadyExists(e... | }
q := c.Session.Query(stmt, colValues...).WithContext(ctx)
if casWrite {
applied, err := q.MapScanCAS(map[string]interface{}{})
if err != nil {
sendCounters(c.executeFailScope, e.Name, operation, err)
return err
}
if !applied {
return yarpcerrors.AlreadyExistsErrorf("item already exists")
}
} ... | {
// split row into a list of names and values to compose query stmt using
// names and use values in the session query call, so the order needs to be
// maintained.
colNames, colValues := splitColumnNameValue(row)
// Prepare insert statement
stmt, err := InsertStmt(
Table(e.Name),
Columns(colNames),
Value... | identifier_body |
SharedEnum.ts |
rePerSignatureLengthMax = 100,
}
export enum EStoryStack { // storyStack 表的枚举
story_stack_daily_times = 2045, // 剧本搜罗每天搜罗次数
story_stack_search_cost = 2046, // 剧本搜罗每次消耗物品
story_stack_cd_stage_cost = 2047, // 剧本搜罗每阶段搜罗冷却加速消耗资源类型和数量
story_stack_cd_stage_length = 2048, // 剧本搜罗阶段时长
story_stack_cd... | finished = 3, // 完成
rewarded = 4, // 已领奖的
}
export enum EAchievementType { // 成就或者任务的类型
daily = 1, // 日常
achievement = 2, // 成就
story = 3, // 剧本
mainTask = 4, // 主线任务
}
export enum EMallItemLimitType { // 商店限购类型
daily = 1, // 每日
weekly = 2, // 每周
}
export enum EManageBusiness { // 经营事... | none = 0, // 初始化
receivable = 1, // 可接
received = 2, // 已接 | random_line_split |
SharedEnum.ts | LimitType { // 商店限购类型
daily = 1, // 每日
weekly = 2, // 每周
}
export enum EManageBusiness { // 经营事务
baseLine = 10, // 基础代办事务上限
interval = 180, // 间隔时长
}
export enum EManageVisit { // 经营探班
baseLine = 3, // 基础探班队列
overdueTime = 180, // 过期时长
baseIntervalTime = 300, // 基本间隔时间
}
export enum EMana... | "GetGuid | identifier_name | |
main.rs | Status::new(Code::InvalidArgument, "invalid header name")
})?;
builder = builder.header(key, &header.value[..]);
}
if self.mock_network {
// Forward the network access to the controller.
warn!("mock network request");
... | /// If the tag corresponds to sensor state (say maybe it starts with #
/// which is reserved for state tags), forward the request as a state
/// change instead.
async fn push(
&self, req: Request<PushData>,
) -> Result<Response<()>, Status> {
debug!("push");
// Validate the p... | /// forward to the controller.
/// | random_line_split |
main.rs | Status::new(Code::InvalidArgument, "invalid header name")
})?;
builder = builder.header(key, &header.value[..]);
}
if self.mock_network {
// Forward the network access to the controller.
warn!("mock network request");
warn!("finish diff_... | (
&self, req: Request<PushData>,
) -> Result<Response<()>, Status> {
debug!("push");
// Validate the process is valid and has permissions to write the file.
// No serializability guarantees from other requests from the same process.
// Sanitizes the path.
let req = re... | push | identifier_name |
main.rs | Status::new(Code::InvalidArgument, "invalid header name")
})?;
builder = builder.header(key, &header.value[..]);
}
if self.mock_network {
// Forward the network access to the controller.
warn!("mock network request");
warn!("finish diff_... | return Ok(Response::new(()));
}
if state_tags::is_state_tag(&req.tag) {
Some(state_tags::parse_state_tag(&req.tag))
} else {
None
}
} else {
unreachable!()
};
if let Some((sensor, key)) =... | {
debug!("push");
// Validate the process is valid and has permissions to write the file.
// No serializability guarantees from other requests from the same process.
// Sanitizes the path.
let req = req.into_inner();
let rx = {
if let Some(perms) = self.proces... | identifier_body |
main.rs | Status::new(Code::InvalidArgument, "invalid header name")
})?;
builder = builder.header(key, &header.value[..]);
}
if self.mock_network {
// Forward the network access to the controller.
warn!("mock network request");
warn!("finish diff_... |
}
}
impl Host {
/// Generate a new host with a random ID.
pub fn new(
base_path: PathBuf,
controller: &str,
cold_cache_enabled: bool,
warm_cache_enabled: bool,
pubsub_enabled: bool,
mock_network: bool,
) -> Self {
use rand::Rng;
let id: u... | {
// Forward the file access to the controller and return the result
debug!("push: {} forwarding push tag={}", req.process_token, req.tag);
self.api.forward_push(req).await
} | conditional_block |
parser.rs | when parsing vmem files.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum ParseError {
/// Failure to parse an integer from hexadecimal.
#[error("failed to parse as hexadecimal integer")]
ParseInt(#[from] ParseIntError),
/// An opened comment was not closed.
#[error("unclosed comment")]
... | () {
// Check we can pick out the correct token from a string:
let expected = [
("", Token::Eof, 0),
("@ff", Token::Addr(0xff), 3),
("ff", Token::Value(0xff), 2),
("// X", Token::Comment, 4),
("/* X */", Token::Comment, 7),
(" ", T... | token | identifier_name |
parser.rs | when parsing vmem files.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum ParseError {
/// Failure to parse an integer from hexadecimal.
#[error("failed to parse as hexadecimal integer")]
ParseInt(#[from] ParseIntError),
/// An opened comment was not closed.
#[error("unclosed comment")]
... | /// Catch-all for any characters that don't belong in vmem files.
#[error("unknown character '{0}'")]
UnknownChar(char),
}
/// Representation of the possible tokens found in vmem files.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Token {
/// End of file.
Eof,
/// Address directive, e.g. `@... | AddrMissingValue,
| random_line_split |
parser.rs | parsing vmem files.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum ParseError {
/// Failure to parse an integer from hexadecimal.
#[error("failed to parse as hexadecimal integer")]
ParseInt(#[from] ParseIntError),
/// An opened comment was not closed.
#[error("unclosed comment")]
Unclo... |
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse() {
let input = r#"
AB
// comment
CD EF
@42
12 /* comment */ 34
"#;
let expected = Vmem {
sections: vec![
Section {
... | {
// Check for whitespace at the beginning of the input.
let len = match s.find(|c: char| !c.is_whitespace()) {
Some(0) => return Ok(None),
Some(len) => len,
None => s.len(),
};
let token = Token::Whitespace;
let span = Span { len, token };
... | identifier_body |
hCassandra_test.py | .01" \
"AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}" \
"AND comment = ''" \
"AND compaction = {'class': " \
"'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold':... | """
Select a random cassandra node from a list of IPs
"""
return random.choice(cluster_ips) | identifier_body | |
hCassandra_test.py | self.create_triggers()
# Launch Cassandra Stress-Client(s)
self.launch_stress_client()
# Rerun the test
res = self.rerun_test(self.options)
# Return Test Results
return res
def create_triggers(self):
try:
cluster_ips = self.options.cluster_ips.sp... | node_ip = select_random_node(node_ips)
# Determine delay before stopping cassandra node (to simulate failure / node down)
duration_secs = max_duration*60
time_next_stop = random.randint(1, duration_secs/4)
l.debug("STOP programmed in %s seconds" % time_next_stop)
... | conditional_block | |
hCassandra_test.py | (HydraBase):
def __init__(self, options, runtest=True, mock=False):
self.options = options
self.config = ConfigParser()
HydraBase.__init__(self, 'CassandraStressTest', self.options, self.config, startappserver=runtest, mock=mock,
app_dirs=['src', 'hydra'])
... | RunTestCassandra | identifier_name | |
hCassandra_test.py | l.info("Create keyspace [keyspace1]...")
# Create Keyspace
session.execute("CREATE KEYSPACE keyspace1 WITH replication = {'class': 'SimpleStrategy', "
"'replication_factor': '1'} AND durable_writes = true;")
l.info("Create tables [standard1] & [counter1]... | ssh.exec_command(stop_cmd)
# Determine delay before starting cassandra node (to simulate rejoin to the cluster)
time_next_rejoin = random.randint(1, duration_secs/4)
l.debug("START programmed in %s seconds" % time_next_rejoin) | random_line_split | |
main.rs | a",))
.add("Adverb",vec!("b","bl","ad","d","dl","œa","dg",))
.add("AllPronouns", vec!("rr","rz","ryt","Rg","ry","rys","rzs","rzt","ryv","k",))
.add("AskWhen", vec!("rzt"))
.add("When", vec!("ryt"))
.add("AskHow", vec!("ryv"))
.add("AskWhere", vec!(... | !(
| identifier_name | |
main.rs | continue;
}
let hash_get = hash.get_mut(tag);
match hash_get {
None => {
let vec = vec!(last_word);
hash.insert(tag, vec);
}
Some(vec) => {
if vec.len() >= 10 {continue;}
vec.push(last... | i = i + 1;
// 奇数列为word, 偶数列为tag
if i % 2 != 0 {
last_word = tag; | random_line_split | |
main.rs | _sentance = sentance!(
[element="Who"][word="是"][element= "Adjective"][word="的"][element="Adjective"][element="IntranstiveVerb"][word="器."]
);
for _ in 1..255 {
let mut sentance = generic_sentance.clone();
sentance.resolve_sentance(&mut resolver, &directionary);
let output = sent... | &new_word, matcher_result);
match matcher_result {
Some(element_vec) => {
for element in element_vec{
let library_result = self.library.get_mut(element.as_str());
match library_result {
Some(ele_vec) => {
... | identifier_body | |
users.py | from galaxy.web.base.controller import BaseAPIController
from galaxy.web.base.controller import CreatesApiKeysMixin
from galaxy.web.base.controller import CreatesUsersMixin
from galaxy.web.base.controller import UsesTagsMixin
log = logging.getLogger( __name__ )
class UserAPIController( BaseAPIController, UsesTagsMix... | from galaxy.security.validate_user_input import validate_email
from galaxy.security.validate_user_input import validate_password
from galaxy.security.validate_user_input import validate_publicname
from galaxy.web import _future_expose_api as expose_api
from galaxy.web import _future_expose_api_anonymous as expose_api_a... | random_line_split | |
users.py | name
from galaxy.web import _future_expose_api as expose_api
from galaxy.web import _future_expose_api_anonymous as expose_api_anonymous
from galaxy.web.base.controller import BaseAPIController
from galaxy.web.base.controller import CreatesApiKeysMixin
from galaxy.web.base.controller import CreatesUsersMixin
from galax... |
# ...and is logged in - return full
else:
user = trans.user
else:
user = self.get_user( trans, id, deleted=deleted )
# check that the user is requesting themselves (and they aren't del'd) unless admin
if not trans.... | item = self.anon_user_api_value( trans )
return item | conditional_block |
users.py | name
from galaxy.web import _future_expose_api as expose_api
from galaxy.web import _future_expose_api_anonymous as expose_api_anonymous
from galaxy.web.base.controller import BaseAPIController
from galaxy.web.base.controller import CreatesApiKeysMixin
from galaxy.web.base.controller import CreatesUsersMixin
from galax... | ( BaseAPIController, UsesTagsMixin, CreatesUsersMixin, CreatesApiKeysMixin ):
def __init__(self, app):
super(UserAPIController, self).__init__(app)
self.user_manager = users.UserManager(app)
self.user_serializer = users.UserSerializer( app )
self.user_deserializer = users.UserDeseri... | UserAPIController | identifier_name |
users.py | expose_api
from galaxy.web import _future_expose_api_anonymous as expose_api_anonymous
from galaxy.web.base.controller import BaseAPIController
from galaxy.web.base.controller import CreatesApiKeysMixin
from galaxy.web.base.controller import CreatesUsersMixin
from galaxy.web.base.controller import UsesTagsMixin
log =... | """
DELETE /api/users/{id}
delete the user with the given ``id``
:param id: the encoded id of the user to delete
:type id: str
:param purge: (optional) if True, purge the user
:type purge: bool
"""
if not trans.app.config.allow_user_deletion:
... | identifier_body | |
requestpool.go | indicates that the batch cannot be increased further by calling again with the same arguments.
func (rp *Pool) NextRequests(maxCount int, maxSizeBytes uint64, check bool) (batch [][]byte, full bool) {
rp.lock.Lock()
defer rp.lock.Unlock()
if check {
if (len(rp.existMap) < maxCount) && (rp.sizeBytes < maxSizeByte... | {
rp.logger.Debugf("Request %s auto-remove timeout expired, going to remove from pool", reqInfo)
if err := rp.RemoveRequest(reqInfo); err != nil {
rp.logger.Errorf("Removal of request %s failed; error: %s", reqInfo, err)
return
}
rp.metrics.CountOfDeleteRequestPool.Add(1)
rp.timeoutHandler.OnAutoRemoveTimeout(... | identifier_body | |
requestpool.go | for a semaphore with a lock, as it will prevent draining the pool.
if err := rp.semaphore.Acquire(ctx, 1); err != nil {
rp.metrics.CountOfFailAddRequestToPool.With(
rp.metrics.LabelsForWith(api.NameReasonFailAdd, api.ReasonSemaphoreAcquireFail)...,
).Add(1)
return errors.Wrapf(err, "acquiring semaphore for r... | random_line_split | ||
requestpool.go | ForwardTimeout time.Duration
ComplainTimeout time.Duration
AutoRemoveTimeout time.Duration
RequestMaxBytes uint64
SubmitTimeout time.Duration
Metrics *api.MetricsRequestPool
}
// NewPool constructs new requests pool
func NewPool(log api.Logger, inspector api.RequestInspector, th RequestTimeou... |
}
count := minInt(rp.fifo.Len(), maxCount)
var totalSize uint64
batch = make([][]byte, 0, count)
element := rp.fifo.Front()
for i := 0; i < count; i++ {
req := element.Value.(*requestItem).request
reqLen := uint64(len(req))
if totalSize+reqLen > maxSizeBytes {
rp.logger.Debugf("Returning batch of %d re... | {
return nil, false
} | conditional_block |
requestpool.go | ForwardTimeout time.Duration
ComplainTimeout time.Duration
AutoRemoveTimeout time.Duration
RequestMaxBytes uint64
SubmitTimeout time.Duration
Metrics *api.MetricsRequestPool
}
// NewPool constructs new requests pool
func NewPool(log api.Logger, inspector api.RequestInspector, th RequestTimeou... | () int {
rp.lock.Lock()
defer rp.lock.Unlock()
return len(rp.existMap)
}
// NextRequests returns the next requests to be batched.
// It returns at most maxCount requests, and at most maxSizeBytes, in a newly allocated slice.
// Return variable full indicates that the batch cannot be increased further by calling ag... | Size | identifier_name |
crawl_stations_data_and_update_tb.py | is set no other '
'argument is considered.'
)
parser.add_argument(
'-i', '--input-stations-file', dest='input_stations_file', type=is_valid_file, required=False, default=None,
help='File with a list of desired INMET stations (one name per row). Fetch all available stations data ' ... |
def get_station(cfg_params, station_name):
current_device_id = ''
# first get the device id
while True:
try:
api_response = device_controller_api_inst.get_tenant_device_using_get(station_name)
current_device_id = api_response.id.id
except ApiException as e:
... | relation_search_parameters = swagger_client.RelationsSearchParameters(
root_id=cfg_params['tb_entities_access']['root_asset_id'], root_type='ASSET', direction='FROM', max_level=0)
query = swagger_client.DeviceSearchQuery(device_types=['automatic-station'], parameters=relation_search_parameters,
... | identifier_body |
crawl_stations_data_and_update_tb.py | is set no other '
'argument is considered.'
)
parser.add_argument(
'-i', '--input-stations-file', dest='input_stations_file', type=is_valid_file, required=False, default=None,
help='File with a list of desired INMET stations (one name per row). Fetch all available stations data ' ... | ts_utc = int(calendar.timegm(time_tuple_utc)) * 1000
json_temp = {'unavailable_data': ''}
# adjust data types
for key, value in current_data.iteritems():
if key in ['hora', 'vento_vel', 'umid_max', 'umid_min', 'umid_inst']:
try:
json_temp[k... | if i == 0:
most_recent_data = current_data['data'].replace('/','-')
# convert current datetime to timestamp
date = current_data['data'].split('/')
time_tuple_utc = (int(date[2]), int(date[1]), int(date[0]), int(current_data['hora']), 0, 0) | random_line_split |
crawl_stations_data_and_update_tb.py | r
def set_station_attributes(station_token, attributes):
# set station attributes
while True:
try:
api_response = device_api_controller_api_inst.post_device_attributes_using_post(station_token, attributes)
except ApiException as e:
if (json.loads(e.body)['message'] == '... | start_date = station_attributes['mostRecentData'] | conditional_block | |
crawl_stations_data_and_update_tb.py | set no other '
'argument is considered.'
)
parser.add_argument(
'-i', '--input-stations-file', dest='input_stations_file', type=is_valid_file, required=False, default=None,
help='File with a list of desired INMET stations (one name per row). Fetch all available stations data ' +
... | (station_token, station_data):
# load station data
reader = csv.reader(station_data)
keys = reader.next()
# iterate over data collects
for i, row_of_values in enumerate(reader, start = 0):
current_data = dict(zip(keys, row_of_values))
most_recent_data = ''
# get date from the... | load_station_data | identifier_name |
virtio_constants.rs | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* VirtIO Header, located in BAR 0.
*/
pub const VIRTIO_PCI_HOST_FEATURES: u64 = 0; /* host'... | pub const VIRTIO_NET_F_STATUS: usize = 16; /* virtio_net_config.status available */
pub const VIRTIO_NET_F_CTRL_VQ: usize = 17; /* Control channel available */
pub const VIRTIO_NET_F_CTRL_RX: usize = 18; /* Control channel RX mode support */
pub const VIRTIO_NET_F_CTRL_VLAN: usize = 1... | random_line_split | |
virtio_constants.rs | 12;
/* This marks a buffer as continuing via the next field. */
pub const VIRTQ_DESC_F_NEXT: u16 = 1;
/* This marks a buffer as write-only (otherwise read-only). */
pub const VIRTQ_DESC_F_WRITE: u16 = 2;
/* This means the buffer contains a list of buffer descriptors. */
pub const VIRTQ_DESC_... | from | identifier_name | |
debugging_errors.py | errors occur when Python was expecting something to be have a certain indentation level but instead encountered something different. Remember, Python cares about whitespace, so if you fail to adhere to what Python is expecting, you will get an `IndentationError`.
# will produce a syntax error
# and specifically an in... |
### `try`/`except` Block
The general structure of a `try`/`except` blog is as follows:
```python
try:
# Tries to do this code
pass # pass just says is not an operation; carry on
except:
# If there is an error (an exception), keep going and do this instead
pass
```
For example, if, we wanted to ask t... |
While *syntax errors* will necessarily fail, *exceptions* do not necessarily have to lead to breaking the program - they can be programmatically dealt with, using `try` and `except`. A `try`/`except` block allows you to try some code. If, in attempting to execute that code, an exeption is encountered, Python will inst... | random_line_split |
debugging_errors.py |
Well, to answer this question you could consider the following call of the function:
example_function([1, 2, 3, 4])
The above example of the function executes and returns the value 14, the sum of all the values in the input list plus the value stored in the fourth position of the input list.
But, what about the f... | running_sum = 0
for item in input_list:
running_sum = running_sum + item
special_value = input_list[3]
return running_sum + special_value | conditional_block | |
main.rs | u64, frames: u64) -> u64 {
buffer_const_size(align) + buffer_frame_size(align) * frames
}
const fn uniform_offset(index: usize, align: u64) -> u64 {
buffer_const_size(align) + buffer_frame_size(align) * index as u64
}
const fn per_instance_offset(index: usize, align: u64) -> u64 {
uniform_offset(index, ali... |
Ok(MeshRenderPipeline {
align,
buffer,
sets,
})
}
}
fn model_transform() -> nalgebra::Matrix4<f32> {
let rot = nalgebra::UnitQuaternion::identity();
nalgebra::Similarity3::from_parts(Vector3::new(0.5, 0.5, 0.0).into(), rot, 0.5).into()
}
fn model_trans... | {
// println!(
// "upload const: {}",
// std::mem::size_of::<PerInstanceConst>() * scene.per_instance_const.len()
// );
unsafe {
factory
.upload_visible_buffer(&mut buffer, 0, &scene.per_instance_const[..])
... | conditional_block |
main.rs | .limits()
.min_uniform_buffer_offset_alignment;
let mut buffer = factory
.create_buffer(
BufferInfo {
size: buffer_size(align, frames) as u64,
usage: hal::buffer::Usage::UNIFORM
| hal::buffer::Usage::INDIRE... | random_line_split | ||
main.rs |
const fn buffer_const_size(align: u64) -> u64 {
align_to(PER_INSTANCE_CONST_SIZE * NUM_INSTANCES, align)
}
const fn buffer_frame_size(align: u64) -> u64 {
align_to(UNIFORM_SIZE + PER_INSTANCE_SIZE * NUM_INSTANCES, align)
}
const fn buffer_size(align: u64, frames: u64) -> u64 {
buffer_const_size(align) + bu... | {
((s - 1) / align + 1) * align
} | identifier_body | |
main.rs | : u64, frames: u64) -> u64 {
buffer_const_size(align) + buffer_frame_size(align) * frames
}
const fn | (index: usize, align: u64) -> u64 {
buffer_const_size(align) + buffer_frame_size(align) * index as u64
}
const fn per_instance_offset(index: usize, align: u64) -> u64 {
uniform_offset(index, align) + UNIFORM_SIZE
}
#[derive(Debug, Default)]
struct MeshRenderPipelineDesc;
#[derive(Debug)]
struct MeshRenderPipe... | uniform_offset | identifier_name |
catalog.rs | new();
map.insert(TIMESTAMP_COLUMN, ts_column);
map.insert(1, source_column);
self.ensure_columns(map)
}
pub fn with_data<P: AsRef<Path>>(root: P) -> Result<Catalog<'cat>> {
let root = root.as_ref().to_path_buf();
let meta = root.join(CATALOG_METADATA);
Catalo... | let meta = meta.as_ref();
if !meta.exists() { | random_line_split | |
catalog.rs | _METADATA);
if meta.exists() {
bail!("Catalog metadata already exists {:?}", meta);
}
let mut catalog = Catalog {
colmap: Default::default(),
groups: Default::default(),
indexes: Default::default(),
data_root: root,
};
... |
fn prepare_partition_groups<P, I>(root: P, ids: I) -> Result<PartitionGroupMap<'cat>>
where
P: AsRef<Path>,
I: IntoIterator<Item = SourceId>,
{
ids.into_iter()
.map(|source_id| {
let path = PartitionGroupManager::new(&root, source_id).with_context(|_| {
... | {
let _ = self.ensure_group(source_id)?;
Ok(())
} | identifier_body |
catalog.rs | _METADATA);
if meta.exists() {
bail!("Catalog metadata already exists {:?}", meta);
}
let mut catalog = Catalog {
colmap: Default::default(),
groups: Default::default(),
indexes: Default::default(),
data_root: root,
};
... | (&mut self) -> Result<()> {
let ts_column = Column::new(BlockStorage::Memmap(BlockType::U64Dense), "timestamp");
let source_column = Column::new(BlockStorage::Memory(BlockType::I32Dense), "source_id");
let mut map = HashMap::new();
map.insert(TIMESTAMP_COLUMN, ts_column);
map.ins... | ensure_default_columns | identifier_name |
catalog.rs | _METADATA);
if meta.exists() {
bail!("Catalog metadata already exists {:?}", meta);
}
let mut catalog = Catalog {
colmap: Default::default(),
groups: Default::default(),
indexes: Default::default(),
data_root: root,
};
... |
}
self.ensure_columns(column_map)
}
/// Extend internal index map without any sanitization checks.
///
/// This function uses `std::iter::Extend` internally,
/// so it allows redefinition of a index type.
/// Also, the index' support for a given column is not checked.
/// ... | {
bail!("Column Name already exists '{}'", column.name);
} | conditional_block |
ViewTrajectories.py | "GREEN", "SALMON", "VIOLET"]
CurrentColor = [0]
def GetColor():
color = colorlist[CurrentColor[0]]
CurrentColor[0] += 1
if CurrentColor[0] > len(colorlist):
CurrentColor[0] = 0
return color
def EVT_NEW_FRAME_EVENT( window, function ):
window.Connect( -1, -1, NEW_FRAME_EVENT, function )
... | dlg.Destroy()
class TrajectoryViewer(wx.App):
""" | random_line_split | |
ViewTrajectories.py | IT_MENU = wx.NewId()
ID_DRAWTEST_MENU = wx.NewId()
ID_DRAWMAP_MENU = wx.NewId()
ID_CLEAR_MENU = wx.NewId()
ID_SET_FRAMERATE_MENU = wx.NewId()
ID_OPEN = wx.NewId()
ID_RUN_MOVIE = wx.NewId()
ID_RUNONTOP_MOVIE = wx.NewId()
ID_RERUN_MOVIE = wx.NewId()
ID_PAUSE_BUTTON = wx.NewId()
colorlist = ["BLACK", "RED", "CYAN", "GRE... | (self,event):
self.Close(True)
def OnCloseWindow(self, event):
self.Destroy()
def RunMovie(self,event = None):
import RandomArray
start = clock()
shift = RandomArray.randint(0,0,(2,))
NumFrames = 50
for i in range(NumFrames):
... | OnQuit | identifier_name |
ViewTrajectories.py | IT_MENU = wx.NewId()
ID_DRAWTEST_MENU = wx.NewId()
ID_DRAWMAP_MENU = wx.NewId()
ID_CLEAR_MENU = wx.NewId()
ID_SET_FRAMERATE_MENU = wx.NewId()
ID_OPEN = wx.NewId()
ID_RUN_MOVIE = wx.NewId()
ID_RUNONTOP_MOVIE = wx.NewId()
ID_RERUN_MOVIE = wx.NewId()
ID_PAUSE_BUTTON = wx.NewId()
colorlist = ["BLACK", "RED", "CYAN", "GRE... |
print "running the movie took %f seconds to disply % | points = self.LEs.Points
shift = RandomArray.randint(-5,5,(2,))
points += shift
self.LEs.SetPoints(points)
self.Canvas.Draw() | conditional_block |
ViewTrajectories.py | _FRAME_EVENT( window, function ):
window.Connect( -1, -1, NEW_FRAME_EVENT, function )
class FrameEvent(wx.PyEvent):
def __init__(self):
wx.PyEvent.__init__(self)
self.SetEventType(NEW_FRAME_EVENT)
class DrawFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__... | frame = DrawFrame(None, title="Trajectory Viewer", size=(700,700))
self.SetTopWindow(frame)
return True | identifier_body | |
cluster_instances.js | </b>";
}
if ("SLAVE" == value) {
if (row.slaveof) {
return "└";
}
}
return "";
}
function instanceStatusFormatter(value) {
if ("STARTED" == value) {
return "运行中";
}
if ("STOPPED" == value) {
return "已停止";
}
return "未运行";
}
function instan... | type: "PATCH",
url: "/" + command + "/instances",
data: JSON.stringify(servers),
contentType: "application/json",
success: function () {
table.bootstrapTable('refresh');
unblockUI();
}
});
}
function delClusterNodes() {
var table = $('#red... | ction (row) {
if (row["status"].toLowerCase().indexOf(command) != -1) {
hasError = true;
return;
}
return row.id;
});
if (hasError) {
alert("无法重复操作已开启或停止的服务器!");
return;
}
if (servers.length < 1) {
alert("请至少选择一项!");
retur... | identifier_body |
cluster_instances.js | 节点</b>";
}
if ("SLAVE" == value) {
if (row.slaveof) {
return "└";
}
}
return "";
}
function instanceStatusFormatter(value) {
if ("STARTED" == value) {
return "运行中";
}
if ("STOPPED" == value) {
return "已停止";
}
return "未运行";
}
function inst... | success: function (data) {
if (!data || data.length == 0) {
alert("未找到匹配的节点,请重试或检查主机状态!");
return;
}
var msg = "";
for (var i = 0; i < data.length; i++) {
node = data[i];
if (node.slotRanges.length) {... | data: JSON.stringify(servers),
dataType: "json",
contentType: "application/json",
async: false, | random_line_split |
cluster_instances.js | </b>";
}
if ("SLAVE" == value) {
if (row.slaveof) {
return "└";
}
}
return "";
}
function instanceStatusFormatter(value) {
if ("STARTED" == value) {
return "运行中";
}
if ("STOPPED" == value) {
return "已停止";
}
return "未运行";
}
function instan... | alert("未找到匹配的节点,请重试或检查主机状态!");
return;
}
var msg = "";
for (var i = 0; i < data.length; i++) {
node = data[i];
if (node.slotRanges.length) {
msg += "[" + node.ip + ":" + node.port + "],";
... | || data.length == 0) {
| identifier_name |
cluster_instances.js | ) {
if ("MASTER" == value) {
return "<b>主节点</b>";
}
if ("SLAVE" == value) {
if (row.slaveof) {
return "└";
}
}
return "";
}
function instanceStatusFormatter(value) {
if ("STARTED" == value) {
return "运行中";
}
if ("STOPPED" == value) {
r... | Password").val('');
}
}
function cacheSizeFormatter(value) {
return value + 'GB';
}
function instanceRoleFormatter(value, row, index, field | conditional_block | |
debug-trace-player.ts | // Tracks all the data slots which have been touched during the current step.
private dirtyMask: boolean[] = [];
// Tracks all the data slots which hold function return values.
private returnValues: boolean[] = [];
// Tracks line numbers that have breakpoints set on them.
private breakpointLines: Set<numb... | (): boolean {
return this.breakpointLines.has(this.getCurrentLine());
}
/** Replaces all current breakpoints with a new set of them. */
public setBreakpoints(breakpointLines: Set<number>): void {
this.breakpointLines = breakpointLines;
}
/** Returns the current set of lines which have a breakpoint. ... | atBreakpoint | identifier_name |
debug-trace-player.ts | // Tracks all the data slots which have been touched during the current step.
private dirtyMask: boolean[] = [];
// Tracks all the data slots which hold function return values.
private returnValues: boolean[] = [];
// Tracks line numbers that have breakpoints set on them.
private breakpointLines: Set<numb... |
/** Returns a slot's component as a variable-name suffix, e.g. ".x" or "[2][2]". */
public getSlotComponentSuffix(slotIndex: number): string {
const slot: SlotInfo = this.trace!.slots[slotIndex];
if (slot.rows > 1) {
return `[${Math.floor(slot.index / slot.rows)}][${
slot.index % slot.rows
... | {
this.check(this.stack.length > 0);
return this.stack.length - 1;
} | identifier_body |
debug-trace-player.ts | Throws an error if a precondition is not met. Indicates a logic bug or invalid trace. */
private check(result: boolean): void {
if (!result) {
throw new Error('check failed');
}
}
/** Copies trace info from the JSON number array into a TraceInfo struct. */
private getTraceInfo(position: number):... | {
return delta;
} | conditional_block | |
debug-trace-player.ts | ();
/** Throws an error if a precondition is not met. Indicates a logic bug or invalid trace. */
private check(result: boolean): void {
if (!result) {
throw new Error('check failed');
}
}
/** Copies trace info from the JSON number array into a TraceInfo struct. */
private getTraceInfo(position... | if (delta !== 0) {
return delta; | random_line_split | |
lstm_predictor.py |
def add_input_layer(self,):
l_in_x = tf.reshape(self.xs, [-1, self.input_size], name='2_2D') # (batch*n_step, in_size)
# Ws (in_size, cell_size)
Ws_in = self._weight_variable([self.input_size, self.cell_size])
# bs (cell_size, )
bs_in = self._bias_variable([self.cell_size,... | self.n_steps = n_steps
self.input_size = input_size
self.output_size = output_size
self.cell_size = cell_size
self.batch_size = batch_size
self.learning_rate = LR
self.x_vx_mode = x_vx_mode
with tf.name_scope('inputs'):
self.xs = tf.placeholder(tf.floa... | identifier_body | |
lstm_predictor.py | (tf.float32, [batch_size, None, input_size], name='xs')
self.ys = tf.placeholder(tf.float32, [batch_size, None, output_size], name='ys')
with tf.variable_scope('in_hidden'):
self.add_input_layer()
with tf.variable_scope('LSTM_cell'):
self.add_cell()
with tf.va... | # return [h, w, area, x]
# return [h, w, area, area_dao]
return [h, w, area]
def extract_sample(self, filename, time_file):
with open(filename) as fin:
gts = json.loads(fin.read())['frame_data']
# t_samples = [extract_bbox(e['ref_bbox'])] for e in gts]
t_... | w = (b[2] - b[0] + 1.) / self.WIDTH
area = h * w
# x, y = bird_proj.proj((b['left'] + b['right'])/2, b['bot'])
| random_line_split |
lstm_predictor.py | )
with tf.name_scope('initial_state'):
self.cell_init_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)
self.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(
lstm_cell, self.l_in_y, initial_state=self.cell_init_state, time_major=False)
def add_output_... | lstm_process | identifier_name | |
lstm_predictor.py | self.l_in_y = tf.reshape(l_in_y, [self.batch_size, -1, self.cell_size], name='2_3D')
def add_cell(self):
lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size, forget_bias=1.0, state_is_tuple=True)
# lstm_cell = tf.contrib.rnn.MultiRNNCell(
# [lstm_cell() for _ in range(3)], state_i... | self.result[i]['vx'] = vx | conditional_block | |
credentials.rs | 8, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 4, 166, 48, 130, 4,
162, 2, 1, 0, 2, 130, 1, 1, 0, 147, 110, 223, 81, 179, 105, 226, 200, 132, 68, 20, 135, 107, 132, 131, 123,
231, 183, 170, 255, 84, 114, 253, 88, 89, 0, 176, 87, 2, 247, 160, 250, 91, 126, 186, 47, 253, 16, 1... | deserialize_credentials | identifier_name | |
credentials.rs | #[derive(Serialize, Deserialize, Default, Clone)]
pub struct Credentials {
pub project_id: String,
pub private_key_id: String,
pub private_key: String,
pub client_email: String,
pub client_id: String,
pub api_key: String,
#[serde(default, skip)]
pub(crate) keys: Keys,
}
/// Converts a P... | /// # Ok::<(), firestore_db_and_auth::errors::FirebaseError>(())
/// | /// c.add_jwks_public_keys(&JWKSet::new(include_str!("../tests/service-account-test.jwks"))?);
/// c.compute_secret()?;
/// c.verify()?; | random_line_split |
credentials.rs | 132, 131, 123,
231, 183, 170, 255, 84, 114, 253, 88, 89, 0, 176, 87, 2, 247, 160, 250, 91, 126, 186, 47, 253, 16, 123, 88, 60,
145, 245, 3, 211, 114, 200, 12, 2, 134, 205, 20, 9, 21, 170, 146, 65, 40, 2, 107, 115, 225, 210, 80, 213, 137,
70, 139, 79, 193, 26, 18, 182, 150,
];
assert_eq... | {
let jwk_list = JWKSet::new(include_str!("../tests/service-account-test.jwks")).unwrap();
let c: Credentials = Credentials::new(include_str!("../tests/service-account-test.json"))
.expect("Failed to deserialize credentials")
.with_jwkset(&jwk_list)
.expect("JWK public keys verification ... | identifier_body | |
credentials.rs | ,
pub api_key: String,
#[serde(default, skip)]
pub(crate) keys: Keys,
}
/// Converts a PEM (ascii base64) encoded private key into the binary der representation
pub fn pem_to_der(pem_file_contents: &str) -> Result<Vec<u8>, Error> {
use base64::decode;
let pem_file_contents = pem_file_contents
... | {
continue;
} | conditional_block | |
zcooldl.py | =resp.json().get('data', {}).get('content'),
offset=page_size * (page - 1))
# 根据用户 ID 或用户名下载
else:
self.user_id = user_id or self.search_id_by_username(username)
self.base_url = urljoin(HOST_PAGE, USER_SUFFIX.format(id=self.user_id))
... | ages.put(new_scrapy)
self.stat["nimages"] += 1
return scrapy
def fetch_images(self):
"""从任务队列中获取要爬取的主题,使用多线程处理得到需要下载的图片。"""
image_futures = {}
while True:
try:
scrapy = self.topics.get(timeout=Q_TIMEOUT)
image_futures[self.... | identifier_body | |
zcooldl.py | connect to proxy.', 'red')
sys.exit(1)
except Exception as e:
cprint(f'Failed to connect to {search_url}, {e}', 'red')
sys.exit(1)
author_1st = BeautifulSoup(response.text, 'html.parser').find(name='div', class_='author-info')
if (not author_1st) or (author_... | scrapy):
"""下载图片保存到本地。
| conditional_block | |
zcooldl.py | .overwrite = overwrite
self.thumbnail = thumbnail
self.pages = Queue()
self.topics = Queue()
self.images = Queue()
self.stat = {
'npages': 0,
'ntopics': 0,
'nimages': 0,
'pages_pass': set(),
'pages_fail': set(),
... | :return Scrapy: 记录任务信息的数据体
"""
resp = session_request(scrapy.url)
cards = BeautifulSoup(resp.text, 'html.parser').find_all(name='a', class_='card-img-hover')
for idx, card in enumerate(cards if self.max_topics == 'all' else cards[:self.max_topics + 1]):
title = card.g... |
def parse_topics(self, scrapy):
"""爬取主页,解析所有 topic,并将爬取主题的任务添加到任务队列。
:param scrapy: 记录任务信息的数据体 | random_line_split |
zcooldl.py | """
resp = session_request(scrapy.url)
cards = BeautifulSoup(resp.text, 'html.parser').find_all(name='a', class_='card-img-hover')
for idx, card in enumerate(cards if self.max_topics == 'all' else cards[:self.max_topics + 1]):
title = card.get('title')
if self.spec_topic... | whil | identifier_name | |
script.js | Canada",
paragraphs : [
"Озеро Морейн підживлюється льодовиком і досягає свого повного наповнення лише у другій половині червня. Головною принадою озера Морейн є синій колір води. Коли воно наповнене, в ньому відбиваються різні відтінки синього кольору через заломлення світла на кам'янистому дні ... | identifier_body | ||
script.js | Canada",
paragraphs : [
"Озеро Морейн підживлюється льодовиком і досягає свого повного наповнення лише у другій половині червня. Головною принадою озера Морейн є синій колір води. Коли воно наповнене, в ньому відбиваються різні відтінки синього кольору через заломлення світла на кам'янистому дні ... | identifier_name | ||
script.js | ться лише у спеціальному спелеологічному спорядженні. Мавпа печера – має найбільшу протяжність серед лавових печер США – майже 400 метрів."
]
},
{
title : "Канада",
subtitle : "Озеро Морейн",
imgSrc : "images/Moraine_Lake_Canada.jpg",
imgAlt : "Moraine Lake Canada"... | parrentMenuWrap.addEventListener('click', e => {
let index = +e.target.getAttribute("data-number");
| random_line_split | |
reco_tracks.py | _ID
from modules.reco import config, plot
from modules.analysis import config as CONFIGURATION
import os
import itertools
import bokeh
import numpy as np
############################################# INPUT ARGUMENTS
import argparse
parser = argparse.ArgumentParser(description='Track reconstruction from input hits.')
... | (input_files):
"""Reconstruct tracks from hits in all events from the provided input files"""
n_words_event = len(OUT_CONFIG['event']['fields'])
n_words_hit = len(OUT_CONFIG[args.format]['fields'])
# Initialising event
event = -1
G = Geometry(CONFIGURATION)
H = HitManager()
SLs = {}
... | process | identifier_name |
reco_tracks.py | _ID
from modules.reco import config, plot
from modules.analysis import config as CONFIGURATION
import os
import itertools
import bokeh
import numpy as np
############################################# INPUT ARGUMENTS
import argparse
parser = argparse.ArgumentParser(description='Track reconstruction from input hits.')
... | for line in file_in:
file_line_nr += 1
if file_line_nr <= 1:
continue
hits_lst = []
H.reset()
words = line.strip().split()
event = int(words[0])
# Skipping event if it was not ... | """Reconstruct tracks from hits in all events from the provided input files"""
n_words_event = len(OUT_CONFIG['event']['fields'])
n_words_hit = len(OUT_CONFIG[args.format]['fields'])
# Initialising event
event = -1
G = Geometry(CONFIGURATION)
H = HitManager()
SLs = {}
for iSL in config.S... | identifier_body |
reco_tracks.py | _ID
from modules.reco import config, plot
from modules.analysis import config as CONFIGURATION
import os
import itertools
import bokeh
import numpy as np
############################################# INPUT ARGUMENTS
import argparse
parser = argparse.ArgumentParser(description='Track reconstruction from input hits.')
... | file_line_nr += 1
if file_line_nr <= 1:
continue
hits_lst = []
H.reset()
words = line.strip().split()
event = int(words[0])
# Skipping event if it was not specified in command line
... | with open(file_path, 'r') as file_in:
file_line_nr = 0
for line in file_in: | random_line_split |
reco_tracks.py | _ID
from modules.reco import config, plot
from modules.analysis import config as CONFIGURATION
import os
import itertools
import bokeh
import numpy as np
############################################# INPUT ARGUMENTS
import argparse
parser = argparse.ArgumentParser(description='Track reconstruction from input hits.')
... | # Getting XY coordinates of the global segment for the current view
iX = COOR_ID[view[0]]
posx = [start[iX], end[iX]]
posy = [start[2], end[2]]
# Drawing the se... | for view, sls in GLOBAL_VIEW_SLs.items():
sl_ids = [sl.id for sl in sls]
hits_sls = H.hits.loc[H.hits['sl'].isin(sl_ids)]
figs['global'][view].square(x=hits_sls['glpos'+view[0]], y=hits_sls['glpos'+view[1]],
... | conditional_block |
params.pb.go | else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ConnParameters) XXX_Merge(src proto.Message) {
xxx_messageInfo_ConnParameters.Merge(m, src)
}
func (m *ConnParameters) XXX_Size() int {
return m.Size()
}
func (m *ConnParameters) XXX_DiscardU... | {
return xxx_messageInfo_ConnParameters.Marshal(b, m, deterministic)
} | conditional_block | |
params.pb.go | []string {
if m != nil {
return m.Upgrades
}
return nil
}
func init() {
proto.RegisterType((*ConnParameters)(nil), "core.go.ConnParameters")
}
func init() { proto.RegisterFile("params.proto", fileDescriptor_8679b07c520418a1) }
var fileDescriptor_8679b07c520418a1 = []byte{
// 182 bytes of a gzipped FileDescri... | () (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.PingInterval != 0 {
n += 1 + sovParams(uint64(m.PingInterval))
}
if m.PingTimeout != 0 {
n += 1 + sovParams(uint64(m.PingTimeout))
}
l = len(m.SID)
if l > 0 {
n += 1 + l + sovParams(uint64(l))
}
if len(m.Upgrades) > 0 {
for _, s := range m... | Size | identifier_name |
params.pb.go | return 0
}
func (m *ConnParameters) GetSID() string {
if m != nil {
return m.SID
}
return ""
}
func (m *ConnParameters) GetUpgrades() []string {
if m != nil {
return m.Upgrades
}
return nil
}
func init() {
proto.RegisterType((*ConnParameters)(nil), "core.go.ConnParameters")
}
func init() { proto.Registe... |
func (m *ConnParameters) GetPingTimeout() int64 {
if m != nil {
return m.PingTimeout
} | random_line_split | |
params.pb.go |
var xxx_messageInfo_ConnParameters proto.InternalMessageInfo
func (m *ConnParameters) GetPingInterval() int64 {
if m != nil {
return m.PingInterval
}
return 0
}
func (m *ConnParameters) GetPingTimeout() int64 {
if m != nil {
return m.PingTimeout
}
return 0
}
func (m *ConnParameters) GetSID() string {
if... | {
xxx_messageInfo_ConnParameters.DiscardUnknown(m)
} | identifier_body | |
main.rs | .zs.push(s.p.2);
me.rsqrds.push(s.rsqrd);
me.mats.push(s.m);
}
// pad everything out to the simd width
me.xs.resize(len, 0.0);
me.ys.resize(len, 0.0);
me.zs.resize(len, 0.0);
me.rsqrds.resize(len, 0.0);
let default_mat = Material {
... | {
let a = randf_range(rng_state, 0.0, 2.0 * PI);
let z = randf_range(rng_state, -1.0, 1.0);
let r = (1.0 - z * z).sqrt();
V3(r * a.cos(), r * a.sin(), z)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.