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
main_tc.py
def run(config): torch.manual_seed(config.seed) np.random.seed(config.seed) seed(config.seed) if USE_CUDA: torch.cuda.set_device(0) torch.cuda.manual_seed(config.seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True all_rewards = []...
def get_env_fn(rank): def init_env(): env = make_env(env_id, discrete_action=discrete_action) env.seed(seed + rank * 1000) np.random.seed(seed + rank * 1000) return env return init_env if n_rollout_threads == 1: return DummyVecEnv([get_env_fn...
identifier_body
main_tc.py
, discrete_action=discrete_action) env.seed(seed + rank * 1000) np.random.seed(seed + rank * 1000) return env return init_env if n_rollout_threads == 1: return DummyVecEnv([get_env_fn(0)]) else: return SubprocVecEnv([get_env_fn(i) for i in range(n_ro...
(config): torch.manual_seed(config.seed) np.random.seed(config.seed) seed(config.seed) if USE_CUDA: torch.cuda.set_device(0) torch.cuda.manual_seed(config.seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True all_rewards = [] all_p...
run
identifier_name
main_tc.py
, discrete_action=discrete_action) env.seed(seed + rank * 1000) np.random.seed(seed + rank * 1000) return env return init_env if n_rollout_threads == 1: return DummyVecEnv([get_env_fn(0)]) else: return SubprocVecEnv([get_env_fn(i) for i in range(n_ro...
for u_i in range(config.num_updates): for a_i in range(maddpg.nagents): sample = replay_buffer.sample(config.batch_size, to_gpu=USE_CUDA) penalty_helper_1, penalty_helper_2 = maddpg...
maddpg.prep_training(device='cpu')
conditional_block
main_tc.py
_id, discrete_action=discrete_action) env.seed(seed + rank * 1000) np.random.seed(seed + rank * 1000) return env return init_env if n_rollout_threads == 1: return DummyVecEnv([get_env_fn(0)]) else: return SubprocVecEnv([get_env_fn(i) for i in range(n...
lb_t_1 = torch.from_numpy(np.random.rand(1)).float() lb_t_2 = torch.from_numpy(np.random.rand(1)).float() model_dir = Path('./models') / config.env_id / config.model_name if not model_dir.exists(): curr_run = 'run1' else: exst_run_nums = [int(str(folder.name).split('run')[1]) fo...
alpha_1 = 12 alpha_2 = 0.2
random_line_split
WDCNN-DANN(p).py
if class_name.find('Linear') != -1: xavier_uniform_(m.weight.data) def batch_norm_init(m): class_name = m.__class__.__name__ if class_name.find('BatchNorm') != -1: m.reset_running_stats() # split train and split data def data_split_train(data_set, label_set): data_set_train ...
train = [] label_set_val = [] for i in range(data_set.shape[0]): #行数 shape[2]通道数 index = np.arange(data_set.shape[1]) #列数矩阵[0 1 2 '''] np.random.shuffle(index) #随机打乱数据 每次shuffle后数据都被打乱,这个方法可以在机器学习训练的时候在每个epoch结束后将数据重新洗牌进入下一个epoch的学习 a = index[:int((data_set.shape[1]) * 0.8)] ...
label_set_
identifier_name
WDCNN-DANN(p).py
if class_name.find('Linear') != -1: xavier_uniform_(m.weight.data) def batch_norm_init(m): class_name = m.__class__.__name__ if class_name.find('BatchNorm') != -1: m.reset_running_stats() # split train and split data def data_split_train(data_set, label_set): data_set_train ...
s, acc_s,average_loss_t, acc_t)) val_loss_s.append(loss_s.item()) val_loss_t.append(loss_t.item()) val_acc_t.append(acc_t) val_acc_s.append(acc_s) torch.save(model.state_dict(), os.path.join(wandb.run.dir, "model.pth")) #画出验证集正确率曲线 plt.plot(val_acc_s, 'r-',marker...
pu().sum() sum_loss_t += loss_t acc_t = 100. * correct_val_t.item() / length_val_t #目标域正确率 average_loss_t = sum_loss_t.item() / length_val_t #目标域损失 metrics = {"Acc_val_t": acc_t, 'epoch':epoch} wandb.log(metrics) print('\n The {}/{} epoch result : Ave...
conditional_block
WDCNN-DANN(p).py
if class_name.find('Linear') != -1: xavier_uniform_(m.weight.data) def batch_norm_init(m): class_name = m.__class__.__name__ if class_name.find('BatchNorm') != -1:
ta_set_train = [] data_set_val = [] label_set_train = [] label_set_val = [] for i in range(data_set.shape[0]): #行数 shape[2]通道数 index = np.arange(data_set.shape[1]) #列数矩阵[0 1 2 '''] np.random.shuffle(index) #随机打乱数据 每次shuffle后数据都被打乱,这个方法可以在机器学习训练的时候在每个epoch结束后将数据重新洗牌进入下一个epoch...
m.reset_running_stats() # split train and split data def data_split_train(data_set, label_set): da
identifier_body
WDCNN-DANN(p).py
plt.rcParams['font.family'] = ['Times New Roman'] def to_percent(temp, position): return '%1.0f' % (temp) + '%' # model initialization 参数初始化 def weight_init(m): class_name = m.__class__.__name__ #得到网络层的名字 if class_name.find('Conv') != -1: # 使用了find函数,如果不存在返回值为-1,所以让其不等于-1 xavier_u...
r=0.02 ) wandb.init(config=hyperparameter_defaults, project="WDCNN-DANN") config = wandb.config
random_line_split
hls_live.rs
default: stream.default, autoselect: stream.default, channels: Some("2".to_string()), ..Default::default() } }) .collect(), independent_segments: true, ..Default::default(...
fn update_manifest(state: &mut StreamState) { // Now write the manifest let mut path = state.path.clone(); path.push("manifest.m3u8"); println!("writing manifest to {}", path.display()); trim_segments(state); let playlist = MediaPlaylist { version: Some(7), target_duration: 2....
break; } } }
random_line_split
hls_live.rs
default: stream.default, autoselect: stream.default, channels: Some("2".to_string()), ..Default::default() } }) .collect(), independent_segments: true, ..Default::default(...
first = buffer_list.get(0).unwrap(); } // If the buffer only has the HEADER flag set then this is a segment header that is // followed by one or more actual media buffers. assert!(first.flags().contains(gst::BufferFlags::HEADER)); ...
{ let mut path = state.path.clone(); std::fs::create_dir_all(&path).expect("failed to create directory"); path.push("init.cmfi"); println!("writing header to {}", path.display()); let map = first.map_readable().unwrap()...
conditional_block
hls_live.rs
default: stream.default, autoselect: stream.default, channels: Some("2".to_string()), ..Default::default() } }) .collect(), independent_segments: true, ..Default::default(...
// The muxer only outputs non-empty buffer lists let mut buffer_list = sample.buffer_list_owned().expect("no buffer list"); assert!(!buffer_list.is_empty()); let mut first = buffer_list.get(0).unwrap(); // Each list contains a full segmen...
{ let mut path: PathBuf = path.into(); path.push(name); let state = Arc::new(Mutex::new(StreamState { segments: VecDeque::new(), trimmed_segments: VecDeque::new(), path, start_date_time: None, start_time: gst::ClockTime::NONE, media_sequence: 0, segme...
identifier_body
hls_live.rs
default: stream.default, autoselect: stream.default, channels: Some("2".to_string()), ..Default::default() } }) .collect(), independent_segments: true, ..Default::default(...
{ name: String, bitrate: u64, width: u64, height: u64, } struct AudioStream { name: String, lang: String, default: bool, wave: String, } fn trim_segments(state: &mut StreamState) { // Arbitrary 5 segments window while state.segments.len() > 5 { let segment = state.segm...
VideoStream
identifier_name
tasks.py
from __future__ import absolute_import, unicode_literals import json import pkg_resources from celery.utils.log import get_task_logger from celery.worker.control import Panel from reviewbot.celery import celery from rbtools.api.client import RBClient from reviewbot.processing.review import Review from reviewbot.repo...
The ID of the status update for this invocation of the tool. review_settings (dict): Settings for how the review should be created. tool_options (dict): The tool-specific settings. repository_name (unicode): The name of the repository to clone t...
"""Execute an automated review on a review request. Args: server_url (unicode): The URL of the Review Board server. session (unicode): The encoded session identifier. username (unicode): The name of the user who owns the ``session``. review_req...
identifier_body
tasks.py
from __future__ import absolute_import, unicode_literals import json import pkg_resources from celery.utils.log import get_task_logger from celery.worker.control import Panel from reviewbot.celery import celery from rbtools.api.client import RBClient from reviewbot.processing.review import Review from reviewbot.repo...
(api_root): """Return the Review Bot extension resource. Args: api_root (rbtools.api.resource.Resource): The server API root. Returns: rbtools.api.resource.Resource: The extension's API resource. """ # TODO: Cache this. We only use this resource as a link to sub...
_get_extension_resource
identifier_name
tasks.py
from __future__ import absolute_import, unicode_literals import json import pkg_resources from celery.utils.log import get_task_logger from celery.worker.control import Panel from reviewbot.celery import celery from rbtools.api.client import RBClient from reviewbot.processing.review import Review from reviewbot.repo...
else: logger.info('Publishing review %s', log_detail) review_id = review.publish().id status_update.update(state=DONE_FAILURE, description='failed.', review_id=review_id) excep...
status_update.update(state=DONE_SUCCESS, description='passed.')
conditional_block
tasks.py
from __future__ import absolute_import, unicode_literals import json import pkg_resources from celery.utils.log import get_task_logger from celery.worker.control import Panel from reviewbot.celery import celery
from reviewbot.processing.review import Review from reviewbot.repositories import repositories from reviewbot.utils.filesystem import cleanup_tempfiles # TODO: Make the cookie file configurable. COOKIE_FILE = 'reviewbot-cookies.txt' # TODO: Include version information in the agent. AGENT = 'ReviewBot' # Status U...
from rbtools.api.client import RBClient
random_line_split
mod.rs
can also be constructed from a `log::LogRecord`. All /// available metadata is transferred over to the message object. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct Message<'a> { short_message: Cow<'a, str>, full_message: Option<Cow<'a, str>>, #[serde(deserialize_with = "parse_unix_...
/// Return a metadata field with given key pub fn metadata(&self, key: &'a str) -> Option<&Cow<'a, str>> { self.metadata.get(key) } /// Return all metadata pub fn all_metadata(&self) -> &HashMap<Cow<'a, str>, Cow<'a, str>> { &self.metadata } /// Set a metadata field with ...
{ self.level = level; self }
identifier_body
mod.rs
` can also be constructed from a `log::LogRecord`. All /// available metadata is transferred over to the message object. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct Message<'a> { short_message: Cow<'a, str>, full_message: Option<Cow<'a, str>>, #[serde(deserialize_with = "parse_unix...
<S>( short_message: S, level: Level, ) -> Self where S: Into<Cow<'a, str>> + AsRef<str> { Message { short_message: short_message.into(), level, full_message: None, timestamp: None, metadata: HashMap::new(), ...
new_with_level
identifier_name
mod.rs
` can also be constructed from a `log::LogRecord`. All /// available metadata is transferred over to the message object. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct Message<'a> { short_message: Cow<'a, str>, full_message: Option<Cow<'a, str>>, #[serde(deserialize_with = "parse_unix...
self } /// Return the `level` pub fn level(&self) -> Level { self.level } /// Set the `level` pub fn set_level(&mut self, level: Level) -> &mut Self { self.level = level; self } /// Return a metadata field with given key pub fn metadata(&self, key: ...
/// Clear the `timestamp` pub fn clear_timestamp(&mut self) -> &mut Self { self.timestamp = None;
random_line_split
manifest.py
class Manifest: """ List of volumes and information about each one """ def __init__(self, fh=None): """ Create blank Manifest @param fh: fileobj for manifest @type fh: DupPath @rtype: Manifest @return: manifest """ self.hostname = None ...
class ManifestError(Exception): """ Exception raised when problem with manifest """ pass
random_line_split
manifest.py
_dirinfo(self): """ Return None if dirinfo is the same, otherwise error message Does not raise an error message if hostname or local_dirname are not available. @rtype: string @return: None or error message """ if globals.allow_source_mismatch: ...
def get_containing_volumes(self, index_prefix): """ Return list of volume numbers that may contain index_prefix """ return filter(lambda vol_num: self.volume_info_dict[vol_num].contains(index_prefix), self.volume_info_dict.keys()) class...
""" Write string version of manifest to given path """ assert not path.exists() fout = path.open("wb") fout.write(self.to_string()) assert not fout.close() path.setdata()
identifier_body
manifest.py
_dirinfo(self): """ Return None if dirinfo is the same, otherwise error message Does not raise an error message if hostname or local_dirname are not available. @rtype: string @return: None or error message """ if globals.allow_source_mismatch: ...
(self): """ Return string version of self (just concatenate vi strings) @rtype: string @return: self in string form """ result = "" if self.hostname: result += "Hostname %s\n" % self.hostname if self.local_dirname: result += "Local...
to_string
identifier_name
manifest.py
check_dirinfo(self): """ Return None if dirinfo is the same, otherwise error message Does not raise an error message if hostname or local_dirname are not available. @rtype: string @return: None or error message """ if globals.allow_source_mismatch: ...
if (self.hostname != other.hostname or self.local_dirname != other.local_dirname): log.Notice(_("Manifests not equal because hosts or directories differ")) return False return True def __ne__(self, other): """ Defines !=. Not doing this al...
log.Notice(_("Manifests not equal because volume lists differ")) return False
conditional_block
ship.py
else: self.inputColour[i] = sensor_colours[0] self.scan[i] = 1 i +=1 elif self.inputType == 1: #eXPERIMENTAL STUFF FOR continuous LOS self.extrapos.append(maze.getMaximumSightDistance(se...
bp = self.getIntPos() bp = getOffsetPos(bp,midpos) # Draw where the inputs are for decision making. if(self.crashed == False or True): self.drawTargetCheckpoint(screen,maze,bp,midpos = midpos) for i,pos in enumerate(self.inputPos): pygame.draw.circle(scree...
identifier_body
ship.py
.append(np.add(wt.copy(), np.random.normal(0,stray,(shp.dimensions[i],shp.dimensions[i+1])))) for i,bs in enumerate(shp.bias): self.bias.append(np.add(bs.copy(), np.random.normal(0,stray,shp.dimensions[i+1]))) self.normalizeWeights() self.colour = colour self.pare...
(self): """Determines if we have passed a checkpoint this timestep""" if self.maze.checkpoints[self.checkpoint].checkCollision(self.pos): self.checkpoint +=1 if(self.checkpoint >= self.maze.checkpointsPerLap): if(self.maze.mazeType == "circular"): ...
checkCheckpoint
identifier_name
ship.py
+ str(self.pos[0])+ " " + str(self.pos[1])) def getIntPos(self): """Returns the current ship position as a tuple of integers """ return (int(self.pos[0]),int(self.pos[1])) ############### VISUAL ################################# # Functions related to creating various visual effects o...
endpoint = [] pygame.draw.line(screen,(30,30,30),bp,getOffsetPos(g[1],midpos),1)
conditional_block
ship.py
self.weights.append(np.add(wt.copy(), np.random.normal(0,stray,(shp.dimensions[i],shp.dimensions[i+1])))) for i,bs in enumerate(shp.bias): self.bias.append(np.add(bs.copy(), np.random.normal(0,stray,shp.dimensions[i+1]))) self.normalizeWeights() self.colour = colour ...
self.dangle = self.dangle * self.drag*(1-brake/3)*0.6 self.angle += self.dangle self.accel = accel self.vx += accel * np.cos(self.angle) self.vy += accel * np.sin(self.angle) # flat cap on speed if(self.vx > self.maxSpeed): self.vx = self.maxSpeed if(self....
self.dangle += dangle
random_line_split
layers.py
2) bytes_labels = pkl.dumps(forward_labels, 2) # send message to next layer res = self.upper_layer_stub.UpdateInput( nn_pb.ForwardMsg(batch_id=batch_id, output_matrix=bytes_matrix, labels=bytes_labels, is_train=istrain)) # prin...
if batch_id % 100 == 0: print("Complete backpropagation for batch {} at {}".format( batch_id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) return nn_pb.PlainResponse(message="Received at layer {}".format( self.layer_name)) class HiddenLayer(Layer): """ hidden layer""" def ...
"""""" batch_id = req.batch_id
random_line_split
layers.py
"""""" train_X = self.train[0] train_y = self.train[1] val_X = self.val[0] val_y = self.val[1] train_size = train_X.shape[0] batch_id = 0 test_batch_id = -1 # use negative number, diff with batch_id for i in range(epochs): print("Start feed {0} epoch data".format(i)) train_...
delta = softmax_output - labels # compute delta for lower layer first # because current error is based on current weights partial_delta_for_lower = np.dot(delta, self.weights) # send to lower layer self.backward_to_lower(batch_id, partial_delta_for_lower, labels) # cross entropy los...
conditional_block
layers.py
: equals to inputs of this layer """ delta_shape = delta.shape inputs_shape = outputs_of_lower.shape # update biases avg_delta = np.mean(delta, axis=0).reshape(delta_shape[1], 1) self.biases = self.biases - lr * avg_delta # compute gradients for weights delta = delta.reshape(delta_shap...
OutputLayer
identifier_name
layers.py
oked by upper layer will be implemented by hidden layer """ pass class InputLayer(Layer): """ for input data""" def __init__(self, upper_layer, data_path, input_dim, layer_name="input"): super().__init__(layer_name, upper_layer, None, None, input_dim, No...
""" once received input from lower layer: compute weighted sum -> softmax output -> loss -> back propagate """ self.check_weights() batch_id, outputs_of_lower, labels, is_train = self.parse_forward_msg(req) weighted_sum = np.dot(outputs_of_lower, self.weights.transpose()) \ + se...
identifier_body
main.rs
} {:?}", token, events); if token == LISTENER { while let Ok(Some(socket)) = self.listener.accept() { debug!("accepted"); self.count += 1; // socket.0.set_nodelay(true).unwrap(); let token = self.connections .insert_...
struct Connection { socket: TcpStream, input: Vec<u8>, output: Output, keepalive: bool, closed: bool, read_closed: bool, events: EventSet, } struct Output { buf: Vec<u8>, } impl Connection { fn new(socket: TcpStream) -> Connection { Connection { socket: socket,...
random_line_split
main.rs
<'a> { count: u64, listener: &'a TcpListener, connections: Slab<Connection, usize>, } impl<'a> Server<'a> { fn new(listener: &'a TcpListener) -> Server<'a> { Server { count: 0, listener: listener, connections: Slab::new_starting_at(1, 1024), } } ...
Server
identifier_name
activedirectory.component.ts
}, { type : 'input', name : 'ad_bindpw', placeholder : 'Domain Account Password', tooltip : 'Password for the Active Directory administrator\ account. This setting is mandatory and the GUI refuses to save the\ settings if it cannot connect to the domain controller using this\ password...
{ return false; }
conditional_block
activedirectory.component.ts
AD check connectivity frequency (seconds)', tooltip : 'How often to verify that Active Directory services are\ active.', }, { type : 'input', name : 'ad_recover_retry', placeholder : 'How many recovery attempts', tooltip : 'Number of times to attempt reconnecting to the Active\ d...
{}
identifier_body
activedirectory.component.ts
if SSL connections are used. If a certificate does not exist yet,\ create a <a href="http://doc.freenas.org/11/system.html#cas"\ target="_blank">CA</a>, then create a certificate on the Active\ Directory server and import it to the FreeNAS system with\ <a href="http://doc.freenas.org/11/system.html#certificates"\ ...
this.ad_certificate = _.find(this.fieldConfig, {name : 'ad_certificate'}); res.forEach((item) => {
random_line_split
activedirectory.component.ts
input', name : 'ad_bindname', placeholder : 'Domain Account Name', tooltip : 'Name of the Active Directory administrator account.\ This setting is mandatory and the GUI refuses to save the settings\ if it cannot connect to the domain controller using this account name.', }, { type : 'i...
isCustActionVisible
identifier_name
parser.rs
_ecmascript::transforms::typescript; use swc_ecmascript::visit::FoldWith; let mut passes = chain!( Optional::new(jsx_pass, options.transform_jsx), proposals::decorators::decorators(proposals::decorators::Config { legacy: true, emit_metadata: options.emit_metadata }), helpers::inject_hel...
complex_types
identifier_name
parser.rs
, None)); } use swc_ecmascript::transforms::react; let program = Program::Module(module); let options = EmitOptions::default(); let source_map = std::rc::Rc::new(source_map); let jsx_pass = react::react( source_map.clone(), Some(&comments), react::Options { pragma: options.jsx_factory....
{ // Prefer content-type over extension. let url = Url::parse("https://deno.land/x/foo@0.1.0/bar.js").unwrap(); let content_type = Some("text/jsx".to_string()); let syntax = get_syntax(&url, &content_type); assert!(syntax.jsx()); assert!(!syntax.typescript()); // Fallback to extension if co...
identifier_body
parser.rs
if (import.kind == DependencyKind::Import || import.kind == DependencyKind::Export) && import.is_dynamic == false { let specifier = import.specifier.to_string(); deps.push(resolve_import(&specifier, url.as_str())?); } } // If the file is not jsx, ts, or tsx we do not need to tra...
fn test_get_syntax() { // Prefer content-type over extension. let url = Url::parse("https://deno.land/x/foo@0.1.0/bar.js").unwrap(); let content_type = Some("text/jsx".to_string());
random_line_split
main.rs
::mpsc; use libp2p::swarm::{SwarmBuilder, NetworkBehaviourEventProcess}; use tokio::io::AsyncBufReadExt; use std::collections::HashSet; use serde::{Serialize, Deserialize}; use log::{error, info}; const STORAGE_FILE_PATH: &str = "./recipes.json"; type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send...
{ floodsub: Floodsub, mdns: TokioMdns, #[behaviour(ignore)] response_sender: mpsc::UnboundedSender<ListResponse>, } #[tokio::main] async fn main() { pretty_env_logger::init(); info!("Peer Id: {}", PEER_ID.clone()); let (response_sender, mut response_rcv) = tokio::sync::mpsc::unbounded_cha...
RecipeBehaviour
identifier_name
main.rs
Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>; static KEYS: Lazy<identity::Keypair> = Lazy::new(|| identity::Keypair::generate_ed25519()); static PEER_ID: Lazy<PeerId> = Lazy::new(|| PeerId::from(KEYS.public())); static TOPIC: Lazy<Topic> = Lazy::new(|| Topic::new("recipes")); ...
id: new_id, name: name.to_owned(), ingredients: ingredients.to_owned(), instructions: instructions.to_owned(), public: false
random_line_split
main.rs
::mpsc; use libp2p::swarm::{SwarmBuilder, NetworkBehaviourEventProcess}; use tokio::io::AsyncBufReadExt; use std::collections::HashSet; use serde::{Serialize, Deserialize}; use log::{error, info}; const STORAGE_FILE_PATH: &str = "./recipes.json"; type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send...
} } } fn respond_with_publish_recipes(sender: mpsc::UnboundedSender<ListResponse>, receiver: String) { tokio::spawn(async move { match read_local_recipes().await { Ok(recipes) => { let resp = ListResponse { mode: ListMode::ALL, ...
{ error!("error creating recipe: {}", e); }
conditional_block
main.rs
ListRequest { mode: ListMode } #[derive(Debug, Serialize, Deserialize)] struct ListResponse { mode: ListMode, data: Recipes, receiver: String, } enum EventType { Response(ListResponse), Input(String) } #[derive(NetworkBehaviour)] struct RecipeBehaviour { floodsub: Floodsub, mdns: Tok...
{ let content = tokio::fs::read(STORAGE_FILE_PATH).await?; let result = serde_json::from_slice(&content)?; Ok(result) }
identifier_body
main.js
]); $("#content_chart").show(); }else if(graphic.type == "line-chart"){ var time=new Date(event.timestamp); time=(time.getUTCHours()+2)+ ":"+time.getUTCMinutes()+":"+time.getUTCSeconds(); var arrayTMP = new Array(); arrayTMP[0] = time; arrayTMP[1] = parseInt(event.sensorValues[0]); var dimGraphData = g...
function hideOverlay() { $("#overlay").hide(); $("#content_chart").empty(); $("#content_actuator").empty(); $("#values").empty(); if(Object.keys(sensor).length != 0) { listenSensor(operations.REMOVE); sensor = {}; graphic = undefined; } else if(Object.keys(actuator).length != 0) { actuator = {}; actC...
{ $("#overlay").show(); if(Object.keys(sensor).length != 0) { $("#sensorButton").show(); $("#serviceName").text(sensor.displayName); $("#serviceDescription").text(sensor.description); listenSensor(); } else if(Object.keys(actuator).length != 0) { $("#sensorButton").hide(); $("#serviceName").text(actuato...
identifier_body
main.js
]); $("#content_chart").show(); }else if(graphic.type == "line-chart"){ var time=new Date(event.timestamp); time=(time.getUTCHours()+2)+ ":"+time.getUTCMinutes()+":"+time.getUTCSeconds(); var arrayTMP = new Array(); arrayTMP[0] = time; arrayTMP[1] = parseInt(event.sensorValues[0]); var dimGraphData = g...
//actuator for (i = 0; i < actuatorServices.length; i++) { if (actuatorServices[i].id == id) { actuatorServices[i].bind({onBind:function(){ actuator = actuatorServices[i]; toFind = true; showOverlay(); } }); return; } } //DA VERIFICAREEEEEEEEEEEEE - TODO //toF...
{ if(sensorServices[i].id == id){ sensorServices[i].bind({onBind:function(){ sensorServices[i].configureSensor({rate: 1000, eventFireMode: "fixedinterval"}, function(){ sensor = sensorServices[i]; toFind = true; showOverlay(); }, function (){ sensor = undefined; co...
conditional_block
main.js
0]); $("#content_chart").show(); }else if(graphic.type == "line-chart"){ var time=new Date(event.timestamp); time=(time.getUTCHours()+2)+ ":"+time.getUTCMinutes()+":"+time.getUTCSeconds(); var arrayTMP = new Array(); arrayTMP[0] = time; arrayTMP[1] = parseInt(event.sensorValues[0]); var dimGraphData = ...
//toFind = true; } function showOverlay() { $("#overlay").show(); if(Object.keys(sensor).length != 0) { $("#sensorButton").show(); $("#serviceName").text(sensor.displayName); $("#serviceDescription").text(sensor.description); listenSensor(); } else if(Object.keys(actuator).length != 0) { $("#sensorButt...
return; } } //DA VERIFICAREEEEEEEEEEEEE - TODO
random_line_split
main.js
]); $("#content_chart").show(); }else if(graphic.type == "line-chart"){ var time=new Date(event.timestamp); time=(time.getUTCHours()+2)+ ":"+time.getUTCMinutes()+":"+time.getUTCSeconds(); var arrayTMP = new Array(); arrayTMP[0] = time; arrayTMP[1] = parseInt(event.sensorValues[0]); var dimGraphData = g...
(error){ } navigator.getUserMedia({video: true}, successCallback, errorCallback); detector = new AR.Detector(); requestAnimationFrame(tick); discoverFileSystem(); //discoverActuators(); //discoverSensors(); $("#back").text("Back"); $("#back").on("click", function(){ hideOverlay...
errorCallback
identifier_name
scheduler.rs
bootstrap a cluster with existing nodes.")); } info!("Bootstrapping cluster as node {}", node.node_id); self.state.master_node = Some(node.node_id.clone()); self.state.nodes.insert(node.node_id.clone(), node); Executor::from_registry().do_send(ExecutorCommand::UpdateState(self...
test_create_job
identifier_name
scheduler.rs
<String>, } impl ServiceSpec { /// Create ContainerOptions based on this service spec pub fn build_container_options(&self) -> Result<ContainerOptionsBuilder, Error> { let mut opt = ContainerOptions::builder(&*self.image); opt.volumes(self.volumes.iter().map(|i| &**i).collect()) .en...
} // Remove any allocations that don't correspond to any service for allocs in service_allocs.values() { to_remove.extend(allocs.iter().cloned()); } // Now we drop the index service_allocs and we can mutate the state for alloc_id in to_remove { s...
to_remove.extend(existing.iter().take(diff.abs() as usize).cloned()); } }
random_line_split
scheduler.rs
<AllocationId>> = HashMap::new(); for alloc in self.state.allocations.values() { service_allocs .entry((&alloc.job_id, &alloc.service_name)) .or_default() .push(alloc.allocation_id.clone()); } // Put the changes we need to make here, s...
{ let job: JobSpec = serde_yaml::from_str(TEST_JOB_SPEC).expect("Failed to parse sample job spec"); with_bootstrap_node(|| { Scheduler::from_registry() .send(SchedulerCommand::CreateJob(String::from("test-job"), job)) .and_then(move |res| { ...
identifier_body
lib.rs
with the given name and runner. /// /// The runner returning `Ok(())` is interpreted as the test passing. If the /// runner returns `Err(_)`, the test is considered failed. pub fn test<R>(name: impl Into<String>, runner: R) -> Self where R: FnOnce() -> Result<(), Failed> + Send + 'static, ...
_ => {} }; } // If any skip pattern were specified, test for all patterns.
random_line_split
lib.rs
test` uses internal `std` functions to temporarily redirect output. //! `libtest-mimic` cannot use those. See [this issue][capture] for more //! information. //! - `--format=json|junit` //! //! [capture]: https://github.com/LukasKalbertodt/libtest-mimic/issues/9 #![forbid(unsafe_code)] use std::{process, sync::mp...
{ /// The test passed. Passed, /// The test or benchmark failed. Failed(Failed), /// The test or benchmark was ignored. Ignored, /// The benchmark was successfully run. Measured(Measurement), } /// Contains information about the entire test run. Is returned by[`run`]. /// /// This t...
Outcome
identifier_name
lib.rs
test` uses internal `std` functions to temporarily redirect output. //! `libtest-mimic` cannot use those. See [this issue][capture] for more //! information. //! - `--format=json|junit` //! //! [capture]: https://github.com/LukasKalbertodt/libtest-mimic/issues/9 #![forbid(unsafe_code)] use std::{process, sync::mp...
/// Creates a benchmark with the given name and runner. /// /// If the runner's parameter `test_mode` is `true`, the runner function /// should run all code just once, without measuring, just to make sure it /// does not panic. If the parameter is `false`, it should perform the /// actual benc...
{ Self { runner: Box::new(move |_test_mode| match runner() { Ok(()) => Outcome::Passed, Err(failed) => Outcome::Failed(failed), }), info: TestInfo { name: name.into(), kind: String::new(), is_igno...
identifier_body
websocket.rs
) -> fmt::Result { use self::PossibleErr::*; match *self{ Ws(ref w) => w.fmt(f), String(ref s) => s.fmt(f), GraphErr(ref g) => g.fmt(f), JsonErr(ref j) => j.fmt(f), Disp(ref d) => d.fmt(f), None => (None).fmt...
fn encode_update<T: Into<Update>>(update: T) -> WsResult<Message>{ match serde_json::to_string(&update.into()){ Ok(s) => Ok(Message::Text(s)), Err(e) => Err(WsError::new(WsErrorKind::Internal, format!("encode_update failed {:?}", e))) } } struct ClientCommon; impl ClientCommon{ fn on_ope...
{ match serde_json::to_string(&response){ Ok(s) => Ok(Message::Text(s)), Err(e) => Err(WsError::new(WsErrorKind::Internal, format!("encode_response failed {:?}", e))) } }
identifier_body
websocket.rs
} } impl From<GraphErr> for PossibleErr{ fn from(g: GraphErr) -> PossibleErr{ PossibleErr::GraphErr(g) } } impl From<serde_json::Error> for PossibleErr{ fn from(j: serde_json::Error) -> PossibleErr{ PossibleErr::JsonErr(j) } } fn to_ws_err(e: PossibleErr, kind: WsErrorKind) -> WsErr...
struct ServerFactory{ store: GraphStore,
random_line_split
websocket.rs
) -> fmt::Result { use self::PossibleErr::*; match *self{ Ws(ref w) => w.fmt(f), String(ref s) => s.fmt(f), GraphErr(ref g) => g.fmt(f), JsonErr(ref j) => j.fmt(f), Disp(ref d) => d.fmt(f), None => (None).fmt...
(out: &Sender, store: &GraphStore, id: GraphId) -> Result<Self>{ ClientCommon::on_open(out, store, id, ClientType::Backend)?; trace!("Backend attached to GraphId {}", id); Ok(BackendClient{ graph: id }) } fn on_command(&self, out: &Sender, store: &GraphStore, command:...
on_open
identifier_name
ecxgboost_predicttemp_gpu_multi_live_hourly.py
][indexlon]) vstring.append(latlonArray[indexlat][indexlon + 1]) vstring.append(latlonArray[indexlat + 1][indexlon + 1]) vstring.append(latlonArray[indexlat + 1][indexlon]) vstring.append(latlonArray[indexlat - 1][indexlon - 1]) vstring.append(latlonArray[indexlat - 1][indexlon]) vstring.append(...
latlonArray[indexlat
identifier_name
ecxgboost_predicttemp_gpu_multi_live_hourly.py
>"' + pdate + '" and forecast_time<="' + odate + '" group by city_id' print sql cursor001.execute(sql) rows = cursor001.fetchall() if rows==(): #logger.info('该时间段没有数据' +sql) print '该时间段没有数据' return #实况数据 sql_live = 'select v01000,AVG(TEM),MAX(TEM_Max),MIN(TEM_Min) from t_...
sql_into='replace into t_r_3h_temp_accu_mos_dem(initial_time,forecast_hours,temp_accu,temp_mae,temp_rmse)VALUES ("'+initial+'","'+str(ii)+'","'+str(accu)+'","'+str(mae)+'","'+str(rmse)+'")' #print sql_into #logger.info(sql_into) cursor=db.cursor() cursor.execute(sql_into) db...
identifier_body
ecxgboost_predicttemp_gpu_multi_live_hourly.py
)VALUES(%s,%s,%s,%s,%s,%s,%s,%s)' L = [] for j in range(len(stationlist)): perstationlist = [] stationid = stationlist[j][0] temp = result[j] # 每个站点存储 perstationlist.append(stationid) perstationlist.append(origin) perstationlist.append(forecast) pe...
db.commit()
random_line_split
ecxgboost_predicttemp_gpu_multi_live_hourly.py
预报时刻的准确率 def calculate_temp_h_accurity(db,initial,odate,ii): #计算一个起始预报时次的所有预报的准确率。 cursor001 = db.cursor() sql = 'select city_id,initial_time,temperature from t_r_ec_city_forecast_ele_mos_dem where initial_time="' + initial + '" and forecast_time="' + odate + '"' #print sql cursor001.execute(sql) ...
db = MySQLdb.co
conditional_block
levels.go
Skips++ updateStats(it.Value()) continue } // See if we need to skip this key. if len(skipKey) > 0 { if y.SameKey(it.Key(), skipKey) { numSkips++ updateStats(it.Value()) continue } else { skipKey = skipKey[:0] } } if !y.SameKey(it.Key(), lastKey) { if builder...
if !s.cstatus.compareAndAdd(thisAndNextLevelRLocked{}, *cd) {
random_line_split
levels.go
compactDef) bool { cd.lockLevels() defer cd.unlockLevels() tbls := make([]*table.Table, len(cd.thisLevel.tables)) copy(tbls, cd.thisLevel.tables) if len(tbls) == 0 { return false } // Find the biggest table, and compact that first. // TODO: Try other table picking strategies. sort.Slice(tbls, func(i, j int...
appendIteratorsReversed
identifier_name
levels.go
true } func (s *levelsController) fillTables(cd *compactDef) bool { cd.lockLevels() defer cd.unlockLevels() tbls := make([]*table.Table, len(cd.thisLevel.tables)) copy(tbls, cd.thisLevel.tables) if len(tbls) == 0 { return false } // Find the biggest table, and compact that first. // TODO: Try other table ...
{ return *maxVs, nil }
conditional_block
levels.go
(t.Biggest()), 0), } if s.cstatus.overlapsWith(cd.thisLevel.level, cd.thisRange) { continue } cd.top = []*table.Table{t} left, right := cd.nextLevel.overlappingTables(levelHandlerRLocked{}, cd.thisRange) cd.bot = make([]*table.Table, right-left) copy(cd.bot, cd.nextLevel.tables[left:right]) if len(...
{ // Just like with get, it's important we iterate the levels from 0 on upward, to avoid missing // data when there's a compaction. for _, level := range s.levels { iters = level.appendIterators(iters, opt) } return iters }
identifier_body
DataHost.py
% argname) return val def validate_iplist(argname, param, safe): """Validates that an argument is an array of strings, each of which is a valid IP address. Checks that an argument named `argname` is either a single string or an array of strings, each of which is convertible to an `IPAddress` object. If ...
(self): with self._cv: while not self._stopme: npending = 0 ncurreq = len(self._requests) # Insert any new requests. If they fail, remember the error. for r in self._requests: if not r.reply.submitted: debug("HOSTDATA", 1, "submitting request: %s %s", r.k...
run
identifier_name
DataHost.py
" % argname) return val def validate_iplist(argname, param, safe): """Validates that an argument is an array of strings, each of which is a valid IP address. Checks that an argument named `argname` is either a single string or an array of strings, each of which is convertible to an `IPAddress` object. If...
:arg float maxwait: maximum time in seconds to wait for a result. """ reply = Reply() reply.kind = kind reply.until = time.time() + maxwait reply.signal = random.choice(self._signals) reply.pending = set(hosts) with self._cv: self._requests.append(Task(kind, hosts, reply)) s...
:arg str kind: "ip" or "name" :arg list hosts: list of host name string, ip address or a real name
random_line_split
DataHost.py
" % argname) return val def validate_iplist(argname, param, safe): """Validates that an argument is an array of strings, each of which is a valid IP address. Checks that an argument named `argname` is either a single string or an array of strings, each of which is convertible to an `IPAddress` object. If...
# Pump any pending lookups for up to .25 seconds. Note that this # will wait only as long as needed, and will quit immediately # if there is no work at all. It's not unusual we need to wait # longer than this for final results; see the check further on. try: self._cv....
if not r.reply.submitted: debug("HOSTDATA", 1, "submitting request: %s %s", r.kind, r.hosts) r.reply.submitted = True try: self._ip2i.submit(r.hosts, kind=r.kind, callback=r.reply) except Exception, e: r.reply.error = e
conditional_block
DataHost.py
% argname) return val def validate_iplist(argname, param, safe): """Validates that an argument is an array of strings, each of which is a valid IP address. Checks that an argument named `argname` is either a single string or an array of strings, each of which is convertible to an `IPAddress` object. If ...
def statistics(self): with self._cv: return self._ip2i.statistics() def reset_statistics(self): with self._cv: self._ip2i.reset_statistics() def purge(self): with self._cv: self._purge() def stop(self): debug("HOSTDATA", 1, "requesting to stop resolved thread") with sel...
"""Utility to resolve host information.""" _PURGE_INTERVAL = 4*3600 _NUM_SIGS = 8 def __init__(self, statedir): Thread.__init__(self, name = "HostCache") self._ip2i = IPResolver(cachedir = statedir, maxtime=15) self._cv = Condition() self._stopme = False self._requests = [] self._last_pur...
identifier_body
datacreator.py
ufuu.report.models import ReportManga from fufufuu.tag.enums import TagType from fufufuu.tag.models import Tag, TagData, TagAlias #------------------------------------------------------------------------------- CONFIGURATION = { 'default': { 'BLOG': 30, 'COMMENTS': [0, 0, 0, 0, 0, 1, 2, 3], ...
create_blog_entries
identifier_name
datacreator.py
MangaStatus from fufufuu.manga.models import Manga, MangaTag, MangaPage from fufufuu.report.enums import ReportStatus, ReportMangaType from fufufuu.report.models import ReportManga from fufufuu.tag.enums import TagType from fufufuu.tag.models import Tag, TagData, TagAlias #--------------------------------------------...
@timed def create_tags(self): tag_list = [] for tag_type in TagType.manga_m2m: for i in range(1, self.config['TAGS']+1): name = '{} {}'.format(TagType.choices_dict[tag_type], i) tag = Tag(tag_type=tag_type, name=name, slug=slugify(name), created_by=s...
create_user_helper('testuser{}'.format(i))
conditional_block
datacreator.py
MangaStatus from fufufuu.manga.models import Manga, MangaTag, MangaPage from fufufuu.report.enums import ReportStatus, ReportMangaType from fufufuu.report.models import ReportManga from fufufuu.tag.enums import TagType from fufufuu.tag.models import Tag, TagData, TagAlias #--------------------------------------------...
@timed def assign_manga_collection(self): manga_id_set = set(Manga.published.all().values_list('id', flat=True)) for i in range(1, self.config['TAGS_FK']+1): collection_name = 'Collection {}'.format(i) collection = Tag(tag_type=TagType.COLLECTION, name=collection_name, ...
manga_id_set = set(Manga.published.all().values_list('id', flat=True)) for i in range(1, self.config['TAGS_FK']+1): tank_name = 'Tank {}'.format(i) tank = Tag(tag_type=TagType.TANK, name=tank_name, slug=slugify(tank_name), created_by=self.user, updated_by=self.user) tank.save...
identifier_body
datacreator.py
1, 'REPORTS': 1, 'TAGS': 1, 'TAGS_FK': 1, 'USERS': 1, } } CHUNK_SIZE = 100 #------------------------------------------------------------------------------- def timed(func): """ use @timed to decorate a function that will print out the time it took for this function to ...
random_line_split
commands.py
"""Pretty-print the current kraftwerk configuration.""" pprint.pprint(config) @command def create_node(config, args): """Commissions a new server node.""" log = logging.getLogger('kraftwerk.create-node') if 'pubkey' in config: pubkey_paths = [config["pubkey"]] else: pubkey...
stab.parser.add_argument('node', action=NodeAction, nargs='?', help="Server node to interact with.") stab.parser.add_argument('project', action=ProjectAction, nargs='?', help="Project root directory path. Defaults to current directory.") stab.parser.add_argument('--script', '-s', nargs='+', requir...
"""Execute a shell command in the project environment. Useful for django-admin.py syncdb and such.""" cmd = config.template("scripts/env.sh", project=args.project) cmd = '\n'.join([cmd, ' '.join(args.script)]) args.node.ssh(cmd, user=args.user)
identifier_body
commands.py
"""Pretty-print the current kraftwerk configuration.""" pprint.pprint(config) @command def create_node(config, args): """Commissions a new server node.""" log = logging.getLogger('kraftwerk.create-node') if 'pubkey' in config: pubkey_paths = [config["pubkey"]] else: pubkey_pa...
dump.parser.add_argument('project', action=ProjectAction, nargs='?', help="Project root directory path. Defaults to current directory.") @command def load(config, args):
help="Server node to interact with.")
random_line_split
commands.py
"""Pretty-print the current kraftwerk configuration.""" pprint.pprint(config) @command def create_node(config, args): """Commissions a new server node.""" log = logging.getLogger('kraftwerk.create-node') if 'pubkey' in config: pubkey_paths = [config["pubkey"]] else: pubkey_pa...
if type(public_ip) == list: public_ip = public_ip[0] # At least EC2 passes only back hostname if not IP_RE.match(public_ip): public_ip = gethostbyname(public_ip) if confirm("Create /etc/hosts entry?"): etchosts.set_etchosts(args.hostname, public_ip) print u"Node %s (...
if node.id == node_.id and node_.public_ip: public_ip = node_.public_ip[0]
conditional_block
commands.py
(config, args): """Pretty-print the current kraftwerk configuration.""" pprint.pprint(config) @command def create_node(config, args): """Commissions a new server node.""" log = logging.getLogger('kraftwerk.create-node') if 'pubkey' in config: pubkey_paths = [config["pubkey"]] else...
show_config
identifier_name
v2.rs
impl AsRef<Path>, index_db_size: usize, update_db_size: usize, indexing_options: &IndexerOpts, ) -> anyhow::Result<()>
patch_updates(update_dir, update_path)?; v3::load_dump( meta, src, dst, index_db_size, update_db_size, indexing_options, ) } fn patch_index_uuid_path(path: &Path) -> Option<PathBuf> { let uuid = path.file_name()?.to_str()?.trim_start_matches("index-"); ...
{ let indexes_path = src.as_ref().join("indexes"); let dir_entries = std::fs::read_dir(indexes_path)?; for entry in dir_entries { let entry = entry?; // rename the index folder let path = entry.path(); let new_path = patch_index_uuid_path(&path).expect("invalid index folder...
identifier_body
v2.rs
impl AsRef<Path>, index_db_size: usize, update_db_size: usize, indexing_options: &IndexerOpts, ) -> anyhow::Result<()> { let indexes_path = src.as_ref().join("indexes"); let dir_entries = std::fs::read_dir(indexes_path)?; for entry in dir_entries { let entry = entry?; // renam...
(path: &Path) -> Option<PathBuf> { let uuid = path.file_name()?.to_str()?.trim_start_matches("index-"); let new_path = path.parent()?.join(uuid); Some(new_path) } fn patch_settings(path: impl AsRef<Path>) -> anyhow::Result<()> { let mut meta_file = File::open(&path)?; let mut meta: Value = serde_js...
patch_index_uuid_path
identifier_name
v2.rs
impl AsRef<Path>, index_db_size: usize, update_db_size: usize, indexing_options: &IndexerOpts, ) -> anyhow::Result<()> { let indexes_path = src.as_ref().join("indexes"); let dir_entries = std::fs::read_dir(indexes_path)?; for entry in dir_entries { let entry = entry?; // renam...
compat::UpdateResult::DocumentsAddition(r) => Self::DocumentsAddition(r), compat::UpdateResult::DocumentDeletion { deleted } => { Self::DocumentDeletion { deleted } } compat::UpdateResult::Other => Self::Other, } } } /// compat structure from ...
impl From<compat::UpdateResult> for UpdateResult { fn from(other: compat::UpdateResult) -> Self { match other {
random_line_split
subtour2opt.py
.nodes_y[node1] - self.nodes_y[node2] edge_dist = math.sqrt(dx*dx + dy*dy) return edge_dist def edge_hash(self, node1, node2): return hash( ( min(node1,node2), max(node1,node2) ) ) % EDGE_HASH_TABLE_SIZE def edge_exists(self, node1, node2): # return TourEngine.edges[self.edge_...
for line in lines: fout.write(line+'\n') fout.close() print '\nWrote 2-OPT tours to: ', outfile, '\n' def chunks(l, n): # split a list into chunks of length n return [l[i:i+n] for i in range(0, len(l), n)] def shuffled_paths(node_list, path_len): return [random.sample(path, len(path)) ...
random_line_split
subtour2opt.py
.nodes_y[node1] - self.nodes_y[node2] edge_dist = math.sqrt(dx*dx + dy*dy) return edge_dist def edge_hash(self, node1, node2): return hash( ( min(node1,node2), max(node1,node2) ) ) % EDGE_HASH_TABLE_SIZE def edge_exists(self, node1, node2): # return TourEngine.edges[self.edge_...
(self, node1, node2, node3, node4): # does a swap, updating self.next_node array in-place assert node2 == self.next_node[node1], 'node2 does not follow node1 in tour' assert node4 == self.next_node[node3], 'node4 does not follow node3 in tour' self.next_node[node1] = node3 self....
do_swap
identifier_name
subtour2opt.py
(( self.dist(n1,n2) for n1, n2 in enumerate(next_node[:-1]))) def get_edge_counts(self): # return (TourEngine.edges.min(), TourEngine.edges.max()) edges = TourEngine.edges ecounts = {} for e in edges: ecounts[edges[e]] = ecounts.setdefault(edges[e],0) + 1 return ...
improving = False
conditional_block
subtour2opt.py
.nodes_y[node1] - self.nodes_y[node2] edge_dist = math.sqrt(dx*dx + dy*dy) return edge_dist def edge_hash(self, node1, node2): return hash( ( min(node1,node2), max(node1,node2) ) ) % EDGE_HASH_TABLE_SIZE def edge_exists(self, node1, node2): # return TourEngine.edges[self.edge_...
def write_tours(tour1, tour2, outfile): fout = open(outfile, 'w') fout.write('path1,path2\n') lines = [str(n1)+','+str(n2) for n1, n2 in izip(tour1, tour2)] for line in lines: fout.write(line+'\n') fout.close() print '\nWrote 2-OPT tours to: ', outfile, '\n' def chunks(l, n): # sp...
df = pandas.read_csv(tour_file) tour1, tour2 = list(df['path1']), list(df['path2']) return (tour1, tour2)
identifier_body
reedsolomon.go
data to fill the number of requested shards") // ErrReconstructRequired is returned if too few data shards are intact and // a reconstruction is required before you can successfully join the shards. ErrReconstructRequired = errors.New("reconstruction required as one or more required data shards are nil") ) // Ree...
(shards [][]byte, dataOnly bool) error { if len(shards) != r.shards { return ErrTooFewShards } err := checkShards(shards, true) if err != nil { return err } shardSize := shardSize(shards) // Quick check: are all of the shards present (or, if dataOnly, all of the // data shards)? If so, there's nothing to ...
reconstruct
identifier_name
reedsolomon.go
} return r, nil } // Encode encodes parity for a set of shards. The number of shards must match // the number given to New, and each shard must have the same capacity. The data // in the first r.DataShards elements will be used to generate parity, which is // written into the remaining elements. func (r *ReedSolomo...
{ chunkSize := r.DataShards * subsize numChunks := len(data) / chunkSize if len(data)%chunkSize != 0 { numChunks++ } // extend shards to proper len shardSize := numChunks * subsize for i := range shards { if cap(shards[i]) < shardSize { return errors.New("each shard must have capacity of at least len(dat...
identifier_body
reedsolomon.go
data to fill the number of requested shards") // ErrReconstructRequired is returned if too few data shards are intact and // a reconstruction is required before you can successfully join the shards. ErrReconstructRequired = errors.New("reconstruction required as one or more required data shards are nil") ) // Ree...
// Invert the matrix, so we can go from the encoded shards back to the // original data. Then pull out the row that generates the shard that we // want to decode. Note that since this matrix maps back to the original // data, it can be used to create a data shard, but not a parity shard. dataDecodeMatrix, err := ...
{ for c := 0; c < r.DataShards; c++ { subMatrix[subMatrixRow][c] = r.m[validIndex][c] } }
conditional_block
reedsolomon.go
divisible by 32 do = (do + 31) & (^31) start := 0 for start < byteCount { if start+do > byteCount { do = byteCount - start } wg.Add(1) go func(start, stop int) { for c := 0; c < r.DataShards; c++ { in := inputs[c][start:stop] for iRow, out := range outputs { if c == 0 { galMulSlice(...
random_line_split
SIPResponse.go
= "Bad Event" case REQUEST_PENDING: retval = "Request Pending" case SERVER_INTERNAL_ERROR: retval = "Server Internal Error" case UNDECIPHERABLE: retval = "Undecipherable" case NOT_IMPLEMENTED: retval = "Not implemented" case BAD_GATEWAY: retval = "Bad gateway" case SERVICE_UNAVAILABLE: retval =...
// /** // * Make a clone (deep copy) of this object. // *@return a deep copy of this object. // */ // public Object clone() { // SIPResponse retval = (SIPResponse) super.clone(); // retval.statusLine = (StatusLine) this.statusLine.clone(); // return retval; // } // /** //...
{ retval := this.SIPMessage.GetMessageAsEncodedStrings() if this.statusLine != nil { retval.PushFront(this.statusLine.String()) } return retval }
identifier_body
SIPResponse.go
the range 200 and 700. // */ func (this *SIPResponse) IsFinalResponseFromInt(rc int) bool { return rc >= 200 && rc < 700 } // /** Is this a final response? // *@return true if this is a final response. // */ func (this *SIPResponse) IsFinalResponse() bool { return this.IsFinalResponseFromInt(this.sta...
GetDialogId2
identifier_name
SIPResponse.go
IllegalArgumentException if nil string // */ func (this *SIPResponse) SetReasonPhrase(reasonPhrase string) { //if this.reasonPhrase == nil) // throw new IllegalArgumentException("Bad reason phrase"); if this.statusLine == nil { this.statusLine = header.NewStatusLine() } this.statusLine.SetReasonPhrase(re...
{ retval.WriteString(core.SIPSeparatorNames_COLON) retval.WriteString(from.GetTag()) }
conditional_block
SIPResponse.go
retval = "Bad Event" case REQUEST_PENDING: retval = "Request Pending" case SERVER_INTERNAL_ERROR: retval = "Server Internal Error" case UNDECIPHERABLE: retval = "Undecipherable" case NOT_IMPLEMENTED: retval = "Not implemented" case BAD_GATEWAY: retval = "Bad gateway" case SERVICE_UNAVAILABLE: r...
// /** // * Match with a template. // *@param matchObj template object to match ourselves with (nil // * in any position in the template object matches wildcard) // */ // public boolean match(Object matchObj) { // if (matchObj == nil) return true; // else if ( ! matchObj.GetClass().e...
// super.equals(other); // }
random_line_split
clone.go
printRepositoryInfo(i) uuid := getCurrentIndexUUID(dir) if uuid == i.UUID { fmtc.Println("{g}Looks like you already have the same set of data{!}") return } if !options.GetB(OPT_YES) { ok, err := terminal.ReadAnswer("Clone this repository?", "N") fmtc.NewLine() if !ok || err != nil { os.Exit(0) }...
info.AddOption(OPT_VER, "Show version") info.AddExample( "https://rbinstall.kaos.st /path/to/clone",
random_line_split
clone.go
s}" if options.GetB(OPT_NO_COLOR) { fmtc.DisableColors = true } switch { case fmtc.IsTrueColorSupported(): colorTagApp, colorTagVer = "{#CC1E2C}", "{#CC1E2C}" case fmtc.Is256ColorsSupported(): colorTagApp, colorTagVer = "{#160}", "{#160}" default: colorTagApp, colorTagVer = "{r}", "{r}" } } // checkAr...
string, a
identifier_name
clone.go
OPT_COMPLETION = "completion" OPT_GENERATE_MAN = "generate-man" ) // ////////////////////////////////////////////////////////////////////////////////// // // INDEX_NAME is name of index file const INDEX_NAME = "index3.json" // ////////////////////////////////////////////////////////////////////////////////// // ...
if !fsutil.IsExecutable(dir) { printErrorAndExit("Directory %s is not executable", dir) } } // cloneRepository start repository clone process func cloneRepository(url, dir string) { fmtc.Printf("Fetching index from {*}%s{!}…\n", url) i, err := fetchIndex(url) if err != nil { printErrorAndExit(err.Error()) ...
printErrorAndExit("Directory %s is not readable", dir) }
conditional_block
clone.go
("Target %s is not a directory", dir) } if !fsutil.IsReadable(dir) { printErrorAndExit("Directory %s is not readable", dir) } if !fsutil.IsExecutable(dir) { printErrorAndExit("Directory %s is not executable", dir) } } // cloneRepository start repository clone process func cloneRepository(url, dir string) { ...
age() switch options.GetS(OPT_COMPLETION) { case "bash": fmt.Printf(bash.Generate(info, "rbinstall-clone")) case "fish": fmt.Printf(fish.Generate(info, "rbinstall-clone")) case "zsh": fmt.Printf(zsh.Generate(info, optMap, "rbinstall-clone")) default: return 1 } return 0 } // printMan pr
identifier_body
lib.rs
>; /// Generate data from the configuration in the spec. /// /// Provide a writer that the line protocol should be written to. /// /// If `start_datetime` or `end_datetime` are `None`, the current datetime will /// be used. pub async fn generate<T: DataGenRng>( spec: &specification::DataSpec, points_writer_bu...
let expected_line_protocol = "cpu up=f 10000000000\n"; assert_eq!(line_protocol, expected_line_protocol); // Don't get any points anymore because we're past the ending datetime
random_line_split
lib.rs
_2018_idioms)] #![warn( missing_copy_implementations, missing_debug_implementations, missing_docs, clippy::explicit_iter_loop, clippy::future_not_send, clippy::use_self, clippy::clone_on_ref_ptr )] use crate::substitution::Substitute; use rand::Rng; use rand_seeder::Seeder; use snafu::{Resu...
(&mut self, dest: &mut [u8]) { self.rng.fill_bytes(dest); } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> std::result::Result<(), rand::Error> { self.rng.try_fill_bytes(dest) } } /// Gets the current time in nanoseconds since the epoch pub fn now_ns() -> i64 { let since_the_epoch = ...
fill_bytes
identifier_name
lib.rs
_2018_idioms)] #![warn( missing_copy_implementations, missing_debug_implementations, missing_docs, clippy::explicit_iter_loop, clippy::future_not_send, clippy::use_self, clippy::clone_on_ref_ptr )] use crate::substitution::Substitute; use rand::Rng; use rand_seeder::Seeder; use snafu::{Resu...
/// Generate a random GUID pub fn guid(&mut self) -> uuid::Uuid { let mut bytes = [0u8; 16]; self.rng.fill_bytes(&mut bytes); uuid::Builder::from_bytes(bytes) .set_variant(uuid::Variant::RFC4122) .set_version(uuid::Version::Random) .build() } } ...
{ let seed = seed.into(); Self { rng: Seeder::from(&seed).make_rng(), seed, } }
identifier_body
lib.rs
_2018_idioms)] #![warn( missing_copy_implementations, missing_debug_implementations, missing_docs, clippy::explicit_iter_loop, clippy::future_not_send, clippy::use_self, clippy::clone_on_ref_ptr )] use crate::substitution::Substitute; use rand::Rng; use rand_seeder::Seeder; use snafu::{Resu...
let mut agent = agent::Agent::<T>::new( agent_spec, &agent_name, agent_id, &seed, agent_tags, start_datetime, end_datetime, execution_start_time, continue_on, ...
{ agent_tags.push(tag::Tag::new(name_tag_key, &agent_name)); }
conditional_block