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
utils.py
newimagedb.close() return True #================================================================================= # Eigentextures #================================================================================= class Eigentextures: ''' This class implements the principal components anal...
v=self.getPC(numpc) dumpMatrix2File(v,filename) return
identifier_body
utils.py
image[0:ldrows,ldcols:ldcols+image.shape[1]]=image[image.shape[0]-ldrows:image.shape[0],:] # Fills bottom border dummyimage[(ldrows+image.shape[0]):,ldcols:(ldcols+image.shape[1])]=image[0:udrows,:] # Fills left border dummyimage[ldrows:ldrows+image.shape[0],0:ldcols]=image[:,i...
getEigentexturesEVR
identifier_name
utils.py
.asarray(np.zeros(shapes.shape[0])) ay=np.asarray(np.zeros(shapes.shape[0])) tx=np.asarray(np.zeros(shapes.shape[0])) ty=np.asarray(np.zeros(shapes.shape[0])) # The "while" loop checks the convergence of the alignment. # The convergence is checked measuring the difference of previous mean_shape...
else: break f.seek(pointer_to_write) if f.readline()!="": print "Attention!The provided array has less elements than\n" print "the number of lines in the file." f.close() return #==========...
x=buf.find('\n') line=buf[0:x+1] #print 'line= '+line new_line=line.rstrip('\n')+sep+str(a[i])+'\n' #print 'new_line= '+new_line invasion=len(new_line) #print 'size of invasion='+str(invasion) buf=buf[x+1::] ...
conditional_block
utils.py
ax=np.asarray(np.zeros(shapes.shape[0])) ay=np.asarray(np.zeros(shapes.shape[0])) tx=np.asarray(np.zeros(shapes.shape[0])) ty=np.asarray(np.zeros(shapes.shape[0])) # The "while" loop checks the convergence of the alignment. # The convergence is checked measuring the difference of previous mean...
def reticulate(h=302,w=527,s=15,l=2): ret=np.array(np.zeros((h,w))) ret=ret+255 for i in range(l): ret[:,i::s]=0 ret[i::s]=0 return ret #=================================================================== # crop # # im -> image (numpy array) # ox -> column to start crop (...
#============================================================
random_line_split
main.rs
InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::{ channel::{Channel, Message}, gateway::GatewayIntents, id::{ChannelId, GuildId, UserId}, user...
Some("!setroleassign") => { handle_set_reaction_message( &words.collect::<Vec<_>>(), msg.channel_id, msg.guild_id.expect("Tried to set role assignment message in non-guild"), &msg.author, http, msg, ...
{ handle_show_theme_count( msg.channel_id, msg.guild_id.expect("Tried to show theme idea count in non-guild"), &msg.author, http ).await?; }
conditional_block
main.rs
InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::{ channel::{Channel, Message}, gateway::GatewayIntents, id::{ChannelId, GuildId, UserId}, user...
( http: HttpClient, channel_id: ChannelId, user_id: UserId, guild_id: GuildId, ) -> Result<()> { let standard_message = //"Send me a PM to submit theme ideas.\n\n\ "Get a role to signify one of your skill sets with the command `!role <role name>`\n\ and leave a role with `!le...
send_help_message
identifier_name
main.rs
InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::{ channel::{Channel, Message}, gateway::GatewayIntents, id::{ChannelId, GuildId, UserId}, user...
async fn handle_event( event: (u64, Event), http: HttpClient, current_user: &CurrentUser ) -> Result<()> { match event { (_, Event::MessageCreate(msg)) => { // Don't send replies to yourself if msg.author.id != current_user.id { if is_pm(&http, msg.chann...
{ match http.channel(channel_id).await?.unwrap() { Channel::Private(_) => Ok(true), _ => Ok(false) } }
identifier_body
main.rs
::{Channel, Message}, gateway::GatewayIntents, id::{ChannelId, GuildId, UserId}, user::CurrentUser, }, }; mod channel; mod reaction; mod role; mod roles; mod state; mod theme; mod utils; use channel::{handle_create_channels, handle_remove_channels, handle_clear_channel_associations, handle...
if has_role(&http, guild_id, user_id, ORGANIZER).await? { format!("{}\n\n{}", standard_message, organizer_message) } else { standard_message.to_string()
random_line_split
instance.py
, expiration: datetime.datetime, enable_iam_auth: bool, ) -> None: self.ip_addrs = ip_addrs self.database_version = database_version self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # update ssl.PROTOCOL_TLS_CLIENT default self.context.check_hostname = ...
(self) -> None: """ Forces a new refresh attempt immediately to be used for future connection attempts. """ # if next refresh is not already in progress, cancel it and schedule new one immediately if not self._refresh_in_progress.is_set(): self._next.cancel() ...
force_refresh
identifier_name
instance.py
IP addressess with the given preference are found, an error is raised.""" if ip_type.value in self.ip_addrs: return self.ip_addrs[ip_type.value] raise CloudSQLIPTypeError( "Cloud SQL instance does not have any IP addresses matching " f"preference: {ip_type.va...
await asyncio.sleep(delay)
conditional_block
instance.py
str, expiration: datetime.datetime, enable_iam_auth: bool,
# update ssl.PROTOCOL_TLS_CLIENT default self.context.check_hostname = False # verify OpenSSL version supports TLSv1.3 if ssl.HAS_TLSv1_3: # force TLSv1.3 if supported by client self.context.minimum_version = ssl.TLSVersion.TLSv1_3 # fallback to TLSv1.2 f...
) -> None: self.ip_addrs = ip_addrs self.database_version = database_version self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
random_line_split
instance.py
class InstanceMetadata: ip_addrs: Dict[str, Any] context: ssl.SSLContext database_version: str expiration: datetime.datetime def __init__( self, ephemeral_cert: str, database_version: str, ip_addrs: Dict[str, Any], private_key: bytes, server_ca_cer...
PUBLIC: str = "PRIMARY" PRIVATE: str = "PRIVATE" PSC: str = "PSC"
identifier_body
statutes_parse.py
): """ Exception is raised if a unit in a refren cannot be parsed. """ pass class StatutesParser(StatutesProcessor): """ Class to parse the content of a reference area identified by StatutesExtractor """ def parse_main(self, main_text: str) -> list: """ Parses a strin...
else: return lawid elif match_type == "internal": if current_lawid is None: raise Exception("Current law id must be set for internal reference") return current_lawid else: return None # match_type: ignore or unknown @st...
rt len(lawid) == 2 if lawid[0] in self.laws_lookup.values(): return lawid[0] elif lawid[1] in self.laws_lookup.values(): return lawid[1] else: return lawid[1]
conditional_block
statutes_parse.py
(Exception): """ Exception is raised if a unit in a refren cannot be parsed. """ pass class StatutesParser(StatutesProcessor): """ Class to parse the content of a reference area identified by StatutesExtractor """
def parse_main(self, main_text: str) -> list: """ Parses a string containing a reference to a specific section within a given law. E.g. "§ 123 Abs. 4 Satz 5 und 6". The parsed informtaion is formatted into lists nested in lists nested in lists. The outer list is a list of re...
random_line_split
statutes_parse.py
): """ Exception is raised if a unit in a refren cannot be parsed. """ pass class StatutesParser(StatutesProcessor): """ Class to parse the content of a reference area identified by StatutesExtractor """ def parse_main(self, main_text: str) -> list: """ Parses a strin...
n: str): """ Returns: True if the token is a 'numeric' value of the reference. """ return numb_pattern.fullmatch( token, ) @staticmethod def fix_errors_in_citation(citation): """ Fix some common inconsistencies in the references such as double...
mb(toke
identifier_name
statutes_parse.py
): """ Exception is raised if a unit in a refren cannot be parsed. """ pass class StatutesParser(StatutesProcessor): """ Class to parse the content of a reference area identified by StatutesExtractor """ def parse_main(self, main_text: str) -> list: """ Parses a strin...
method def split_parts_accidently_joined(reference_paths): """ Reformats the parsed references to separate accitently joined references. E.g. the original referehence "§ 123 § 126" will not be split by split_citation_into_enum_parts because the separation is falsly not indicated by ...
A citation can contain references to multiple parts of the law. E.g. '§§ 20 und 35' or 'Art. 3 Abs. 1 Satz 1, Abs. 3 Satz 1'. The citation is split into parts so that each referenced section of the law is separated. E.g. '§§ 20' and '35' resp. 'Art. 3 Abs. 1 Satz 1' and 'Abs. 3 Satz...
identifier_body
matrix.py
OpenMaya.MMatrix.identity: if invertMatrix: matrix = matrix.inverse() vector *= matrix # Return new vector return [vector.x,vector.y,vector.z] def getTranslation(matrix): ''' Return the translation component of a matrix. @param matrix: Matrix to extract translation from @type matrix: maya.OpenMaya.MMatrix...
''' Return the specified matrix as a list @param matrix: Matrix to return list for @type matrix: maya.OpenMaya.MMatrix ''' return [ matrix(0,0),matrix(0,1),matrix(0,2),matrix(0,3), matrix(1,0),matrix(1,1),matrix(1,2),matrix(1,3), matrix(2,0),matrix(2,1),matrix(2,2),matrix(2,3), matrix(3,0),matrix(3,1),...
identifier_body
matrix.py
OpenMaya.MScriptUtil.setDoubleArray(matrix[1], 1, yAxis[1]) OpenMaya.MScriptUtil.setDoubleArray(matrix[1], 2, yAxis[2]) OpenMaya.MScriptUtil.setDoubleArray(matrix[2], 0, zAxis[0]) OpenMaya.MScriptUtil.setDoubleArray(matrix[2], 1, zAxis[1]) OpenMaya.MScriptUtil.setDoubleArray(matrix[2], 2, zAxis[2]) OpenMaya.MScrip...
#OpenMaya.MScriptUtil.setDoubleArray(matrix[0], 2, valueList[2]) #OpenMaya.MScriptUtil.setDoubleArray(matrix[0], 3, valueList[3]) #OpenMaya.MScriptUtil.setDoubleArray(matrix[1], 0, valueList[4])
random_line_split
matrix.py
Matrix: Use the matrix inverse to transform the vector @type invertMatrix: bool ''' # Create MPoint/MVector object for transformation if transformAsPoint: vector = OpenMaya.MPoint(vector[0],vector[1],vector[2],1.0) else: vector = OpenMaya.MVector(vector[0],vector[1],vector[2]) # Check input is of type MMatrix ...
asList
identifier_name
matrix.py
values for the matrix @type translate: tuple/list @param xAxis: xAxis of the matrix @type xAxis: tuple/list @param yAxis: yAxis of the matrix @type yAxis: tuple/list @param zAxis: zAxis of the matrix @type zAxis: tuple/list ''' # Create transformation matrix from input vectors matrix = OpenMaya.MMatrix() va...
else: upVector = mathUtils.crossProduct(crossVector,aimVector) # Build axis dictionary axisDict={aimAxis: aimVector,upAxis: upVector,crossAxis: crossVector} # Build rotation matrix mat = buildMatrix(xAxis=axisDict['x'],yAxis=axisDict['y'],zAxis=axisDict['z']) # Return rotation matrix return mat def inver...
upVector = mathUtils.crossProduct(aimVector,crossVector)
conditional_block
main.rs
, firing: false, fire_counter: 0.0, }) { Ok(idx) => idx, Err(_) => { println!("rejecting connection; too many players"); return; } };
// Set the user ID to some combinaiton of the arena index and generation. let id = idx.into_raw_parts().0 as u8; players[idx].player.id = id; // TODO(jack) Broadcast PlayerLeft messages. // Broadcast PlayerJoined messages. let mut tcp_txs: Vec<_> = players .iter() .filter(|(oth...
random_line_split
main.rs
, firing: false, fire_counter: 0.0, }) { Ok(idx) => idx, Err(_) => { println!("rejecting connection; too many players"); return; } }; // Set the user ID to some combinaiton of the arena index and generation. let id = idx.into_raw_parts().0 ...
0.0 } else { dampened_velocity_unclamped }; let velocity_unit = player .player .velocity .try_normalize(0.0) .unwrap_or(Vector2::new(0.0, 0.0)); player.player.velocity = dampened_velocity * velocity_unit; pl...
{ // Apply player impulse. for (_, player) in players.iter_mut() { let acceleration = 64.0; let max_velocity = 16.0; let friction = 16.0; // Acceleration ranges from `friction` to `friction + acceleration`, // and is inversely proportional to the projection of the curren...
identifier_body
main.rs
( players: &mut Arena<Player>, bullets: &Arena<Bullet>, stream: TcpStream, mut internal_tcp_tx: Sender<(Index, Option<game::TcpServerMessage>)>, tick_rate: u32, tick_zero: SystemTime, tick: game::Tick, ) { println!("connection!"); let (tx, mut rx) = channel(4); let idx = match p...
accept
identifier_name
Loan Eligibility Prediction_Benchmark_ML_Algorithm.py
# ### Use GridSearchCV for finding the best model with the best hyperparameters # - ### Build models # - ### Create Parameter Grid # - ### Run GridSearchCV # - ### Choose the best model with the best hyperparameter # - ### Give the best accuracy # - ### Also, benchmark the best accuracy that you could get for every c...
# - KNN # - Logistic Regression # - SVM # - Random Forest # - Any other algorithm of your choice
random_line_split
main.rs
're looking for... may be in logs, or in generated C++, or generated .rs") .takes_value(true), ) .arg( Arg::new("creduce") .long("creduce") .value_name("PATH") .help("creduce binary location") .default_value("cre...
{ config: String, header: String, } fn do_run(matches: ArgMatches, tmp_dir: &TempDir) -> Result<(), std::io::Error> { let rs_path = tmp_dir.path().join("input.rs"); let concat_path = tmp_dir.path().join("concat.h"); match matches.subcommand_matches("repro") { None => { let subm...
ReproCase
identifier_name
main.rs
're looking for... may be in logs, or in generated C++, or generated .rs") .takes_value(true), ) .arg( Arg::new("creduce") .long("creduce") .value_name("PATH") .help("creduce binary location") .default_value("cre...
{ let haystack = std::fs::read_to_string(concat_path)?; Ok(["class Box", "class Vec", "class Slice"] .iter() .all(|needle| haystack.contains(needle))) }
identifier_body
main.rs
pro") { None => { let submatches = matches.subcommand_matches("file").unwrap(); let incs: Vec<_> = submatches .values_of("inc") .unwrap_or_default() .map(PathBuf::from) .collect(); let defs: Vec<_> = submatches.v...
gen_cmd: &str,
random_line_split
main.rs
're looking for... may be in logs, or in generated C++, or generated .rs") .takes_value(true), ) .arg( Arg::new("creduce") .long("creduce") .value_name("PATH") .help("creduce binary location") .default_value("cre...
}; Ok(()) } /// Try to detect whether the preprocessed source code already contains /// a preprocessed version of cxx.h. This is hard because all the comments /// and preprocessor symbols may have been removed, and in fact if we're /// part way through reduction, parts of the code may have been removed too. f...
{ std::fs::copy(&concat_path, PathBuf::from(output_path))?; }
conditional_block
cn.js
() { return ( <Layout title="华炎魔方,华炎办公,审批王,低代码,零代码,快速开发工具,企业PaaS平台" description="华炎魔方是一款随需应变的管理软件开发工具,旨在通过其强大的敏捷性、灵活性和开放性帮助企业创新、扩展和集成企业业务系统。基于该平台,您可以快速创建智能化、移动化的企业应用。" keywords={["低代码,低代码开发,低代码开发平台,开源低代码开发平台,快速开发平台,快速开发工具,paas,零代码,零代码开发,零代码开发平台"]} > <section className="flex bg-cover bg-no-r...
Landing
identifier_name
cn.js
<p className="mt-3 text-base text-gray-700 sm:mt-5 sm:text-xl lg:text-lg xl:text-xl"> 华炎魔方基于商业智能和模型驱动,即使是不懂编程的业务人员,也能轻松便捷地创建智能化、移动化的企业应用。 </p> <div className="mt-5 sm:mt-8 sm:flex sm:justify-center lg:justify-start"> <div className="rounded-md shadow"> <a href="htt...
{ return ( <Layout title="华炎魔方,华炎办公,审批王,低代码,零代码,快速开发工具,企业PaaS平台" description="华炎魔方是一款随需应变的管理软件开发工具,旨在通过其强大的敏捷性、灵活性和开放性帮助企业创新、扩展和集成企业业务系统。基于该平台,您可以快速创建智能化、移动化的企业应用。" keywords={["低代码,低代码开发,低代码开发平台,开源低代码开发平台,快速开发平台,快速开发工具,paas,零代码,零代码开发,零代码开发平台"]} > <section className="flex bg-cover bg-no-repe...
identifier_body
cn.js
不懂编程的业务人员,也能轻松便捷地创建智能化、移动化的企业应用。 </p> <div className="mt-5 sm:mt-8 sm:flex sm:justify-center lg:justify-start"> <div className="rounded-md shadow"> <a href="http://oss.steedos.com/apps/pdfviewer/web/viewer.html?file=http://oss.steedos.com/docs/%E5%8D%8E%E7%82%8E%E9%AD%94%E6%96%B9%...
</div> </div> </div> </div> </div> </section> <section className="flex bg-cover bg-no-repeat bg-gray-50"> <div className="mx-auto max-w-screen-xl px-4 sm:px-6 lg:px-8 my-16"> <div class="relative"> <div class="lg:grid lg:grid-flow-row-dense lg:grid-cols-2 lg:gap-8 lg:item...
urls={[ {name:"高清", url:"https://www-steedos-com.oss-accelerate.aliyuncs.com/videos/creator/steedos-guide.mp4"}, ]}/>
random_line_split
model_transformer.py
: return [match_layer.layer] # If 2 different layers point to the same input, or if a layer uses the # same input multiple times, the input layer can be repeated. But it # preserves a bit of structure. leaf_layers = [] for inp in match_layer.input_layers: leaf_layers.extend(self._get_l...
weight_value_tuples.append((weight_tensor, weights_map[weight_name])) K.batch_set_value(weight_value_tuples)
random_line_split
model_transformer.py
match_layer(layer, pattern): return None if self._is_functional_model( self.model) and not self._is_match_supported(layer, is_head_node): return None if len(pattern.inputs) == 0: # Leaf layer in pattern. return LayerNode( layer, self._get_layer_weights(layer['config']...
replacement_nodes.extend(_get_replacement_nodes(input_layer))
conditional_block
model_transformer.py
(layer_name, {}) def _get_layer_metadata(self, layer_name): return self._layer_metadata_map.get(layer_name, {}) def _match_pattern(self, target, pattern): return re.match('^' + pattern + '$', target) is not None def _match_layer(self, layer, pattern): """Check if specific layer matches the pattern....
def _match_layer_with_inputs(self, layer, pattern, is_head_node): """Match pattern at this layer, and continue to match at its inputs.""" if not self._match_layer(layer, pattern): return None if self._is_functional_model( self.model) and not self._is_match_supported(layer, is_head_node):...
"""Get the names of a layer's input layers.""" if self._is_functional_model(self.model): inbound_nodes = layer['inbound_nodes'] return [connection_info[0] for connection_info in inbound_nodes[0]] else: # Sequential model. layers = self._config['layers'] i = layers.index(layer) if ...
identifier_body
model_transformer.py
and layer['config']['name'] in matched_layers: continue match_layer = self._match_layer_with_inputs( layer, pattern, is_head_node=True) if match_layer: return match_layer return None def _get_leaf_layers(self, match_layer): """Return leaf layers from this sub-graph tre...
_set_layer_weights
identifier_name
generate_samples.py
= True # choose objects from the list; make visible, move and rotate objects_order = list(range(len(objects))) random.shuffle(objects_order) n_objects = random.randint(1,len(objects)-1) obj_center = np.asarray([0,0], 'float32') for i in range(n_objects): obj = objects[objects_order[i]] ...
else: n.outputs[0].default_value = [random.random(), random.random(), random.random(), 1] if "rand" in n.name: n.outputs[0].default_value = random.random() if "switch" in n.name: n.outputs[0].default_val...
c=random.random() n.outputs[0].default_value = [c, c, c, 1]
conditional_block
generate_samples.py
# Image texture onto background for more realistic reflections if BACKGROUND_REFLECTIONS: bg_img_path = img_list[step % len(img_list)-1] # unrandomized bpy.data.images["ground.jpg"].filepath = bg_img_path # hide all objects for obj in objects: obj.hide_render = True # ob...
print(o.name, 'has no rotation range yet. Set to [0,360].') o["rotation_range"] = (0,360) if not 'cam_pos_range' in o: print(o.name, 'has no camera position range yet. Set to [0,90].')
random_line_split
generate_samples.py
= True # choose objects from the list; make visible, move and rotate objects_order = list(range(len(objects))) random.shuffle(objects_order) n_objects = random.randint(1,len(objects)-1) obj_center = np.asarray([0,0], 'float32') for i in range(n_objects): obj = objects[objects_order[i]] ...
(): ## iterates all materials in the blender file and applies random adjustments based on naming conventions textures = bpy.data.materials #['rand_plastic'] for t in textures: # random color for rand if "rand" in t.name: tex_nodes = t.node_tree.nodes for n in tex_node...
texture_adjustments
identifier_name
generate_samples.py
= True # choose objects from the list; make visible, move and rotate objects_order = list(range(len(objects))) random.shuffle(objects_order) n_objects = random.randint(1,len(objects)-1) obj_center = np.asarray([0,0], 'float32') for i in range(n_objects): obj = objects[objects_order[i]] ...
def texture_adjustments(): ## iterates all materials in the blender file and applies random adjustments based on naming conventions textures = bpy.data.materials #['rand_plastic'] for t in textures: # random color for rand if "rand" in t.name: tex_nodes = t.node_tree.nodes ...
for obj in objects: if obj.data.shape_keys: keys = obj.data.shape_keys.key_blocks if len(keys): for i, k in enumerate(keys): if i: k.value = random.random()
identifier_body
kogitoapp_types.go
// +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.displayName="Runtime" // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.x-descriptors="urn:alm:descriptor:com.tectonic.ui:label" // +kubebuilder:validation:Enum=quarkus;springboot Runtime RuntimeType `json:"runtime,omitempty"` // ...
// The name of the runtime used, either Quarkus or SpringBoot. // Default value: quarkus. // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors=true
random_line_split
kogitoapp_types.go
are going to configure the persistence infrastructure yourself. // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors=true // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.displayName="Enable Persistence" // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.x-descriptors...
(name, value string) { if k.Resources.Limits == nil { k.Resources.Limits = corev1.ResourceList{} } k.Resources.Limits[corev1.ResourceName(name)] = resource.MustParse(value) } // KogitoAppServiceObject Data to define the service of the Kogito application. // +k8s:openapi-gen=true type KogitoAppServiceObject struc...
AddResourceLimit
identifier_name
kogitoapp_types.go
are going to configure the persistence infrastructure yourself. // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors=true // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.displayName="Enable Persistence" // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.x-descriptors...
k.Resources.Limits[corev1.ResourceName(name)] = resource.MustParse(value) } // KogitoAppServiceObject Data to define the service of the Kogito application. // +k8s:openapi-gen=true type KogitoAppServiceObject struct { // Labels for the application service. Labels map[string]string `json:"labels,omitempty"` } // ...
{ k.Resources.Limits = corev1.ResourceList{} }
conditional_block
kogitoapp_types.go
are going to configure the persistence infrastructure yourself. // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors=true // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.displayName="Enable Persistence" // +operator-sdk:gen-csv:customresourcedefinitions.specDescriptors.x-descriptors...
// AddResourceLimit adds new resource limit. Works also on an uninitialized Limits field. func (k *KogitoAppBuildObject) AddResourceLimit(name, value string) { if k.Resources.Limits == nil { k.Resources.Limits = corev1.ResourceList{} } k.Resources.Limits[corev1.ResourceName(name)] = resource.MustParse(value) } ...
{ if k.Resources.Requests == nil { k.Resources.Requests = corev1.ResourceList{} } k.Resources.Requests[corev1.ResourceName(name)] = resource.MustParse(value) }
identifier_body
block_stream.rs
stream: Box<dyn BlockStream<C>>, size_hint: usize, ) -> Box<dyn BlockStream<C>> { let (sender, receiver) = mpsc::channel::<Result<BlockStreamEvent<C>, Error>>(size_hint); crate::spawn(async move { BufferedBlockStream::stream_blocks(stream, sender).await }); Box::new(Buffered...
inner: Pin<Box<dyn Stream<Item = Result<BlockStreamEvent<C>, Error>> + Send>>, } impl<C: Blockchain + 'static> BufferedBlockStream<C> { pub fn spawn_from_stream(
random_line_split
block_stream.rs
pub trait BlockStream<C: Blockchain>: Stream<Item = Result<BlockStreamEvent<C>, Error>> + Unpin + Send { } /// BlockRefetcher abstraction allows a chain to decide if a block must be refetched after a dynamic data source was added #[async_trait] pub trait BlockRefetcher<C: Blockchain>: Send + Sync { fn required...
(block: C::Block, mut trigger_data: Vec<C::TriggerData>, logger: &Logger) -> Self { // This is where triggers get sorted. trigger_data.sort(); let old_len = trigger_data.len(); // This is removing the duplicate triggers in the case of multiple // data sources fetching the same ...
new
identifier_name
MPO.py
= pd.DataFrame(self.CML_weights, columns=self.stock_names+["Risk-free rate"]) T = [re.sub(r'\n', "% <br>", re.sub(r'[ ]+', " ", PD.iloc[i].to_string() ))+"%" for i in PD.index] if n == "CMLp": PD = pd.DataFrame(self.CMLpw, index=self.stock_names+["Risk-free rate"]) ...
# online = True, # window_size=3650, # window_move=365,
random_line_split
MPO.py
(1)).dropna() def assign_data_window(self, opperation_type=None): """the unelegance is here that there needs to be first a calculation of the backtest weights with one range of data held out followed then by a calculation of the backtest expected return calculated on the held out data ...
h = ({'type':'eq', 'fun': lambda W: sum(W)-1.}, # Sum of weights = 100% {'type':'eq', 'fun': lambda W: exp_return(W, R) - r}) # equalizes portfolio return to r for r in Fr: # For given level of return r, find weights which minimizes portfolio variance. ...
""" where: R is the vector of expected returns Fr is the range expected returns on the EFF C is the var-covariance matrix """ # TODO: add options to short and borrow W = R*0 + 1/len(R) #Initialize equal procent weights ...
identifier_body
MPO.py
(W)-1.}, # Sum of weights = 100% {'type':'eq', 'fun': lambda W: quad_var(W, C) - ri}, # equalizes portfolio risk to ri {'type':'eq', 'fun': lambda W: exp_return1(W, R, rf) - re}) # equalizes portfolio return to re for ri, re in zip(CMLx, CMLy): ...
name = self.name_of_data + self.name plot_url = offline.plot(fig, image='png',auto_open=self.auto_open, image_filename=name, output_type='file', image_width=1200, image_height=1000, filename="figures/{0}.html".format(name) # run some...
conditional_block
MPO.py
1)).dropna() def assign_data_window(self, opperation_type=None): """the unelegance is here that there needs to be first a calculation of the backtest weights with one range of data held out followed then by a calculation of the backtest expected return calculated on the held out data ...
(self): #Using plane mean value self.market_returns = self.data_window[self.market_indecies].mean() #scaling to yearly using eulers self.market_returns_yr = np.exp(self.market_returns*12)-1 def calculate_exp_return(self): # #Using CAPM # self.exp_return = se...
calculate_expected_market_return
identifier_name
my.js
(), _h = isWap && _w<h?$win.height():_w * 1135 / 720; $wrapers.height(_h); if($win.height()<300){ $(".cn-slidetips").hide(); }else{ $(".cn-slidetips").show(); } }; sl(); $win.resize(sl); }; //滑动绑定函数 var onSlideChangeTime = 0; var onS...
ck(function(){ var _fxbg=$('.fxbg'); var _tan=$(".tan"); var _bg = $(".bg"); _fxbg.fadeIn(); _bg.fadeOut(); _tan.fadeOut(); }) //分享成功 function fxsuccess(){ var _fxbg=$(".fxbg"); _fxbg.fadeIn(); } $("#zp").click(function(){ var type=0; var count=$("#count").val(); if($("#z...
li
identifier_name
my.js
isWap=yt.isWap(), w = 720, h = 1135; var sl = function () { var _w = $wraper1.width(), h = $win.height(), _h = isWap && _w<h?$win.height():_w * 1135 / 720; $wrapers.height(_h); if($win.height()<300){ $(".cn-slidet...
random_line_split
my.js
lse; }; //滑动绑定 yt.app = function () { var $swiperContainer = $("#swiper-container1"), $pages = $("#wrapper").children(), $as = $("#nav li a"), $lis = $("#nav li"), $win =$(window), slideCount = $pages.length, nowIndex = 0, acn = "animation", mySwi...
} return fa
conditional_block
my.js
zdy','jp1'); } } else{ if($('.jp img').attr('zdy')=='jp1') { $('.jp img').attr('src','images/jp2.png?vid=1.0'); $('.jp img').attr('zdy','jp2'); } else{ $('.jp img').attr('src','images/jp1.png'); $('.jp img').attr('zdy','jp1'...
>谢谢您参与!</p>','<p>活动结束后</p><p>会有专人通知您的了!</p>') // $("#end").click(function(){ // _bg.fadeOut(); // _product.fadeOut(); // }); } function producttag(type){ var _bg = $(".bg"); var _tag=$("#tag"); _bg.fadeIn(); _tag.fadeIn(); var _tagpic=$("#tag .prd-tag-pic"); var _...
identifier_body
client_dns.go
string) (string, error) { domains, err := d.getDomainsWithCache(ctx) if err != nil { return "", err } domain, ok := domains[domainId] if !ok { return "", fmt.Errorf("DNS domain with id %s not found", domainId) } return CompositeDomainName(domain.DomainName, domain.DomainId), nil } // CreateOrUpdateDomainRe...
{ if err := d.waitForAliDNSRateLimiter(ctx); err != nil { return err } req := alidns.CreateDeleteDomainRecordRequest() req.RecordId = id if _, err := d.Client.DeleteDomainRecord(req); err != nil && !isDomainRecordDoesNotExistError(err) { return err } return nil }
identifier_body
client_dns.go
ID, accessKeySecret) if err != nil { return nil, err } return &dnsClient{ Client: *client, accessKeyID: accessKeyID, domainsCache: f.domainsCache, domainsCacheMutex: &f.domainsCacheMutex, RateLimiter: f.getRateLimiter(accessKeyID), RateLimiterWaitTi...
if err := d.waitForAliDNSRateLimiter(ctx); err != nil { return nil, err }
random_line_split
client_dns.go
nil { return err } for _, value := range values { if record, ok := records[value]; ok { // Only update the existing domain record if the current TTL value is different from the given one // At this point we know that rr, recordType, and value are the same if record.TTL != ttl { if err := d.updateDom...
{ return true }
conditional_block
client_dns.go
(region, accessKeyID, accessKeySecret string) (DNS, error) { client, err := alidns.NewClientWithAccessKey(region, accessKeyID, accessKeySecret) if err != nil { return nil, err } return &dnsClient{ Client: *client, accessKeyID: accessKeyID, domainsCache: f.domainsCache, ...
(ctx context.Context, domainName, rr, recordType string) (map
getDomainRecords
identifier_name
lib.rs
(outputs: &syn::ReturnType) -> TokenStream { let ty = match outputs { syn::ReturnType::Default => quote!(()), syn::ReturnType::Type(_, ty) => quote!(#ty), }; quote!(pg_extend::pg_type::PgType::from_rust::<#ty>().return_stmt()) } fn impl_info_for_fdw(item: &syn::Item) -> TokenStream { l...
pg_foreignwrapper
identifier_name
lib.rs
let arg_type: &syn::Type = match *arg { syn::FnArg::SelfRef(_) | syn::FnArg::SelfValue(_) => { panic!("self functions not supported") } syn::FnArg::Inferred(_) => panic!("inferred function parameters not supported"), syn::FnArg::Captured(ref captur...
fn impl_info_for_fdw(item: &syn::Item) -> TokenStream { let typ = if let syn::Item::Struct(typ) = item { typ } else { panic!("Annotation only supported on structs") }; let mut decl = item.clone().into_token_stream(); let struct_name = &typ.ident; let func_name = syn::Ident::n...
{ let ty = match outputs { syn::ReturnType::Default => quote!(()), syn::ReturnType::Type(_, ty) => quote!(#ty), }; quote!(pg_extend::pg_type::PgType::from_rust::<#ty>().return_stmt()) }
identifier_body
lib.rs
let arg_type: &syn::Type = match *arg { syn::FnArg::SelfRef(_) | syn::FnArg::SelfValue(_) => { panic!("self functions not supported") } syn::FnArg::Inferred(_) => panic!("inferred function parameters not supported"), syn::FnArg::Captured(ref captur...
// arbitrary Datum conversions occur here, and could panic // so this is inside the catch unwind #get_args_from_datums // this is the meat of the function call into the extension code let result = #func_name(#func_params); ...
// guard the Postgres process against the panic, and give us an oportunity to cleanup let panic_result = panic::catch_unwind(|| { // extract the argument list let (mut args, mut args_null) = pg_extend::get_args(func_info);
random_line_split
biogrid-class.ts
ALL_BATTERY.DEFAULT_START_ENERGY; return positions.map( (position, index) => new BioBattery({ x: position.x, y: position.y, gridItemName: `${gridItemName}-${index}`, gridItemResistance: batteryResistance, energyInKiloWattHour: initEnergy, max...
{ if (this.positionOutOfBounds(newPos, townSize)) { outOfBoundsCount++; } switch (angle) { case 0: yOffset = 0; xOffset = radius; break; case 90: xOffset = 0; yOffset = radius; break; case 180: xOffse...
conditional_block
biogrid-class.ts
approximately have a maxCapacity of 540,000KJ private largeBatteries: Battery[]; // A dictionary with the position as its key // Used to keep track of whether an item is already placed in a position private itemInPosition: { [positionString: string]: boolean } = {}; // All details for the source of energy ...
private createBatteries( positions: ItemPosition[], gridItemName: string ): Battery[] { const batteryResistance = gridItemName === bioconstants.GRID_ITEM_NAMES.LARGE_BATTERY ? bioconstants.RESISTANCE.LARGE_BATTERY : bioconstants.RESISTANCE.SMALL_BATTERY; const maxCapacity = ...
{ return this.state.getJsonGraph(); }
identifier_body
biogrid-class.ts
, opts: BiogridOptions) { const todayMidnight = new Date(); todayMidnight.setHours(0); this.startDate = opts.startDate || todayMidnight; // Batteries const smallBatteryPositions = this.createGridItemPositions( town.getTownSize(), opts.numberOfSmallBatteryCells ); const largeBatte...
townSize: TownSize, numberOfGridItems: number ): ItemPosition[] {
random_line_split
biogrid-class.ts
); } /** * Drain the energy users according to the time of day */ updateEnergyUsage(date: Date) { this.town.getEnergyUsers().forEach((energyUser) => { energyUser.decreaseEnergyAccordingToTimeOfDay(date); }); } /** * This method takes the results of th brain and then it changes the...
positionOccupied
identifier_name
sync.rs
unwrap() } fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> { serde_json::from_slice(buf) } /// Stores state needed by the container to perform synchronization. pub struct SyncStore { page: Page_Proxy, key: Vec<u8>, updates: Sender<SyncMsg>, transaction_pending: bool, buffer: B...
/// Run this in a thread, it will return when it encounters an error /// reading the channel or when the `Stop` message is recieved. pub fn work(&self) -> Result<(), RecvError> { loop { let msg = self.chan.recv()?; match msg { SyncMsg::Stop => return Ok(()),...
{ SyncUpdater { container_ref, chan } }
identifier_body
sync.rs
).unwrap() } fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> { serde_json::from_slice(buf) } /// Stores state needed by the container to perform synchronization. pub struct SyncStore { page: Page_Proxy, key: Vec<u8>, updates: Sender<SyncMsg>, transaction_pending: bool, buffer:...
(ledger: &mut Ledger_Proxy, key: Vec<u8>) { let (s1, s2) = Channel::create(ChannelOpts::Normal).unwrap(); let resolver_client = ConflictResolverFactory_Client::from_handle(s1.into_handle()); let resolver_client_ptr = ::fidl::InterfacePtr { inner: resolver_client, version: ConflictResolverFac...
start_conflict_resolver_factory
identifier_name
sync.rs
).unwrap() } fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> { serde_json::from_slice(buf) } /// Stores state needed by the container to perform synchronization. pub struct SyncStore { page: Page_Proxy, key: Vec<u8>, updates: Sender<SyncMsg>, transaction_pending: bool, buffer:...
let watcher = PageWatcherServer { updates: updates.clone(), buffer: buffer.clone() }; let _ = fidl::Server::new(watcher, s2).spawn(); let (mut snap, snap_request) = PageSnapshot_new_pair(); page.get_snapshot(snap_request, Some(key.clone()), Some(watcher_client_ptr)) .with(le...
let watcher_client = PageWatcher_Client::from_handle(s1.into_handle()); let watcher_client_ptr = ::fidl::InterfacePtr { inner: watcher_client, version: PageWatcher_Metadata::VERSION };
random_line_split
test_rnn2rnn_power.py
ample("15min").sum().reset_index() power_15min = power_15min.pivot(index='cid', columns='data_time', values='value') power_daily = power.set_index("data_time").groupby("cid").resample("1D").sum().reset_index() power_daily = power_daily.pivot(index='cid', columns='data_time', values='value') xy_15min = power_15min.valu...
spliter = ForwardSpliter() train_idx, valid_idx = spliter.split(np.arange(xy.shape[1]), ENC_LEN, N_TEST + N_VALID) valid_idx, test_idx = spliter.split(valid_idx, ENC_LEN, N_TEST) train_xy = TimeSeries(xy[:, train_idx]) valid_xy = TimeSeries(xy[:, valid_idx]) trn_weight = TimeSeries(weights[:, train_idx]) val_weigh...
def split(self, time_idx, enc_len, valid_size): if valid_size < 1: valid_size = int(np.floor(len(time_idx) * valid_size)) valid_idx = time_idx[-(valid_size + enc_len):] train_idx = time_idx[:-valid_size] return train_idx, valid_idx
identifier_body
test_rnn2rnn_power.py
(x, axis, fill_zero=True): mu = np.nanmean(x, axis, keepdims=True) std = np.nanstd(x, axis, keepdims=True) x_norm = (x - mu) / std if fill_zero: x_norm = np.nan_to_num(x_norm) return x_norm, mu, std power = pd.read_csv('./data/df.csv', parse_dates=['data_time'])[['data_time', 'cid', 'value...
normalize
identifier_name
test_rnn2rnn_power.py
ample("15min").sum().reset_index() power_15min = power_15min.pivot(index='cid', columns='data_time', values='value') power_daily = power.set_index("data_time").groupby("cid").resample("1D").sum().reset_index() power_daily = power_daily.pivot(index='cid', columns='data_time', values='value') xy_15min = power_15min.valu...
valid_frame = Seq2SeqDataLoader(valid_xy, batch_size=64, enc_lens=ENC_LEN, dec_lens=DEC_LEN, use_cuda=True, mode='valid', time_free_space=0, time_interval=48, enc_num_feats=val_enc_num, enc_ca...
mode='train', time_free_space=0, enc_num_feats=trn_enc_num, enc_cat_feats=trn_enc_cat, dec_num_feats=trn_dec_num, dec_cat_feats=trn_dec_cat, weights=trn_weight, seq_last=False)
random_line_split
test_rnn2rnn_power.py
ample("15min").sum().reset_index() power_15min = power_15min.pivot(index='cid', columns='data_time', values='value') power_daily = power.set_index("data_time").groupby("cid").resample("1D").sum().reset_index() power_daily = power_daily.pivot(index='cid', columns='data_time', values='value') xy_15min = power_15min.valu...
return result holidays = get_holiday_features(power_daily.columns) xy_holiday_mean = holiday_apply(power_daily, holidays, np.mean).values xy_holiday_mean = normalize(xy_holiday_mean, 0)[0] xy_weekday = pd.get_dummies(power_daily.columns.weekday).values xy_hour = pd.get_dummies(power_daily.columns.hour).values xy...
result[h] = x.loc[:, holidays[h].values.astype(bool)].agg(func, axis=1).values
conditional_block
authconn_internal.py
by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # For those usages ...
proj = self.db.get_one("projects", {BaseTopic.id_field("projects", project): project}) if proj["_id"] not in user_content["projects"] and proj["name"] not in user_content["projects"]: raise AuthException("project {} not allowed for this user".format(project), ...
# database will not be needed if not project: project = user_content["projects"][0] # To allow project names in project_id
random_line_split
authconn_internal.py
by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # For those usages ...
self, config, db, token_cache): Authconn.__init__(self, config) self.logger = logging.getLogger("nbi.authenticator.internal") # Get Configuration # self.xxx = config.get("xxx", "default") self.db = db self.token_cache = token_cache # To be Confirmed se...
_init__(
identifier_name
authconn_internal.py
applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # For those usages not...
def authenticate(self, user, password, project=None, token_info=None): """ Authenticate a user using username/password or previous token_info plus project; its creates a new token :param user: user: name, id or None :param password: password or None :param project: name, id...
"" Invalidate a token. :param token: token to be revoked """ try: self.token_cache.pop(token, None) self.db.del_one("tokens", {"_id": token}) return True except DbException as e: if e.http_code == HTTPStatus.NOT_FOUND: ...
identifier_body
authconn_internal.py
applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # For those usages not...
else: # raise msg = "Error during token revocation using internal backend" self.logger.exception(msg) raise AuthException(msg, http_code=HTTPStatus.UNAUTHORIZED) def authenticate(self, user, password, project=None, token_info=None): ...
aise AuthException("Token '{}' not found".format(token), http_code=HTTPStatus.NOT_FOUND)
conditional_block
setup-cluster-images.py
| sudo apt-key add - echo "deb http://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list sudo apt-get update -y sudo apt-get install -y policykit-1 docker-ce setup_machine_id sudo dphys-swapfile swapoff sudo dphys-swapfile uninstall sudo update-rc.d dphys-swapfile remove echo...
continue
conditional_block
setup-cluster-images.py
-e /boot/setup.txt ]] ; then tmp=`mktemp` mv /boot/setup.txt "$tmp" sh -x "/%s" "$tmp" >/boot/setup.log 2>&1 rm -f "$tmp" fi """ % SETUP_NODE_SH def absjoin(*params): return abspath(join(*params)) # FIXME - add comments to the methods class ClusterSetup: def __call__(self, archive, nod...
targetdir = getcwd() if len(args) < 4 else args[3] nodenames = prepare_names( NODE_COUNT if len(args) < 2 else int(args[1]), NODE_PREFIX if len(args) < 3 else args[2]) ipaddress = BASE_IP if len(args) < 5 else _check_ip(args[4]) raspbian_archive = abspath(args[0]) setup = ClusterSetup() ...
identifier_body
setup-cluster-images.py
e849565cd7d27ac2daf68faa835a5151fd3feac87c6715bcb92d58dc280 cfssl-certinfo 4106c11c61aa9e98b1967adab6db711d2b50a0f02f844329e9ad44f199bdf135 cfssl-newkey 71e41ef447f49ad236d75ec42152625c6fcf6c37122784740bd19b0a7c399560 cfssl-scan 11c708acaf48a69abf6f896f5c6158f7547a3c1bf44e14ca3b3ab440c1f808f1 cfssl e138102329d96f5a...
(self, image, nodename, master, ipadddress, cfssl): with self._mount(image): self._setup_nodename(master, nodename) self._enable_ssh() self._setup_cgroups() debug('install cfssl to %s' % absjoin('system', USR_LOCAL_BIN)) self._copytree(cfssl, absjoin('...
_prepare_node_image
identifier_name
setup-cluster-images.py
e849565cd7d27ac2daf68faa835a5151fd3feac87c6715bcb92d58dc280 cfssl-certinfo 4106c11c61aa9e98b1967adab6db711d2b50a0f02f844329e9ad44f199bdf135 cfssl-newkey 71e41ef447f49ad236d75ec42152625c6fcf6c37122784740bd19b0a7c399560 cfssl-scan 11c708acaf48a69abf6f896f5c6158f7547a3c1bf44e14ca3b3ab440c1f808f1 cfssl e138102329d96f5a...
def _setup_cgroups(self): debug('setup cgrops in %s' % getcwd()) with open(absjoin('boot', 'cmdline.txt'), 'a') as cmdline: cmdline.write('cgroup_enable=cpuset cgroup_memory=1') def _enable_ssh(self): debug('enable ssh in %s' % getcwd()) with open(absjoin('boot', 'ss...
ipaddress = self._increment_ip(ipaddress) info('done')
random_line_split
lib.rs
Exonum nodes. //! //! `exonum-cli` supports multi-stage configuration process made with safety in mind. It involves //! 4 steps (or stages) and allows to configure and run multiple blockchain nodes without //! need in exchanging private keys between administrators. //! //! # How to Run the Network //! //! 1. Generate ...
else { Command::from_args() }; if let StandardResult::Run(run_config) = command.execute()? { let genesis_config = Self::genesis_config(&run_config, self.builtin_instances); let db_options = &run_config.node_config.private_config.database; let database =...
{ Command::from_iter(args) }
conditional_block
lib.rs
Exonum nodes. //! //! `exonum-cli` supports multi-stage configuration process made with safety in mind. It involves //! 4 steps (or stages) and allows to configure and run multiple blockchain nodes without //! need in exchanging private keys between administrators. //! //! # How to Run the Network //! //! 1. Generate ...
/// Adds new Rust service to the list of available services. pub fn with_rust_service(mut self, service: impl ServiceFactory) -> Self { self.rust_runtime = self.rust_runtime.with_factory(service); self } /// Adds a new `Runtime` to the list of available runtimes. /// /// Note ...
{ let temp_dir = TempDir::new()?; let mut this = Self::with_args(vec![ OsString::from("run-dev"), OsString::from("--artifacts-dir"), temp_dir.path().into(), ]); this.temp_dir = Some(temp_dir); Ok(this) }
identifier_body
lib.rs
Exonum nodes. //! //! `exonum-cli` supports multi-stage configuration process made with safety in mind. It involves //! 4 steps (or stages) and allows to configure and run multiple blockchain nodes without //! need in exchanging private keys between administrators. //! //! # How to Run the Network //! //! 1. Generate ...
use std::{env, ffi::OsString, iter, path::PathBuf}; use crate::command::{run::NodeRunConfig, Command, ExonumCommand, StandardResult}; pub mod command; pub mod config; pub mod io; pub mod password; mod config_manager; /// Rust-specific node builder used for constructing a node with a list /// of provided services. ...
use tempfile::TempDir;
random_line_split
lib.rs
public configurations of every other node, producing a single //! configuration file with all the necessary node and network settings. //! 4. Use `run` command and provide it with final node configuration file produced at the previous //! step. If the secret keys are protected with passwords, the user need to ente...
supervisor_service
identifier_name
main.py
to sort by print("To-Do:") for item_index in my_list: # The range needs to be the length of the list # being printed if item_index.visible and not show_hidden: # Only print visible items # if show hidden is false print(item_index.priority, item_index.text, sep='....
select_item
identifier_name
main.py
many characters long the line should be, default is 100 :returns nothing""" for i in range(size): print('-', end='') # Prints out a single dash, no newline afterwards # (the end= sets the last character to blank print('') # Print out a newline (using the default ending of a print ...
"""The purpose of this function is to display a list of all items in the todo list and number each individually to allow the user to select an item to modify or delete. The available numbers may skip some if some items are hidden :param todo_list: the list of ListItem objects to display :param ...
identifier_body
main.py
1 line_counter += 1 except ValueError: print("An error has occurred trying to load the file") result = int(clean_input( "Please enter a 2 to overwrite the current save file and start " "over or any other number to exit the program")) if result == 2:...
random_line_split
main.py
else: # Assume the item is visible if the text is not # False list_item[3] = True todo.insert(0, ListItem(list_item[0], list_item[1], list_item[2], list_item[3])) temp = 1 ...
if todo_list[item_index].visible: # If an item is visible, then # they are not all hidden state = 0 # Neither
conditional_block
routes.py
f get_sensor_type_id(sensor_type_name): """Given a sensor type name, get the ID of the sensor type from the database.""" query = db.session.query( TypeClass.id, ).filter(TypeClass.sensor_type == sensor_type_name) sensor_id = db.session.execute(query).fetchone() if isinstance(sensor_id, Itera...
ven a sensor type ID, get the name of the sensor type from the database.""" query = db.session.query( TypeClass.sensor_type, ).filter(TypeClass.id == sensor_type_id) sensor_name = db.session.execute(query).fetchone() if isinstance(sensor_name, Iterable): sensor_name = sensor_name[0] ...
identifier_body
routes.py
date()) + timedelta(hours=14) dt_to = pd.to_datetime(dt_to_.date()) + timedelta(days=1, hours=15) d_from = pd.to_datetime(dt_from_.date()) d_to = pd.to_datetime(dt_to_.date()) col_ec = "electricity_consumption" sensor_device_id = "Clapham" lights_on_cols = [] # getting eneregy data for th...
ture_range_analysis(temp_d
identifier_name
routes.py
ensor_type_name] else: value = lambda: None DATA_TABLES_BY_SENSOR_TYPE[sensor_type_id] = value return value() def get_columns_by_sensor_type(sensor_type_id): """Return the names of the data columns in the table corresponding to a given sensor type ID. By "data columns"...
prev_row_value = energy_hour.loc[df_index, "lights_on_4"] lights_on_cols.append("lights_on_4") # Lights ON 5: Lights are assumed on if the energy use is over 0.9 # times the days' energy use mean, and the energy demand is over 30 kW. energy_hour["energy_date_mean"] = energy_hour.groupby("energy...
.isnan(energy_hour.loc[df_index, "lights_on_4"]) and not np.isnan( prev_row_value ): energy_hour.loc[df_index, "lights_on_4"] = prev_row_value
conditional_block
routes.py
[sensor_type_name] else: value = lambda: None DATA_TABLES_BY_SENSOR_TYPE[sensor_type_id] = value return value() def get_columns_by_sensor_type(sensor_type_id): """Return the names of the data columns in the table corresponding to a given sensor type ID. By "data column...
""" dt_from = pd.to_datetime(dt_from_.date()) + timedelta(hours=14) dt_to = pd.to_datetime(dt_to_.date()) + timedelta(days=1, hours=15) d_from = pd.to_datetime(dt_from_.date()) d_to = pd.to_datetime(dt_to_.date()) col_ec = "electricity_consumption" sensor_device_id = "Clapham" lights_...
lights_results_df - a pandas dataframe with mean lights on values
random_line_split
main.rs
, keys::Keys, merkledb::{BinaryValue, Snapshot, TemporaryDB}, runtime::{ migrations::{InitMigrationError, MigrationScript}, oneshot::Receiver, versioning::Version, AnyTx, ArtifactId, CallInfo, CommonError, ExecutionContext, ExecutionError, ExecutionFail, InstanceDescr...
fn is_artifact_deployed(&self, id: &ArtifactId) -> bool { self.deployed_artifacts.contains_key(id) } /// Initiates adding a new service and sets the counter value for this. fn initiate_adding_service( &self, context: ExecutionContext<'_>, artifact: &ArtifactId, ...
{ Receiver::with_result(self.deploy_artifact(artifact, spec)) }
identifier_body
main.rs
, keys::Keys, merkledb::{BinaryValue, Snapshot, TemporaryDB}, runtime::{ migrations::{InitMigrationError, MigrationScript}, oneshot::Receiver, versioning::Version, AnyTx, ArtifactId, CallInfo, CommonError, ExecutionContext, ExecutionError, ExecutionFail, InstanceDescr...
Some(InstanceStatus::Stopped) => { let instance = self.started_services.remove(&spec.id); println!("Stopping service {}: {:?}", spec, instance); } _ => { // We aren't interested in other possible statuses. } } ...
{ // Unwrap here is safe, since by invocation of this method // `exonum` guarantees that `initiate_adding_service` was invoked // before and it returned `Ok(..)`. let instance = self .start_service(&spec.artifact, &spec.as_descriptor())...
conditional_block
main.rs
Height, keys::Keys, merkledb::{BinaryValue, Snapshot, TemporaryDB}, runtime::{ migrations::{InitMigrationError, MigrationScript}, oneshot::Receiver, versioning::Version, AnyTx, ArtifactId, CallInfo, CommonError, ExecutionContext, ExecutionError, ExecutionFail, Instanc...
}) } /// In the present simplest case, the artifact is added into the deployed artifacts table. fn deploy_artifact( &mut self, artifact: ArtifactId, spec: Vec<u8>, ) -> Result<(), ExecutionError> { // Invariant guaranteed by the core assert!(!self.deploye...
_name: instance.name.to_owned(), ..SampleService::default()
random_line_split
main.rs
, keys::Keys, merkledb::{BinaryValue, Snapshot, TemporaryDB}, runtime::{ migrations::{InitMigrationError, MigrationScript}, oneshot::Receiver, versioning::Version, AnyTx, ArtifactId, CallInfo, CommonError, ExecutionContext, ExecutionError, ExecutionFail, InstanceDescr...
(&mut self, _snapshot: &dyn Snapshot, _mailbox: &mut Mailbox) {} } impl From<SampleRuntime> for (u32, Box<dyn Runtime>) { fn from(inner: SampleRuntime) -> Self { (SampleRuntime::ID, Box::new(inner)) } } impl WellKnownRuntime for SampleRuntime { const ID: u32 = 255; } fn node_config() -> (NodeConf...
after_commit
identifier_name
index.js
n; for(let input of tx.inputs) capacityInputs += BigInt(input.cell_output.capacity); for(let output of tx.outputs) capacityOutputs += BigInt(output.cell_output.capacity); if(capacityInputs - capacityOutputs > ckbytesToShannons(1)) throw new Error(`Transaction fee too high: ${formattedNumber(shanno...
{ capacity: formattedNumber(hexToInt(input.cell_output.capacity)) + " Shannons", capacityCkbytes: formattedNumber((Number(hexToInt(input.cell_output.capacity)) / 100_000_000), 4) + " CKBytes", lock: new ScriptValue(input.cell_output.lock).hash(), type: (!!input.cell_output.type) ? new ScriptValue(inpu...
} for(const input of transaction.inputs) { let cell =
random_line_split
index.js
number of CKBytes needed. * * @returns {Object} An object with the inputCells[] found and the inputCapacity contained within the provided Cells. */ async function collectCapacityWithType(indexer, lockScript, typeScript, capacityRequired) { const query = {lock: lockScript, type: typeScript}; const cellCo...
readFile
identifier_name
index.js
OutputCapacity: true, showOutputData: false, showOutputLock: true, showOutputType: true, showWitnesses: true, showTxFee: true }; options = {...defaults, ...options}; let obj = { deps: [], inputs: [], outputs: [], witnesses: [] }; for(const dep of transaction.cellDeps) { ...
{ const rpc = new RPC(nodeUrl); let result; try { result = await rpc.send_transaction(signedTx); } catch(error) { const regex = /^(\w+): ([\w\s]+) (\{.*\})$/; const matches = error.message.match(regex); if(!!matches && matches.length > 0) { const category = matches[1]; const typ...
identifier_body
utils.py
""" """ # If we have a filter, apply it. if filter_tree is not None: try: objs_to_print = filter_objects_from_simple_keypaths(objs, filter_tree.split(',')) except Exception as e: log.error(e.args[0]) exit(1) else: objs_to_print = objs ...
if as_json and (depth is not None or filter_tree is not None): log.error("If you choose to print it as json, do not provide a depth or filter. Those are for printing it as a tree.") exit() """ SDK1.6 Note: Since print_tree is not supported in 1.6, when both the available output form...
identifier_body
utils.py
in keyPaths: # If we've found a dict, we recurse deeper to pull out the objs. # Because this is a dict, we must advance our keyPaths recursion. # Consider the following example: if key not in dictionaryOfInterest: raise ValueError("'"+key+"' is not a valid key for this level...
decrypt
identifier_name