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
cfg_simulator.py
For the categorical model, this limits the upper bound of the learned throttle #it's very IMPORTANT that this value is matched from the training PC config.py and the robot.py #and ideally wouldn't change once set. MODEL_CATEGORICAL_MAX_THROTTLE_RANGE = 0.8 #RNN or 3D SEQUENCE_LENGTH = 3 #some models use a ...
#Path following PATH_FILENAME = "donkey_path.pkl" # the path will be saved to this filename PATH_SCALE = 5.0 # the path display will be scaled by this factor in the web page PATH_OFFSET = (0, 0) # 255, 255 is the center of the map. This offset controls where the origin is displayed. ...
random_line_split
index.js
// console.log(part.itemId, item.stItemInfo); // 反查完成的成就小id let achiReqList = achiReqTable.filter(o => o.fashionId === part.fashionId); // todo 有空的 // todo 保存6464小icon let hash = getHash(`DATA\\IMAGESETS\\ICONS\\ITEMTIPSICON\\${item.szTIPS2D}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; ...
data[1]; itemTable = data[2]; achiReqTable = data[3]; achiTable = data[4]; // 新增坐骑 itemTable = itemTable.concat(data[5]); // todo 是否可以染色 let partRes = {}; let setRes = {}; let glamourRes = {}; let dyeRes = {}; let dyesumRes = {}; // 以主表开始遍历 fashionTable.forEach(part => { // 查item表提数据 ...
identifier_body
index.js
Table = data[1]; itemTable = data[2]; achiReqTable = data[3]; achiTable = data[4]; // 新增坐骑 itemTable = itemTable.concat(data[5]); // todo 是否可以染色 let partRes = {}; let setRes = {}; let glamourRes = {}; let dyeRes = {}; let dyesumRes = {}; // 以主表开始遍历 fashionTable.forEach(part => { // 查it...
set
identifier_name
index.js
] = { pos: part.position, // 主表 suiyin: part.suiyin, // 主表 weight: part.weight, // 主表 itemId: part.itemId, // 主表 equipData: { name: item.stItemInfo, gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), menpai: item.JobDemand...
// 构造套装表 setTable.forEach(set => { // todo 保存三体型卡片 [set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => { let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`); let fullPath = `${imgSrcPath}${hash}.tga`; if(fs.existsSync(fullPath)) { ...
random_line_split
index.js
还分门派! // 身份、盟会职务不关键,全部显示 explain: item.szExplain, des: item.szBackground, icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有! type: item.ddCatDesc, }, achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id ...
menpai: -1, // 身份、盟会职务不关键,全部显示 explain: '使用后获得“心王·影冠”外装外形', des: '露凝香,玉笼烟。\\n谁共我,醉明月?', icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是只有男的 type: '外装', }, achiId: 24749, // 反查achievement request表,收集了该物品可以达成的成就小Id } }; // 全部套装 let exampleSets = { 328: { // 心王影套装id name:...
conditional_block
main.rs
device.get_device_queue(queue_family_index, 0) }; let mut events_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Ash - Example") .with_dimensions(winit::dpi::LogicalSize { width: WIDTH, height: HEIGHT, }) .build(&eve...
( entry: &Entry<V1_0>, instance: &Instance<V1_0>, window: &winit::Window, physical_device: PhysicalDevice, device: &Device<V1_0>, ) -> Result<(Swapchain, SwapchainKHR), vk::Result> { let surface = create_surface(entry, instance, window).unwrap(); let surface_loader = Surface::new(ent...
create_swapchain
identifier_name
main.rs
app_name = CString::new("Niagara-rs").unwrap(); let raw_name = app_name.as_ptr(); let appinfo = vk::ApplicationInfo { s_type: vk::StructureType::ApplicationInfo, api_version: vk_make_version!(1, 0, 36), p_application_name: raw_name, p_engine_name: raw_name, application_v...
random_line_split
main.rs
device.get_device_queue(queue_family_index, 0) }; let mut events_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Ash - Example") .with_dimensions(winit::dpi::LogicalSize { width: WIDTH, height: HEIGHT, }) .build(&eve...
fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> { let app_name = CString::new("Niagara-rs").unwrap(); let raw_name = app_name.as_ptr(); let appinfo = vk::ApplicationInfo { s_type: vk::StructureType::ApplicationInfo, api_version: vk_make_version!(1, 0, 36), p_application_n...
{ Entry::new().unwrap() }
identifier_body
tweetnacl.rs
(a: &mut Self, b: &mut Self, choice: Choice) { // what TweetNacl originally does // let mask: i64 = !(b - 1); // TweetNacl translated to Choice language // let mask: i64 = !(choice.unwrap_u8() as i64) - 1); // `subtle` definition, which is equivalent // let mask: i64 = -(...
conditional_swap
identifier_name
tweetnacl.rs
!=4) M(c,c,i); // } // FOR(a,16) o[a]=c[a]; // } fn inverse(&self) -> FieldElement { // TODO: possibly assert! that fe != 0? // make our own private copy let mut inverse = *self; // exponentiate with 2**255 - 21, // which by Fermat's little theorem is the sa...
assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes());
random_line_split
tweetnacl.rs
xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, ]); const EDWARDS_BASEPOINT_X: Self = Self([ 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169, ]); ...
} sqrt } } impl ConstantTimeEq for FieldElement { fn ct_eq(&self, other: &Self) -> Choice { let canonical_self = self.to_bytes(); let canonical_other = other.to_bytes(); canonical_self.ct_eq(&canonical_other) } } impl PartialEq for FieldElement { fn eq(&self,...
{ sqrt = &sqrt * self; }
conditional_block
tweetnacl.rs
0f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, ]); const EDWARDS_BASEPOINT_X: Self = Self([ 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169, ]); const EDWARDS_BASEPOINT_Y: Self = Self([ 0x6658,...
{ for (x, y) in self.0.iter_mut().zip(other.0.iter()) { *x -= y; } }
identifier_body
control.rs
= loop { let q = view.event_proc(cross); view = match q { // delegate to top-level control loop DelegateEvent::Quit | DelegateEvent::OpenDialog(_) => { quit = match &mut view { HexView::Aligned(v, _, _) => !v.process_es...
random_line_split
control.rs
= read_to_string(Self::settings_file().ok()?).ok()?; serde_json::from_str(&config).ok() } pub fn save_config(&self) -> Result<(), Box<dyn Error + 'static>> { let config = serde_json::to_string(self)?; let r = std::fs::create_dir_all(Self::config_path()?); if let Err(ref e) = r ...
{ sink.send(Box::new(|siv: &mut Cursive| { siv.call_on_name("aligned", |view: &mut Aligned| { view.process_action(&mut Dummy, otherwise); }) .expect("Could not send new data to view"); })) ...
conditional_block
control.rs
settings = settings_new; } } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct Settings { pub algo: AlignAlgorithm, pub style: Style, } impl Settings { fn config_path() -> Result<PathBuf, std::io::Error> { match std::env::var_os("BIODIFF_CONFIG_DIR") { Som...
cursiv_theme
identifier_name
print_test.py
D tensor after being normalized ''' mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2]) beta = tf.get_variable('beta', dimension, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32)) gamma = tf.get_variable('gamma', dimension, tf.float32, ...
DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False) with tf.variable_scope('DRN_5_2'): DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False) # [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作 with tf.variable_scope('DRN_6_1'): DRN_6 = residua...
DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_4_2'): DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False) with tf.variable_scope('DRN_5_1'):
random_line_split
print_test.py
_channel, output_channel]) conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') else: conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation) with tf.variable_scope('conv2_in_block'): conv2 =...
240×320×3 # label = tf.cast(label, tf.float32).eval() # print("label.dtype:", label.dtype) # uint8 # 开始转换一下生成结果 # 显示原始数据的分布是什么 i0 = Image.fromarray(label) # plt.figure(i+1) result = i0.show()
conditional_block
print_test.py
) if dilation == 1: conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') elif dilation == 2: conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME') elif dilation == 4: conv_layer = tf.nn.atrous_conv2...
# 解码
identifier_name
print_test.py
D tensor after being normalized ''' mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2]) beta = tf.get_variable('beta', dimension, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32)) gamma = tf.get_variable('gamma', dimension, tf.float32, ...
conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') else: conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation) with tf.variable_scope('conv2_in_block'): conv2 = bn_relu_conv_layer(conv1, [...
etwork :return: 4D tensor. ''' input_channel = input_layer.get_shape().as_list()[-1] # 按照正常的网络结构 # 我们选择先bath 然后进行卷积和relu的操作 # Y = conv(Relu(batch_normalize(X))) # bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1) ''' 设置残差网络的模板的第一层 ''' # 这里进行查看输入输出维度以...
identifier_body
push_active_set.rs
: &Pubkey, // This node. node: &Pubkey, // Gossip node. origins: &[Pubkey], // CRDS value owners. stakes: &HashMap<Pubkey, u64>, ) { let stake = stakes.get(pubkey); for origin in origins { if origin == pubkey { continue; } ...
} impl PushActiveSetEntry { const BLOOM_FALSE_RATE: f64 = 0.1; const BLOOM_MAX_BITS: usize = 1024 * 8 * 4; fn get_nodes<'a>( &'a self, origin: &'a Pubkey, // If true forces gossip push even if the node has pruned the origin. mut should_force_push: impl FnMut(&Pubkey) -> bo...
{ &self.0[get_stake_bucket(stake)] }
identifier_body
push_active_set.rs
: &Pubkey, // This node. node: &Pubkey, // Gossip node. origins: &[Pubkey], // CRDS value owners. stakes: &HashMap<Pubkey, u64>, ) { let stake = stakes.get(pubkey); for origin in origins { if origin == pubkey { continue; } ...
( &self, node: &Pubkey, // Gossip node. origin: &Pubkey, // CRDS value owner ) { if let Some(bloom_filter) = self.0.get(node) { bloom_filter.add(origin); } } fn rotate<R: Rng>( &mut self, rng: &mut R, size: usize, // Number of no...
prune
identifier_name
push_active_set.rs
push to for crds values belonging to this bucket. for (k, entry) in self.0.iter_mut().enumerate() { let weights: Vec<u64> = buckets .iter() .map(|&bucket| { // bucket <- get_stake_bucket(min stake of { // this node, crds value...
random_line_split
push_active_set.rs
Option<&u64>) -> &PushActiveSetEntry { &self.0[get_stake_bucket(stake)] } } impl PushActiveSetEntry { const BLOOM_FALSE_RATE: f64 = 0.1; const BLOOM_MAX_BITS: usize = 1024 * 8 * 4; fn get_nodes<'a>( &'a self, origin: &'a Pubkey, // If true forces gossip push even if th...
{ assert!(entry.get_nodes(origin, |_| false).eq(keys)); }
conditional_block
tag_tweets_py2.py
regex so that we can preserve case for # them as needed: EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE) # These regex are added EMOJI_RE = re.compile(EMOJIS, re.UNICODE) URLS_RE = re.compile(URLS, re.VERBOSE | re.I | re.UNICODE) PHONUM_RE = re.compile(Phone_numbers, re.VERBOSE | re.I | re.UNICODE...
# Fix HTML character entities: text = NLTK._replace_html_entities(text) # Shorten problematic sequences of characters safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text) # Tokenize: words = WORD_RE.findall(safe_text) clean_text = text # # Possibly alter the cas...
tknzr = NLTK.TweetTokenizer() return tknzr.tokenize(text)
conditional_block
tag_tweets_py2.py
;D', ' :‑P', ' :P', ' X‑P', ' x‑p', ' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)', '(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)', ...
return def is_json(myjson): try: json_object = json.loads(myjson) except ValueError, e: return False return True de
identifier_body
tag_tweets_py2.py
# WORD_RE performs poorly on these patterns: HANG_RE = re.compile(r"""([^a-zA-Z0-9])\1{3,}""") # The emoticon string gets its own regex so that we can preserve case for # them as needed: EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE) # These regex are added EMOJI_RE = re.compile(EMOJIS, re.UNICOD...
WORD_RE = re.compile(r"""(%s)""" % "|".join(REGEXPS), re.VERBOSE | re.I | re.UNICODE)
random_line_split
tag_tweets_py2.py
':\'‑)', ':\')', ' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p', ' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)', ...
icode te
identifier_name
Conv_layer.py
, height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_...
def im2col(self, X): """ :param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector :param filter_dim: :return: vector of dimension 1 by filter_dim^2 """ flat_vect = np.reshape(X, -1) return flat_vect def convolutio...
random_line_split
Conv_layer.py
height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_m...
def set_data_mtx(self,input_mtx): self.data_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) def get_gradient(self, x, y, depth): ...
self.padded_mtx = input_mtx self.depth , self.width,self.height = input_mtx.shape self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
identifier_body
Conv_layer.py
height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_m...
self.input_vol.set_padded_mtx(np.asarray(input_img_list)) def set_weights(self,input_vol): for j in range(len(self.filter_map)): self.filter_map[j].set_data_mtx(input_vol[j,:,:,:]) def Naive_forwardpass(self): """ Forward pass of conv net implementing output map ge...
if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 : for j in range(0,input_img.shape[0]): input_img_list[j] = self.zero_pad(input_img_list[j]) print(input_img_list) padded = True else: ...
conditional_block
Conv_layer.py
height, depth, weight_init='undefined'): self.width = width self.height = height self.depth = depth n_weight_vals = self.height * self.width * self.depth self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width)) self.delta_data_m...
(self, image_col, filter_col): conv_result = np.sum(np.dot(image_col, filter_col)) return conv_result def zero_pad(self,x): return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0) def zero_pad_image(self): input_img =self.input_vol.data_mtx.copy() input_img_l...
convolution_op
identifier_name
forms.py
.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigData, Comment from common.widgets import SelectMultiple, SelectDateTimeWidget from common import util from recaptcha_dja...
(self, **kwargs): if self.name == 'deleted_at' or self.auto_now or self.auto_now_add: return None defaults = {'form_class': SelectDateTimeField} defaults.update(kwargs) return super(DateTimeProperty, self).get_form_field(**defaults) class StringListProperty(djangoforms.StringListProperty): __me...
get_form_field
identifier_name
forms.py
from django import forms from django.conf import settings from django.core.validators import validate_email from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigD...
import logging
random_line_split
forms.py
.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigData, Comment from common.widgets import SelectMultiple, SelectDateTimeWidget from common import util from recaptcha_dja...
class UnloggedCommentForm(CommentForm): class Meta(CommentForm.Meta): pass captcha = ReCaptchaField() class BlockNewForm(BaseForm): class Meta: model = Block exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params'] def __init__(self, *args, **kwargs): super(BlockNewForm, self).__init_...
class Meta: model = Comment exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type'] def __init__(self, *args, **kwargs): self.extra_params = {} if "extra_params" in kwargs: self.extra_params = kwargs.pop("extra_params") super(CommentForm, self).__init__(*args, **kw...
identifier_body
forms.py
.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from common.models import Block, MenuItem, Theme, ConfigData, Comment from common.widgets import SelectMultiple, SelectDateTimeWidget from common import util from recaptcha_dja...
if isinstance(value, basestring): value = util.get_tags(value.lower()) return value class MultiEmailField(forms.Field): def to_python(self, value): if not value: return [] return util.get_tags(value.lower()) def validate(self, value): super(MultiEmailField, self).validate(value) ...
return []
conditional_block
mod.rs
i: usize, world: &'a World, } impl<'a> Iterator for ForceIterator<'a> { type Item = Vector3<f32>; fn next(&mut self) -> Option<Vector3<f32>> { if self.i < self.world.objects.len() { let force = self.world.force_on(self.i); self.i += 1; Some(force) } ...
start_freq, end_freq, start_force, end_force, start_force.norm(), ) } /// This function validates the geometry of the world. The function should be called, because it /// guarantees overflows later on in the simulation. /// /// # ...
{ println!("Geometry:"); println!( "\tWorld size: ({}, {}, {})", self.size.x, self.size.y, self.size.z ); for (i, bbox) in self.objects.iter().enumerate() { println!("\t{}: {}", i, bbox); } println!("{}", self.simulation_config); ...
identifier_body
mod.rs
i: usize, world: &'a World, } impl<'a> Iterator for ForceIterator<'a> { type Item = Vector3<f32>; fn next(&mut self) -> Option<Vector3<f32>> { if self.i < self.world.objects.len() { let force = self.world.force_on(self.i); self.i += 1; Some(force) } ...
(&self, i: usize, frequency: f32) -> Vector3<f32> { // Progress bar let bbox = &self.objects[i].bbox(); let dx = bbox.x1 - bbox.x0 + 4; let dy = bbox.y1 - bbox.y0 + 4; let dz = bbox.z1 - bbox.z0 + 4; let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len())...
force_on_for_freq
identifier_name
mod.rs
i: usize, world: &'a World, } impl<'a> Iterator for ForceIterator<'a> { type Item = Vector3<f32>; fn next(&mut self) -> Option<Vector3<f32>> { if self.i < self.world.objects.len() { let force = self.world.force_on(self.i); self.i += 1; Some(force) } ...
// Check for intersection with other objects for (j, bbox_2) in expanded_boxes.iter().enumerate() { if i < j && bbox_1.intersects(&bbox_2) { return Err(WorldError::ShapesIntersect { index_1: i, index_2: j, ...
random_line_split
algorithm.rs
pub walks: RandomWalks<I>, } fn walks<'a, L, G: 'a, RNG>( starting_nodes: impl Iterator<Item = &'a Id<G::Node>>, network: &G, ledger_view: &L, mut rng: RNG, get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64, ) -> RandomWalks<Id<G::Node>> where L: LedgerView, G: Graph, ...
ledger_view: &L, ) -> Osrank where L: LedgerView, G: Graph, <G::Node as GraphObject>::Id: Eq + Clone + Hash, { let total_walks = random_walks.len(); let node_visits = random_walks.count_visits(&node_id); Fraction::from(1.0 - ledger_view.get_damping_factors().project) * Osrank::new(no...
node_id: Id<G::Node>,
random_line_split
algorithm.rs
<G, I> where I: Eq + Hash, { network_view: G, pub walks: RandomWalks<I>, } fn walks<'a, L, G: 'a, RNG>( starting_nodes: impl Iterator<Item = &'a Id<G::Node>>, network: &G, ledger_view: &L, mut rng: RNG, get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64, ) -> RandomWalks<Id...
WalkResult
identifier_name
channel.rs
: &Thread) -> ArcType { let symbol = vm .global_env() .get_env() .find_type_info("Receiver") .unwrap() .name .clone(); Type::app(Type::ident(symbol), collect![T::make_type(vm)]) } } field_decl!{ sender, receiver } pub type Cha...
{ ExternModule::new( vm, record!{ resume => primitive::<fn(&'vm Thread) -> Result<(), String>>("std.thread.prim.resume", resume), (yield_ "yield") => primitive::<fn(())>("std.thread.prim.yield", yield_), spawn => primitive!(1 std::thread::prim::spawn), ...
identifier_body
channel.rs
the `Thread` thread: GcPtr<Thread>, queue: Arc<Mutex<VecDeque<T>>>, } impl<T> Userdata for Sender<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, { } impl<T> fmt::Debug for Sender<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}",...
thread: RootedThread, action: WithVM<'vm, FunctionRef<Action>>, ) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> { struct SpawnFuture<F>(Mutex<Option<F>>); impl<F> fmt::Debug for SpawnFuture<F> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Future") } ...
#[cfg(not(target_arch = "wasm32"))] fn spawn_on<'vm>(
random_line_split
channel.rs
the `Thread` thread: GcPtr<Thread>, queue: Arc<Mutex<VecDeque<T>>>, } impl<T> Userdata for Sender<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, { } impl<T> fmt::Debug for Sender<T> where T: fmt::Debug, { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", *self.queue.lock().unwrap()) } } impl<T> Traverseable for Sender<T> { fn traverse(&self, _gc: &mut Gc) { // No need to traverse in Sender as values can only be accessed through Receiver } } impl<T> Sender<T> { fn send(&...
fmt
identifier_name
devices.js
\___ \ | | | | |__| | |__| | |____| |____ ____) | |_| |_|\____/|_____/|______|______|_____/ */ /* _____ _____ /\ | __ \_ _| / \ | |__) || | / /\ \ | ___/ | | / ____ \| | _| |_ /_/ \_\_| |_____| */ const auth ={ auth:{ username: 'admin', password:...
(userId) { try { const rules = await AlarmRule.find({userId}) return rules } catch (error) { return "error" } } async function selectDevice(userId, dId){ try { const result = await Device.updateMany({userId: userId}, {selected: false}) const result2 = await ...
getAlarmRules
identifier_name
devices.js
:{ username: 'admin', password: process.env.EMQX_DEFAULT_APPLICATION_SECRET } } //GET DEVICES router.get("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id //get devices var devices = await Device.find({userId: userId}) //descouplin...
{ try { const rules = await AlarmRule.find({ userId: userId, dId: dId }); if (rules.length > 0) { asyncForEach(rules, async rule => { const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId; const res = await axios.delete(url, auth); ...
identifier_body
devices.js
\___ \ | | | | |__| | |__| | |____| |____ ____) | |_| |_|\____/|_____/|______|______|_____/ */ /* _____ _____ /\ | __ \_ _| / \ | |__) || | / /\ \ | ___/ | | / ____ \| | _| |_ /_/ \_\_| |_____| */ const auth ={ auth:{ username: 'admin', password:...
} const res = await axios.put(url, newRule, auth) if (res.status === 200 && res.data.data) { await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status}) console.log("Saver Rule Status Update...".green) return { status: "success", action: "update" ...
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId const newRule = { enabled: status
random_line_split
devices.js
const toSend = { status: "error", error: error } return res.status(500).json(toSend) } }) //NEW DEVICE router.post("/device", checkAuth, async (req, res) =>{ try { const userId = req.userData._id var newDevice = req.body.newDevice newD...
{ result += characters.charAt ( Math.floor(Math.random() * charactersLength) ) }
conditional_block
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table...
else if (type == "sort") { return "sort"; } else if (type == "filter") { return "label"; } else { return item.value; } } } } function headerTitle(title) { return "<span class='header-title'>" + title + "</span>"; } fu...
{ return runLink(item.value, row.run); }
conditional_block
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table...
function addOrUpdateRows(dt, items) { var added = false; items.forEach(function(item, index) { var curRow = findRow(dt, item); if (curRow != null) { updateRow(dt, curRow, item); } else { addRow(dt, item); added = true; } }); if (added...
{ var ids = items.map(function(item) { return item.run.id; }); return new Set(ids); }
identifier_body
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table...
return new Set(ids); } function addOrUpdateRows(dt, items) { var added = false; items.forEach(function(item, index) { var curRow = findRow(dt, item); if (curRow != null) { updateRow(dt, curRow, item); } else { addRow(dt, item); added = true; ...
random_line_split
compare-table.ts
= new Set(); fields.forEach(function(field) { if (field.source) { sources.add(field.source); } }); return Array.from(sources).join(","); } export function init(table, fields, options) { // TODO: use of jQuery disabled to support compile return undefined; /* jQuery(table...
(dt, target) { var row = dt.row("#" + target.run.id); return row.data() != undefined ? row : null; } function updateRow(dt, row, newItem) { var curItem = row.data(); dt.columns().every(function(colIndex) { var property = dt.column(colIndex).dataSrc(); var curVal = curItem[property]; ...
findRow
identifier_name
tree.go
[1:], aUrl[:idx]}) return h } } } *aParams = append(*aParams, param{aNode.Text[1:], aUrl}) return aNode } else if aNode.Type == VariantNode { // 变量节点 // # 消除path like /abc 的'/' idx := strings.IndexByte(aUrl, r.DelimitChar) //fmt.Println("D态", aUrl, " | ", aNode.Text[1:], idx) if idx == 0 {...
oot", s
identifier_name
tree.go
// two static route, content longer is first. func (self TSubNodes) Less(i, j int) bool { if self[i].Type == StaticNode { if self[j].Type == StaticNode { return len(self[i].Text) > len(self[j].Text) } return true } if self[j].Type == StaticNode { return false } else { return self[i].Level > self[j].Le...
// static route will be put the first, so it will be match first.
random_line_split
tree.go
self[i], self[j] = self[j], self[i] } // static route will be put the first, so it will be match first. // two static route, content longer is first. func (self TSubNodes) Less(i, j int) bool { if self[i].Type == StaticNode { if self[j].Type == StaticNode { return len(self[i].Text) > len(self[j].Text) } ret...
wap(i, j int) {
identifier_body
tree.go
(aUrl[:idx]) > 1 && strings.IndexByte(aUrl[:idx], r.DelimitChar) > -1 { retnil = true continue } //fmt.Println("类型2", aUrl[:idx], aNode.ContentType) if !validType(aUrl[:idx], aNode.ContentType) { //fmt.Println("错误类型", aUrl[:idx], aNode.ContentType) return nil //continue } h...
conditional_block
builder.py
scan = _op(ops.scan) zip = _op(ops.zip) allpairs = _op(ops.allpairs) flatten = _op(ops.flatten) print = _op(ops.print) concat = _op(ops.concat) length = _op(ops.length) contains ...
"""Split the current block, returning (old_block, new_block)""" # ------------------------------------------------- # Sanity check
random_line_split
builder.py
self._insert_op(result) return result def _process_void(self, *args, **kwds): result = kwds.pop('result', None) op = _process(self, types.Void, list(args), result) if kwds: op.add_metadata(kwds) return op if ops.i...
result.add_metadata(metadata)
conditional_block
builder.py
Acosh = _const(ops.Acosh) Tan = _const(ops.Tan) Atan = _const(ops.Atan) Atan2 = _const(ops.Atan2) Tanh = _const(ops.Tanh) Atanh = _const(ops.Atanh) Log = _const(ops.Log) Log2 ...
class Builder(OpBuilder): """ I build Operations and emit them into the function. Also provides convenience operations, such as loops, guards, etc. """ def __init__(self, func): self.func = func self.module = func.module self._curblock = None self._lastop = None ...
if type == args[0].type: return args[0] return buildop(self, type, args, result)
identifier_body
builder.py
Acosh = _const(ops.Acosh) Tan = _const(ops.Tan) Atan = _const(ops.Atan) Atan2 = _const(ops.Atan2) Tanh = _const(ops.Tanh) Atanh = _const(ops.Atanh) Log = _const(ops.Log) Log2 ...
(self, type, args, result=None, buildop=convert): if type == args[0].type: return args[0] return buildop(self, type, args, result) class Builder(OpBuilder): """ I build Operations and emit them into the function. Also provides convenience operations, such as loops, guards, etc...
convert
identifier_name
gdbstub.rs
1..]; let mut out = String::new(); ctx.dbg.pause(); match ty { 'g' => { let hw = ctx.dbg.hw(); for reg in 0..15 { out += &format!("{:08X}", hw.read_reg(reg).swap_bytes()); } out += &format!("{:08X}", hw.pause_addr().swap_bytes()); ...
let mut connection = Connection { listener: &listener,
random_line_split
gdbstub.rs
= cmd.splitn(2, |c| c == ',' || c == ':' || c == ';'); let ty = parse_next(&mut s)?; let mut out = String::new(); match ty { "Cont" => { let params = parse_next(&mut s)?; let threads = params.split(';'); for thread in threads { let mut thread_data...
GdbCtx
identifier_name
gdbstub.rs
} fn handle_gdb_cmd_q(cmd: &str, _ctx: &mut GdbCtx) -> Result<String> { let mut s = cmd.splitn(2, ':'); let ty = parse_next(&mut s)?; let mut out = String::new(); match ty { "fThreadInfo" => out += "m0000000000000001", "sThreadInfo" => out += "l", "C" => out += "QC0000000000000...
{ let reason_str = match self.reason { BreakReason::Breakpoint => format!(";{}:", "swbreak"), _ => String::new(), }; format!("T05{:02X}:{:08X};{:02X}:{:08X}{};", 15, self.r15.swap_bytes(), 13, self.r13.swap_bytes(), ...
identifier_body
spinning_square.rs
fn handle_toggle_rounded_message(&mut self, _msg: &ToggleRoundedMessage) { self.rounded = !self.rounded; self.square_path = None; } fn handle_toggle_direction_message(&mut self, _msg: &ToggleDirectionMessage) { self.direction = self.direction.toggle(); } fn handle_other_messag...
{ if keyboard_event.phase == input::keyboard::Phase::Pressed || keyboard_event.phase == input::keyboard::Phase::Repeat { match code_point { SPACE => self.toggle_rounded(), B => self.move_backward(), F => ...
conditional_block
spinning_square.rs
Error> { Ok(()) } fn create_view_assistant_with_parameters( &mut self, params: ViewCreationParameters, ) -> Result<ViewAssistantPtr, Error> { let additional = params.options.is_some(); let direction = params .options .and_then(|options| optio...
} #[derive(Debug)] pub struct ToggleRoundedMessage {} #[derive(Debug)] pub struct ToggleDirectionMessage {} struct SpinningSquareFacet { direction: Direction, square_color: Color, rounded: bool, start: Time, square_path: Option<Path>, size: Size, } impl SpinningSquareFacet { fn new(squar...
match self { Self::Clockwise => Self::CounterClockwise, Self::CounterClockwise => Self::Clockwise, } }
random_line_split
spinning_square.rs
error running echo server")? { if !quiet { println!("Spinning Square received echo request for string {:?}", value); } responder .send(value.as_ref().map(|s| &**s)) .contex...
resize
identifier_name
aup2rpp.py
WavWriter(f, au['sample_rate'], nchannels, 16) elif w.sample_rate != au['sample_rate']: print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav") # TODO Resample, or return multiple files and split the clip... break samples_by_channel.append(samples) ...
assert block['filename'].endswith('.au') block2 = None if is_stereo_track and clip2 is not None: for b in clip2['sequence']['blocks']: if b['start'] == block['start'] and b['len'] == block['len']: block2 = b break if block2 is not None: src_fpath = indexed_files[block...
conditional_block
aup2rpp.py
f = self.f for v in sample_data: f.write(struct.pack(sfc, v)) self.samples_count += nsamples def finalize(self): assert not self.finalized f = self.f end = f.tell() data_chunk_size = f.tell() - self.data_fpos f.seek(self.initial_fpos) assert data_chunk_size == (self.samples_count * self.channel...
output = { 'rate': rate, 'name': unescape(name), 'data_dir': data_dir, 'tracks': [] } for project_item in root: tag = project_item.tag.split('}')[1] if tag == 'wavetrack': o_track = { 'name': unescape(project_item.attrib['name']), 'channel': int(project_item.attrib['channel']), 'linke...
return html.unescape(s)
identifier_body
aup2rpp.py
f = self.f for v in sample_data: f.write(struct.pack(sfc, v)) self.samples_count += nsamples def finalize(self): assert not self.finalized f = self.f end = f.tell() data_chunk_size = f.tell() - self.data_fpos f.seek(self.initial_fpos) assert data_chunk_size == (self.samples_count * self.channel...
samples_by_channel.append(samples) w.append_multichannel_samples(samples_by_channel) w.finalize() return 0 if w is None else w.samples_count def load_audacity_project(fpath): root = ET.parse(fpath).getroot() rate = int(float(root.attrib["rate"])) name = root.attrib['projname'] ns = { 'ns': 'http://...
random_line_split
aup2rpp.py
: def __init__(self, f, sample_rate, channels, bits_per_sample): self.f = f self.sample_rate = sample_rate self.channels = channels self.bits_per_sample = bits_per_sample self.finalized = False self.samples_count = 0 self.fmt_chunk_size = 2 + 2 + 4 + 4 + 2 + 2 self.initial_fpos = f.tell() # Leave...
WavWriter
identifier_name
ipfs.go
() operation TempDir string `json:"temp_dir,omitempty"` // Datastore config DataStore json.RawMessage `json:"datastore,omitempty"` // Address config - same format as ipfs addresses config Addresses json.RawMessage `json:"addresses,omitempty"` // Private network flag, indicates will have to generate swarm.key a...
return err } // StorageInterface impl // Get retrieves object at path and returns as a os.File instance // path should be ipfs cid. Caller should close file when done func (fs *Ipfs) Get(path string) (f *os.File, err error) { // Create output filename from the CID path string var fname string fname, err = fs.ma...
{ // Try to make 0700 if err = os.MkdirAll(path, os.ModePerm); err != nil { return fmt.Errorf("failed to create root dir: %s", path) } }
conditional_block
ipfs.go
Get() operation TempDir string `json:"temp_dir,omitempty"` // Datastore config DataStore json.RawMessage `json:"datastore,omitempty"` // Address config - same format as ipfs addresses config Addresses json.RawMessage `json:"addresses,omitempty"` // Private network flag, indicates will have to generate swarm.k...
} // Check temp dir path if err := ensureDir(cfg.TempDir); err != nil { return nil, err } // Create ipfs node base on configuration if err := ipfs.setupPlugins(cfg.RootPath); err != nil { return nil, err } // Initialize the default ipfs config // Create a config with default options and a 2048 bit key ...
// Check root path if err := ensureDir(cfg.RootPath); err != nil { return nil, err
random_line_split
ipfs.go
. //StorageType string `json:"store,omitempty"` // TODO other raw message types for ipfs specific configuration, eg. Addresses } // Ipfs provides storage interface using IPFS type Ipfs struct { // ipfs core api coreAPI icore.CoreAPI // Configuration config *Config // ipfs node ipfsNode *core.IpfsNode } //...
{ // Load any external plugins if available plugins, err := loader.NewPluginLoader(path) if err != nil { return fmt.Errorf("error loading plugins: %s", err) } // Load preloaded and external plugins if err := plugins.Initialize(); err != nil { return fmt.Errorf("error initializing plugins: %s", err) } if e...
identifier_body
ipfs.go
Get() operation TempDir string `json:"temp_dir,omitempty"` // Datastore config DataStore json.RawMessage `json:"datastore,omitempty"` // Address config - same format as ipfs addresses config Addresses json.RawMessage `json:"addresses,omitempty"` // Private network flag, indicates will have to generate swarm.k...
(path string) (string, error) { return path, nil } // GetEndpoint no-op func (fs *Ipfs) GetEndpoint() string { return "/ipfs" } // Creates an IPFS node and returns its coreAPI func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) { // Open the repo repo, err := fsrepo.Open(repoPa...
GetURL
identifier_name
tree.py
(self, nodes: List[str]=None, root: bool=True): if nodes is None: nodes = [] if root: nodes = self.tree Tree.print_node(nodes) if nodes['class'] == -1: self._print(nodes=nodes['l_node'], root=Fa...
_print
identifier_name
tree.py
def fit(self, x, y, debug=False): """ Convert data to matrix if dataframe Recursively create nodes using tree.buildNodes() """ # Set feature names self.set_names(x) # Convert to mats if not x = self.strip_df(x) y = self.strip_df(y) ...
bs =' ' * node['depth'] * 2 bs2 = '-' * 2 print(bs+'|'+bs2+'*' * 50) print(bs+'|'+bs+node['node_str']) print(bs+'|'+bs+'Depth:', node['depth']) print(bs+'|'+bs+'n samples:', node['n']) if not node['terminal']: print(bs+'|'+bs+'Name: '+node['name']) ...
identifier_body
tree.py
bs2 = '-' * 2 print(bs+'|'+bs2+'*' * 50) print(bs+'|'+bs+node['node_str']) print(bs+'|'+bs+'Depth:', node['depth']) print(bs+'|'+bs+'n samples:', node['n']) if not node['terminal']: print(bs+'|'+bs+'Name: '+node['name']) print(bs+'|'+bs+'Split Value:', n...
'note': f'One class at depth, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} else: # Not terminal. Build next node. # First find best split to run col_idx, best_x, gini = Tre...
cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth,
random_line_split
tree.py
2 = '-' * 2 print(bs+'|'+bs2+'*' * 50) print(bs+'|'+bs+node['node_str']) print(bs+'|'+bs+'Depth:', node['depth']) print(bs+'|'+bs+'n samples:', node['n']) if not node['terminal']: print(bs+'|'+bs+'Name: '+node['name']) print(bs+'|'+bs+'Split Value:', node...
else: cla = Tree.high_class(y, bias) node = {'class': cla, 'depth': depth, 'note': f'Too few data points, class is: {cla}', 'terminal': True, 'n': len(x), 'node_str': d_str} ...
cla = nom_class
conditional_block
opt.rs
recommended) Time Profiler." )] Instruments(AppConfig), } #[derive(Debug, StructOpt)] #[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)] pub(crate) struct AppConfig { /// List available templates #[structopt(short = "l", long)] pub(crate) list_templates: bool, /// Specify the...
(&self) -> Package { if let Some(ref package) = self.package { Package::Package(package.clone()) } else { Package::Default } } // valid target: --example, --bin, --bench fn get_target(&self) -> Target { if let Some(ref example) = self.example { ...
get_package
identifier_name
opt.rs
) Time Profiler." )] Instruments(AppConfig), } #[derive(Debug, StructOpt)] #[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)] pub(crate) struct AppConfig { /// List available templates #[structopt(short = "l", long)] pub(crate) list_templates: bool, /// Specify the instrument...
} impl fmt::Display for Package { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Package::Default => { write!(f, "Default: search all packages for example/bin/bench") } Package::Package(s) => write!(f, "{}", s), } } } im...
{ match p { Package::Default => Packages::Default, Package::Package(s) => Packages::Packages(vec![s]), } }
identifier_body
opt.rs
recommended) Time Profiler."
#[derive(Debug, StructOpt)] #[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)] pub(crate) struct AppConfig { /// List available templates #[structopt(short = "l", long)] pub(crate) list_templates: bool, /// Specify the instruments template to run /// /// To see available temp...
)] Instruments(AppConfig), }
random_line_split
quotes.py
for the price quote. Name, price and as-of date and time are retrieved from Yahoo! Finance. fields: status, source, ticker, name, price, quoteTime, pclose, pchange """ def __init__(self, item): #item = {"ticker":TickerSym, 'm':multiplier, 's':symbol} # TickerSym = symbol t...
OfxWriter
identifier_name
quotes.py
09Nov2017*rlc # -Replace Yahoo quotes csv w/ json # -Removed yahooScrape option # 24Mar2018*rlc # -Use longName when available for Yahoo quotes. Mutual fund *family* name is sometimes given as shortName (see vhcox as example) import os, sys, time, urllib2, socket, shlex, re, csv, uuid, json import site_cfg fro...
self.status=False self.source='Y' #note: each try for a quote sets self.status=true if successful if eYahoo: csvtxt = self.getYahooQuote() quote = self.csvparse(csvtxt) if self.status: self.source='Y' if not s...
print "Getting quote for:", self.ticker
conditional_block
quotes.py
! Finance: # name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2) if Debug: print "Getting quote for:", self.ticker self.status=False self.source='Y' #note: each try for a quote sets self.status=true if successful if eYaho...
""" Create an OFX file based on a list of stocks and mutual funds. """ def __init__(self, currency, account, shares, stockList, mfList): self.currency = currency self.account = account self.shares = shares self.stockList = stockList self.mfList = mfList s...
identifier_body
quotes.py
0) if Debug: print "Quote result string:", csvtxt self.name = quote[0] self.price = quote[1] self.date = quote[2] self.time = quote[3] self.pclose = quote[4] self.pchange = quote[5] #clean things u...
for mf in self.mfList: posmf.append(self._pos("mf", mf.symbol, mf.price, mf.quoteTime)) return OfxTag("INVPOSLIST",
random_line_split
init.rs
884 fn ensure_procfs(path: &Path) -> Result<()> { let procfs_fd = fs::File::open(path)?; let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?; if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC { bail!(format!("{:?} is not on the procfs", path)); } Ok(()) } // Get ...
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?; capabilities::reset_effective(command)?; if let Some(caps) = &proc.capabilities { capabilities::drop_privileges(caps, command)?; } // Take care of LISTEN_FDS used for systemd-active-socket. If the value is //...
{ rootfs::prepare_rootfs( spec, rootfs, namespaces .clone_flags .contains(sched::CloneFlags::CLONE_NEWUSER), ) .with_context(|| "Failed to prepare rootfs")?; // change the root of filesystem of the process to the rootfs...
conditional_block
init.rs
6884 fn ensure_procfs(path: &Path) -> Result<()> { let procfs_fd = fs::File::open(path)?; let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?; if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC { bail!(format!("{:?} is not on the procfs", path)); } Ok(()) } // Get...
"LISTEN_FDS entered is malformed: {:?}. Ignore the value.", &value ); args.preserve_fds } }; // clean up and handle perserved fds. cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?; // notify parents ...
log::warn!(
random_line_split
init.rs
| file_name.to_str().map(String::from)) .filter_map(|file_name| -> Option<i32> { // Convert the file name from string into i32. Since we are looking // at /proc/<pid>/fd, anything that's not a number (i32) can be // ignored. We are only interested in opened fds. m...
test_cleanup_file_descriptors
identifier_name
init.rs
6884 fn ensure_procfs(path: &Path) -> Result<()> { let procfs_fd = fs::File::open(path)?; let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?; if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC { bail!(format!("{:?} is not on the procfs", path)); } Ok(()) } // Get...
}) .collect(); Ok(fds) } // Cleanup any extra file descriptors, so the new container process will not // leak a file descriptor from before execve gets executed. The first 3 fd will // stay open: stdio, stdout, and stderr. We would further preserve the next // "preserve_fds" number of fds. Set th...
{ const PROCFS_FD_PATH: &str = "/proc/self/fd"; ensure_procfs(Path::new(PROCFS_FD_PATH)) .with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?; let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)? .filter_map(|entry| match entry { Ok(entry) => Some(entry.path())...
identifier_body
batch-rotate.go
exported // BatchKeyRotateKV is a datatype that holds key and values for filtering of objects // used by metadata filter as well as tags based filtering. type BatchKeyRotateKV struct { Key string `yaml:"key" json:"key"` Value string `yaml:"value" json:"value"` } // Validate returns an error if key is empty func (...
// Empty indicates if kv is not set func (kv BatchKeyRotateKV) Empty() bool { return kv.Key == "" && kv.Value == "" } // Match matches input kv with kv, value will be wildcard matched depending on the user input func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool { if kv.Empty() { return true } if stri...
{ if kv.Key == "" { return errInvalidArgument } return nil }
identifier_body
batch-rotate.go
exported // BatchKeyRotateKV is a datatype that holds key and values for filtering of objects // used by metadata filter as well as tags based filtering. type BatchKeyRotateKV struct { Key string `yaml:"key" json:"key"` Value string `yaml:"value" json:"value"` } // Validate returns an error if key is empty func (...
() error { if r.Attempts < 0 { return errInvalidArgument } if r.Delay < 0 { return errInvalidArgument } return nil } // BatchKeyRotationType defines key rotation type type BatchKeyRotationType string const ( sses3 BatchKeyRotationType = "sse-s3" ssekms BatchKeyRotationType = "sse-kms" ) // BatchJobKeyR...
Validate
identifier_name
batch-rotate.go
unexported // BatchKeyRotateKV is a datatype that holds key and values for filtering of objects // used by metadata filter as well as tags based filtering. type BatchKeyRotateKV struct { Key string `yaml:"key" json:"key"` Value string `yaml:"value" json:"value"` } // Validate returns an error if key is empty func...
} } return nil } // BatchKeyRotateFilter holds all the filters currently supported for batch replication type BatchKeyRotateFilter struct { NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"` OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"` CreatedAfter ...
} ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil { return err
random_line_split
batch-rotate.go
.WithTimeout(ctx, 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body) if err != nil { return err } if r.Flags.Notify.Token != "" { req.Header.Set("Authorization", r.Flags.Notify.Token) } clnt := http.Client{Transport: getRemoteInstance...
{ attempts := attempts stopFn := globalBatchJobsMetrics.trace(batchKeyRotationMetricObject, job.ID, attempts, result) success := true if err := r.KeyRotate(ctx, api, result); err != nil { stopFn(err) logger.LogIf(ctx, err) success = false } else { stopFn(nil) } ri.trackCu...
conditional_block
lib.rs
が可能なもの // なんらかの可能性がある値について,合致しないことがあるパターン let some_option_value = Some(3); // 合致しないパターンを考慮した制御フローを書かないとコンパイルエラーになる // 下のようにNoneの可能性を考慮して処理する if let Some(x) = some_option_value { println!("some option value is: {}", x); } // 論駁が不可能なもの // あらゆるものにマッチする // ワーニングがでる // irrefu...
identifier_name
lib.rs
: {}", b); } // この例では輝かないが,if-let記法も道具箱にあるんですよ // matchを使って表現するには冗長な場合に使いましょう pub fn if_let_notation() { let a = 3; if let 1 = a { println!("matched value is: 1"); } else if let 2 = a { println!("matched value is: 2"); } else if let 3 = a { println!("matched value is: 3"); }...
for (i, v) in v.iter().enumerate() { println!("{} is at index {}", v, i); } // a is at index 0 // a is at index 1 // a is at index 2 } // 実はいつもつかうlet文もパターンの考え方を使っている pub fn let_statement_uses_pattern() { // let PATTERN = EXPRESSION; // ここでマッチしたものを変数_xに束縛することを意味するパターン // なんでもいいよ...
_as_long_as_vector_has_values() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("vector has {} on the top", top); } // vector has 3 on the top // vector has 2 on the top // vector has 1 on the top } // ...
identifier_body
lib.rs
: {}", b); } // この例では輝かないが,if-let記法も道具箱にあるんですよ // matchを使って表現するには冗長な場合に使いましょう pub fn if_let_notation() { let a = 3; if let 1 = a { println!("matched value is: 1"); } else if let 2 = a { println!("matched value is: 2"); } else if let 3 = a { println!("matched value is: 3"); }...
Message::Quit, Message::Move { x: 3, y: 4 }, Message::Write("Hello!".to_string()), Message::ChangeColor(Color::Rgb(0, 255, 128)), Message::ChangeColor(Color::Hsv(0, 0, 0)), ]; for msg in msgs.iter() { match msg { Message::Quit => { pri...
let msgs = vec![
random_line_split
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carne...
ata, sample_rate): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogr...
veform_to_examples(d
identifier_name
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carne...
def waveform_to_examples(data, sample_rate): # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) ...
random_line_split
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carne...
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate)) example_hop_length = int(round( vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate)) log_mel_examples = mel_features.frame( log_mel, window_length=example_window_length, hop_length=example_hop_lengt...
len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE) # Compute log mel spectrogram features. log_mel = mel_features.log_mel_s...
identifier_body
vggish_input.py
ARE AGREEING TO THE TERMS OF THIS # LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR # DOWNLOAD THE SOFTWARE. # # This is a license agreement ("Agreement") between your academic institution # or non-profit organization or self (called "Licensee" or "You" in this # Agreement) and Carne...
# Compute log mel spectrogram features. log_mel = mel_features.log_mel_spectrogram( data, audio_sample_rate=vggish_params.SAMPLE_RATE, log_offset=vggish_params.LOG_OFFSET, window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS, hop_length_secs=vggish_params.S...
ta = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
conditional_block
rastermanager.py
s = None cols = None rows = None xres = None yres = None # left geo coord 'e.g. Westernmost Longitude" left = None # top geo coord e.g highest Latitude extent top = None transform = [xres, 0.0, left, 0.0, yres, top] geoproperties_file = None # can contain multiple features o...
else: print('PATH MODE in config is not set properly for the cloud implementation of output_Rasters') sys.exit(0) # ----------- create output rasters ----------------- def output_rasters(self, arr, outdir, outname): """ This function creates geotiff files from...
print('google path mode not yet implemented') sys.exit(0)
conditional_block