file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
variables.go
/******************************************************************************* * Copyright 2019 Dell Inc. * Copyright 2020 Intel Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * ...
(serviceConfig interface{}) (int, error) { var overrideCount = 0 contents, err := toml.Marshal(reflect.ValueOf(serviceConfig).Elem().Interface()) if err != nil { return 0, err } configTree, err := toml.LoadBytes(contents) if err != nil { return 0, err } // The toml.Tree API keys() only return to top leve...
OverrideConfiguration
identifier_name
utils.py
#============================================================================ # UTILS #============================================================================ # Script name: utils.py # Created on: 10/10/2012 # Author: Paula D. Paro Costa # Purpose: Collection of snnipets that may b...
def saveEVR2File(self,filename,variance=1): v=self.getEVR(variance) dumpMatrix2File(v,filename) return
v=self.getPC(numpc) dumpMatrix2File(v,filename) return
identifier_body
utils.py
#============================================================================ # UTILS #============================================================================ # Script name: utils.py # Created on: 10/10/2012 # Author: Paula D. Paro Costa # Purpose: Collection of snnipets that may b...
(self,variance=1): # Calculates the eigenvectors of the original covariance matrix if variance>=1: self.__u=np.asarray(np.zeros((self.N,self.M))) for col in range(self.M): if self.__verbose==True: print "Calculating eigentexture "+str(col+1) ...
getEigentexturesEVR
identifier_name
utils.py
#============================================================================ # UTILS #============================================================================ # Script name: utils.py # Created on: 10/10/2012 # Author: Paula D. Paro Costa # Purpose: Collection of snnipets that may b...
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
#============================================================================ # UTILS #============================================================================ # Script name: utils.py # Created on: 10/10/2012 # Author: Paula D. Paro Costa # Purpose: Collection of snnipets that may b...
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
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
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
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
( 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
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
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
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
}; send_message(&http, channel_id, user_id, help_message).await?; Ok(()) }
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
""" Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
(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
""" Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
refresh_task = self._loop.create_task(self._perform_refresh()) refresh_data = await refresh_task except asyncio.CancelledError: logger.debug( f"['{self._instance_connection_string}']: Schedule refresh task cancelled." ) ...
await asyncio.sleep(delay)
conditional_block
instance.py
""" Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
# 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
""" Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
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
import itertools from collections import Counter from regex import regex from quantlaw.de_extract.statutes_abstract import StatutesProcessor from quantlaw.de_extract.statutes_parse_patterns import ( numb_pattern, pre_numb_pattern, sgb_dict, split_citation_into_parts_pattern, split_citation_into_ra...
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
import itertools from collections import Counter from regex import regex from quantlaw.de_extract.statutes_abstract import StatutesProcessor from quantlaw.de_extract.statutes_parse_patterns import ( numb_pattern, pre_numb_pattern, sgb_dict, split_citation_into_parts_pattern, split_citation_into_ra...
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
import itertools from collections import Counter from regex import regex from quantlaw.de_extract.statutes_abstract import StatutesProcessor from quantlaw.de_extract.statutes_parse_patterns import ( numb_pattern, pre_numb_pattern, sgb_dict, split_citation_into_parts_pattern, split_citation_into_ra...
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
import itertools from collections import Counter from regex import regex from quantlaw.de_extract.statutes_abstract import StatutesProcessor from quantlaw.de_extract.statutes_parse_patterns import ( numb_pattern, pre_numb_pattern, sgb_dict, split_citation_into_parts_pattern, split_citation_into_ra...
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
import maya.cmds as mc import maya.OpenMaya as OpenMaya import mathUtils import math class MissingPluginError(Exception): pass def getMatrix(transform,local=False,time=None): ''' @param transform: Transform object to get world matrix from @type transform: str @param local: Get local space matrix instead of the w...
def printMatrix(matrix): ''' Print the specified matrix values to the script editor @param matrix: Matrix to print @type matrix: maya.OpenMaya.MMatrix ''' print ('%.3f' % matrix(0,0))+', '+('%.3f' % matrix(0,1))+', '+('%.3f' % matrix(0,2))+', '+('%.3f' % matrix(0,3)) print ('%.3f' % matrix(1,0))+', '+('%.3f' %...
''' 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
import maya.cmds as mc import maya.OpenMaya as OpenMaya import mathUtils import math class MissingPluginError(Exception): pass def getMatrix(transform,local=False,time=None): ''' @param transform: Transform object to get world matrix from @type transform: str @param local: Get local space matrix instead of the w...
#OpenMaya.MScriptUtil.setDoubleArray(matrix[1], 1, valueList[5]) #OpenMaya.MScriptUtil.setDoubleArray(matrix[1], 2, valueList[6]) #OpenMaya.MScriptUtil.setDoubleArray(matrix[1], 3, valueList[7]) #OpenMaya.MScriptUtil.setDoubleArray(matrix[2], 0, valueList[8]) #OpenMaya.MScriptUtil.setDoubleArray(matrix[2], 1, valu...
#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
import maya.cmds as mc import maya.OpenMaya as OpenMaya import mathUtils import math class MissingPluginError(Exception): pass def getMatrix(transform,local=False,time=None): ''' @param transform: Transform object to get world matrix from @type transform: str @param local: Get local space matrix instead of the w...
(matrix): ''' 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),m...
asList
identifier_name
matrix.py
import maya.cmds as mc import maya.OpenMaya as OpenMaya import mathUtils import math class MissingPluginError(Exception): pass def getMatrix(transform,local=False,time=None): ''' @param transform: Transform object to get world matrix from @type transform: str @param local: Get local space matrix instead of the w...
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
use futures::future::join_all; use generational_arena::{Arena, Index}; use nalgebra::Vector2; use std::env::args; use std::error::Error; use std::net::SocketAddr; use std::num::Wrapping; use std::time::Duration; use std::time::SystemTime; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::prelude::*; use t...
// 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
use futures::future::join_all; use generational_arena::{Arena, Index}; use nalgebra::Vector2; use std::env::args; use std::error::Error; use std::net::SocketAddr; use std::num::Wrapping; use std::time::Duration; use std::time::SystemTime; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::prelude::*; use t...
#[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let port: u32 = match args().nth(1).and_then(|s| s.parse().ok()) { Some(port) => port, None => { eprintln!("Usage: {} PORT", args().nth(0).unwrap()); return Ok(()); } }; let mut players = Arena:...
{ // 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
use futures::future::join_all; use generational_arena::{Arena, Index}; use nalgebra::Vector2; use std::env::args; use std::error::Error; use std::net::SocketAddr; use std::num::Wrapping; use std::time::Duration; use std::time::SystemTime; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::prelude::*; use t...
( 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
# coding: utf-8 # # Task 10 : Benchmark Top ML Algorithms # # This task tests your ability to use different ML algorithms when solving a specific problem. # # ### Dataset # Predict Loan Eligibility for Dream Housing Finance company # # Dream Housing Finance company deals in all kinds of home loans. They have prese...
# ### 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
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
{ 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
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
fn announce_progress(msg: &str) { println!("=== {msg} ==="); } fn print_minimized_case(concat_path: &Path) -> Result<(), std::io::Error> { announce_progress("Completed. Minimized test case:"); let contents = std::fs::read_to_string(concat_path)?; println!("{contents}"); Ok(()) } /// Arguments we...
{ 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
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
test_path: &Path, problem: Option<&str>, rs_file: &Path, extra_clang_args: &[&str], ) -> Result<(), std::io::Error> { announce_progress("Creating interestingness test"); let precompile = !matches.is_present("no-precompile"); let postcompile = !matches.is_present("no-postcompile"); let ru...
gen_cmd: &str,
random_line_split
main.rs
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
}; 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
import React from "react"; import Layout from '@theme/Layout'; import Video from '@site/src/components/Video'; import Features from '@site/src/components/Features'; import FeaturesWide from '@site/src/components/FeaturesWide'; import FAQ from '@site/src/components/FAQ'; import Customers from '@site/src/components/Cust...
() { return ( <Layout title="华炎魔方,华炎办公,审批王,低代码,零代码,快速开发工具,企业PaaS平台" description="华炎魔方是一款随需应变的管理软件开发工具,旨在通过其强大的敏捷性、灵活性和开放性帮助企业创新、扩展和集成企业业务系统。基于该平台,您可以快速创建智能化、移动化的企业应用。" keywords={["低代码,低代码开发,低代码开发平台,开源低代码开发平台,快速开发平台,快速开发工具,paas,零代码,零代码开发,零代码开发平台"]} > <section className="flex bg-cover bg-no-r...
Landing
identifier_name
cn.js
import React from "react"; import Layout from '@theme/Layout'; import Video from '@site/src/components/Video'; import Features from '@site/src/components/Features'; import FeaturesWide from '@site/src/components/FeaturesWide'; import FAQ from '@site/src/components/FAQ'; import Customers from '@site/src/components/Cust...
{ return ( <Layout title="华炎魔方,华炎办公,审批王,低代码,零代码,快速开发工具,企业PaaS平台" description="华炎魔方是一款随需应变的管理软件开发工具,旨在通过其强大的敏捷性、灵活性和开放性帮助企业创新、扩展和集成企业业务系统。基于该平台,您可以快速创建智能化、移动化的企业应用。" keywords={["低代码,低代码开发,低代码开发平台,开源低代码开发平台,快速开发平台,快速开发工具,paas,零代码,零代码开发,零代码开发平台"]} > <section className="flex bg-cover bg-no-repe...
identifier_body
cn.js
import React from "react"; import Layout from '@theme/Layout'; import Video from '@site/src/components/Video'; import Features from '@site/src/components/Features'; import FeaturesWide from '@site/src/components/FeaturesWide'; import FAQ from '@site/src/components/FAQ'; import Customers from '@site/src/components/Cust...
</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
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def _set_layer_names_and_weights(self, layer, names_and_weights): layer.set_weights([weight for _, weight in names_and_weights]) def _name(self, obj): return obj.__class__.__name__ def _get_matched_layers(self, transform): return self._transform_matched_layers_map.get(self._name(transform), []) ...
weight_value_tuples.append((weight_tensor, weights_map[weight_name])) K.batch_set_value(weight_value_tuples)
random_line_split
model_transformer.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
replacement_nodes.append(replacement_node) return replacement_nodes def _add_replacement_nodes(first_layer_removed_index, replacement_nodes): """Add replacement nodes to Sequential model.""" # Potentially insert nodes into middle of model. i = first_layer_removed_index for r...
replacement_nodes.extend(_get_replacement_nodes(input_layer))
conditional_block
model_transformer.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
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
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(self, layer, weights_map): """Sets the values of weights in a Keras layer.""" weight_value_tuples = [] for weight_tensor in layer.weights: weight_name = self._weight_name(weight_tensor.name) if weight_name in weights_map: weight_value_tuples.append((weight_tensor, weights_map[weight_na...
_set_layer_weights
identifier_name
generate_samples.py
import bpy from math import radians, pi, sin, cos import random import os, glob from scipy import ndimage, misc from skimage import draw, color import numpy as np def getChildren(objs): ## returns children of a blender object result = [] for o in bpy.data.objects: p = o.parent if p: ...
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
import bpy from math import radians, pi, sin, cos import random import os, glob from scipy import ndimage, misc from skimage import draw, color import numpy as np def getChildren(objs): ## returns children of a blender object result = [] for o in bpy.data.objects: p = o.parent if p: ...
o["cam_pos_range"] = (0,90) o.pass_index = i + 1 ## adjustments for cropped rendering if RENDER_CROPPED: ## place objects in the center of the scene for o in objects: o.location[0]=0 o.location[1]=0 cam_target.location[0]=0 ca...
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
import bpy from math import radians, pi, sin, cos import random import os, glob from scipy import ndimage, misc from skimage import draw, color import numpy as np def getChildren(objs): ## returns children of a blender object result = [] for o in bpy.data.objects: p = o.parent if p: ...
(): ## 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
import bpy from math import radians, pi, sin, cos import random import os, glob from scipy import ndimage, misc from skimage import draw, color import numpy as np def getChildren(objs): ## returns children of a blender object result = [] for o in bpy.data.objects: p = o.parent if p: ...
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
// Copyright 2019 Red Hat, Inc. and/or its affiliates // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
// +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
// Copyright 2019 Red Hat, Inc. and/or its affiliates // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
(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
// Copyright 2019 Red Hat, Inc. and/or its affiliates // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
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
// Copyright 2019 Red Hat, Inc. and/or its affiliates // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
// 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
use anyhow::Error; use async_stream::stream; use futures03::Stream; use std::fmt; use std::sync::Arc; use thiserror::Error; use tokio::sync::mpsc::{self, Receiver, Sender}; use super::{Block, BlockPtr, Blockchain}; use crate::anyhow::Result; use crate::components::store::{BlockNumber, DeploymentLocator}; use crate::da...
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
use anyhow::Error; use async_stream::stream; use futures03::Stream; use std::fmt; use std::sync::Arc; use thiserror::Error; use tokio::sync::mpsc::{self, Receiver, Sender}; use super::{Block, BlockPtr, Blockchain}; use crate::anyhow::Result; use crate::components::store::{BlockNumber, DeploymentLocator}; use crate::da...
(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
from __future__ import division import pandas_datareader as pdr from pandas_datareader.quandl import QuandlReader from collections import defaultdict import numpy as np from numpy import dot, sqrt import pandas as pd import datetime from random import uniform from scipy.stats import linregress from scipy.optimize impo...
# stack_windows = True, annotations=True, auto_open=True, required_return=0.177 ) CP.run_pack() # CP
# online = True, # window_size=3650, # window_move=365,
random_line_split
MPO.py
from __future__ import division import pandas_datareader as pdr from pandas_datareader.quandl import QuandlReader from collections import defaultdict import numpy as np from numpy import dot, sqrt import pandas as pd import datetime from random import uniform from scipy.stats import linregress from scipy.optimize impo...
R = self.exp_return_yr.values Fr = np.linspace(min(R), max(R), num=100) C = self.cov_matrix.iloc[:-1,:-1].values #cov matrix without market index Vf, Wf = qsolve(R, Fr, C) rf = self.risk_free_rate self.EFFsr = sharpe_ratio(Fr, Vf, rf) #sharpe ratio for portfolios on...
""" 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
from __future__ import division import pandas_datareader as pdr from pandas_datareader.quandl import QuandlReader from collections import defaultdict import numpy as np from numpy import dot, sqrt import pandas as pd import datetime from random import uniform from scipy.stats import linregress from scipy.optimize impo...
self.plot_data = list() # Clear plot data when plot is made def with_moving_windows(self, operation): def func_wrapper(): time = self.end - self.start # self.absolute_start = self.start # self.absolute_end = self.end window = datetime.timedelta(days...
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
from __future__ import division import pandas_datareader as pdr from pandas_datareader.quandl import QuandlReader from collections import defaultdict import numpy as np from numpy import dot, sqrt import pandas as pd import datetime from random import uniform from scipy.stats import linregress from scipy.optimize impo...
(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
var yt = yt || {}; //加载图片 yt.loadImg = function ($imgs, time) { var _time = 0; time = time || 200; $imgs.each(function () { var $that = $(this); if ($that.data('hasload')) { return false; } setTimeout(function () { $that.fadeOut(0); $that...
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
var yt = yt || {}; //加载图片 yt.loadImg = function ($imgs, time) { var _time = 0; time = time || 200; $imgs.each(function () { var $that = $(this); if ($that.data('hasload')) { return false; } setTimeout(function () { $that.fadeOut(0); $that...
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
var yt = yt || {}; //加载图片 yt.loadImg = function ($imgs, time) { var _time = 0; time = time || 200; $imgs.each(function () { var $that = $(this); if ($that.data('hasload')) { return false; } setTimeout(function () { $that.fadeOut(0); $that...
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
var yt = yt || {}; //加载图片 yt.loadImg = function ($imgs, time) { var _time = 0; time = time || 200; $imgs.each(function () { var $that = $(this); if ($that.data('hasload')) { return false; } setTimeout(function () { $that.fadeOut(0); $that...
p>\ <p><span class="prd-tag-bg">型号</span> APGM10L4136-B</p>\ <p><span class="prd-tag-bg">规格</span> 盆尺寸:702*409*198mm</p>\ <p class="prd-tag-sj">主柜尺寸:1010*545*820mm</p> <p class="prd-tag-sj">镜柜尺寸:950*160*650mm</p>'); // $('.prd-tag-up').css('display','none'); ...
>谢谢您参与!</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
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the Lice...
func (d *dnsClient) waitForAliDNSRateLimiter(ctx context.Context) error { timeoutCtx, cancel := context.WithTimeout(ctx, d.RateLimiterWaitTimeout) defer cancel() t := time.Now() if err := d.RateLimiter.Wait(timeoutCtx); err != nil { return &RateLimiterWaitError{Cause: err} } if waitDuration := time.Since(t); ...
{ 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
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the Lice...
records := make(map[string]alidns.Record) pageSize, pageNumber := 20, 1 req := alidns.CreateDescribeDomainRecordsRequest() req.PageSize = requests.NewInteger(pageSize) for { req.PageNumber = requests.NewInteger(pageNumber) req.DomainName = domainName req.RRKeyWord = rr req.TypeKeyWord = recordType resp,...
if err := d.waitForAliDNSRateLimiter(ctx); err != nil { return nil, err }
random_line_split
client_dns.go
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the Lice...
} return false } // CompositeDomainName composes and returns a composite domain name from the given domain name and id, // in the format <domainName>:<domainId> func CompositeDomainName(domainName, domainId string) string { if domainId != "" { return domainName + ":" + domainId } return domainName } // Domain...
{ return true }
conditional_block
client_dns.go
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the Lice...
(ctx context.Context, domainName, rr, recordType string) (map[string]alidns.Record, error) { if err := d.waitForAliDNSRateLimiter(ctx); err != nil { return nil, err } records := make(map[string]alidns.Record) pageSize, pageNumber := 20, 1 req := alidns.CreateDescribeDomainRecordsRequest() req.PageSize = reques...
getDomainRecords
identifier_name
lib.rs
// Copyright 2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed exce...
( _attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { // get a usable token stream let ast: syn::Item = parse_macro_input!(item as syn::Item); // Build the impl let expanded: TokenStream = impl_info_for_fdw(&ast); // Return the generated impl p...
pg_foreignwrapper
identifier_name
lib.rs
// Copyright 2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed exce...
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
// Copyright 2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed exce...
// 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
/** * @summary defines the main grid or control centre in the microgrid where all components of the grid * are connected to the grid. * @author Lev Stambler <levst@google.com> * @author Roland Naijuka <rnaijuka@google.com> * * Created at : 6/26/2020, 3:33:10 PM * Last modified : 7/29/2020, 9:43:17 AM */ im...
if (outOfBoundsCount > 3) { throw new Error( `There are too many items on the grid. New items could not be placed with a minimum distance of ${bioconstants.GRID_DISTANCES.INCREMENTS_KM} km apart` ); } return newPos; } private positionOutOfBounds(pos: ItemPosition, townSize: TownSiz...
{ 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
/** * @summary defines the main grid or control centre in the microgrid where all components of the grid * are connected to the grid. * @author Lev Stambler <levst@google.com> * @author Roland Naijuka <rnaijuka@google.com> * * Created at : 6/26/2020, 3:33:10 PM * Last modified : 7/29/2020, 9:43:17 AM */ im...
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
/** * @summary defines the main grid or control centre in the microgrid where all components of the grid * are connected to the grid. * @author Lev Stambler <levst@google.com> * @author Roland Naijuka <rnaijuka@google.com> * * Created at : 6/26/2020, 3:33:10 PM * Last modified : 7/29/2020, 9:43:17 AM */ im...
const cols = Math.ceil(numberOfGridItems / townSize.width); const rows = Math.ceil(numberOfGridItems / cols); const positions: ItemPosition[] = []; for (let i = 0; i < numberOfGridItems; i++) { const newPositionUnverified = { x: this.roundToGridDistance( (((i % cols) + 0.5) / col...
townSize: TownSize, numberOfGridItems: number ): ItemPosition[] {
random_line_split
biogrid-class.ts
/** * @summary defines the main grid or control centre in the microgrid where all components of the grid * are connected to the grid. * @author Lev Stambler <levst@google.com> * @author Roland Naijuka <rnaijuka@google.com> * * Created at : 6/26/2020, 3:33:10 PM * Last modified : 7/29/2020, 9:43:17 AM */ im...
(pos: ItemPosition): boolean { return this.itemInPosition[this.formatItemPosition(pos)]; } /** * Convert an item into a string */ private formatItemPosition(pos: ItemPosition): string { return `${pos.x}, ${pos.y}`; } }
positionOccupied
identifier_name
sync.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
/// 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
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
(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
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
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
# encoding: utf-8 """ @author : zhirui zhou @contact: evilpsycho42@gmail.com @time : 2020/5/13 10:17 """ from deepseries.model.rnn2rnn import RNN2RNN from deepseries.train import Learner from deepseries.dataset import TimeSeries, FeatureStore, Seq2SeqDataLoader import numpy as np from torch.optim import Adam import p...
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
# encoding: utf-8 """ @author : zhirui zhou @contact: evilpsycho42@gmail.com @time : 2020/5/13 10:17 """ from deepseries.model.rnn2rnn import RNN2RNN from deepseries.train import Learner from deepseries.dataset import TimeSeries, FeatureStore, Seq2SeqDataLoader import numpy as np from torch.optim import Adam import p...
(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
# encoding: utf-8 """ @author : zhirui zhou @contact: evilpsycho42@gmail.com @time : 2020/5/13 10:17 """ from deepseries.model.rnn2rnn import RNN2RNN from deepseries.train import Learner from deepseries.dataset import TimeSeries, FeatureStore, Seq2SeqDataLoader import numpy as np from torch.optim import Adam import p...
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
# encoding: utf-8 """ @author : zhirui zhou @contact: evilpsycho42@gmail.com @time : 2020/5/13 10:17 """ from deepseries.model.rnn2rnn import RNN2RNN from deepseries.train import Learner from deepseries.dataset import TimeSeries, FeatureStore, Seq2SeqDataLoader import numpy as np from torch.optim import Adam import p...
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
# -*- coding: utf-8 -*- # Copyright 2018 Telefonica S.A. # Copyright 2018 ALTRAN Innovación S.L. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
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
# -*- coding: utf-8 -*- # Copyright 2018 Telefonica S.A. # Copyright 2018 ALTRAN Innovación S.L. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
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
# -*- coding: utf-8 -*- # Copyright 2018 Telefonica S.A. # Copyright 2018 ALTRAN Innovación S.L. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
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
# -*- coding: utf-8 -*- # Copyright 2018 Telefonica S.A. # Copyright 2018 ALTRAN Innovación S.L. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
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
#!/usr/bin/env python3 """ Usage: setup-cluster-images image-archive [num_nodes [targetdir]] image-archive - zip file as downloaded from raspberry-pi.org num_nodes - number of nodes in the cluster [4] node_prefix - prefix for the cluster nodes [gg] targetdir - destination directory...
raise RuntimeError('Invalid IP address: %s' % param) return param def main(*args): 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 l...
continue
conditional_block
setup-cluster-images.py
#!/usr/bin/env python3 """ Usage: setup-cluster-images image-archive [num_nodes [targetdir]] image-archive - zip file as downloaded from raspberry-pi.org num_nodes - number of nodes in the cluster [4] node_prefix - prefix for the cluster nodes [gg] targetdir - destination directory...
if __name__ == '__main__': def prepare_names(num_nodes, prefix): result = [prefix + '-master'] for i in range(1, num_nodes): result += ['%s-node-%d' % (prefix, i)] return tuple(result) if len(sys.argv) < 2: exit(__doc__) if geteuid() != 0: exit("You ...
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
#!/usr/bin/env python3 """ Usage: setup-cluster-images image-archive [num_nodes [targetdir]] image-archive - zip file as downloaded from raspberry-pi.org num_nodes - number of nodes in the cluster [4] node_prefix - prefix for the cluster nodes [gg] targetdir - destination directory...
(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
#!/usr/bin/env python3 """ Usage: setup-cluster-images image-archive [num_nodes [targetdir]] image-archive - zip file as downloaded from raspberry-pi.org num_nodes - number of nodes in the cluster [4] node_prefix - prefix for the cluster nodes [gg] targetdir - destination directory...
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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
/// 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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
(run_config: &NodeRunConfig) -> InstanceInitParams { let mode = run_config .node_config .public_config .general .supervisor_mode .clone(); Supervisor::builtin_instance(SupervisorConfig { mode }) } }
supervisor_service
identifier_name
main.py
"""This program displays a customizable list of items by priority value, with priority 1 being the highest. Allows the user to add, edit, mark complete, show completed (hidden), and remove items. Stores the list of items in a .txt file located where this program's main.py file is. All changes are automatically save...
(todo_list, prompt='Error'): # Ask the user # which item from the list is to be modified """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 ...
select_item
identifier_name
main.py
"""This program displays a customizable list of items by priority value, with priority 1 being the highest. Allows the user to add, edit, mark complete, show completed (hidden), and remove items. Stores the list of items in a .txt file located where this program's main.py file is. All changes are automatically save...
def remove_item(todo_list): """The purpose of this function is to delete a ListItem object from a list of ListItem objects by prompting the user for the index and verifying they want to delete the item. :param todo_list: the list of ListItem objects from which to remove one object :r...
"""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
"""This program displays a customizable list of items by priority value, with priority 1 being the highest. Allows the user to add, edit, mark complete, show completed (hidden), and remove items. Stores the list of items in a .txt file located where this program's main.py file is. All changes are automatically save...
invalid_input = False while selection != 6: if invalid_input: invalid_input = False else: print_list(save_file_location, todo_list, True, show_hidden) divider(137 + 17) # Length of prompt statement below list_status = check_list_status(todo_list) ...
random_line_split
main.py
"""This program displays a customizable list of items by priority value, with priority 1 being the highest. Allows the user to add, edit, mark complete, show completed (hidden), and remove items. Stores the list of items in a .txt file located where this program's main.py file is. All changes are automatically save...
return state def menu_loop(todo_list, save_file_location): """The purpose of this function is to repeatedly display the todo list and user prompts menu until the program is closed :param todo_list: the list of ListItem objects to display or modify :param save_file_location: where the .txt ...
if todo_list[item_index].visible: # If an item is visible, then # they are not all hidden state = 0 # Neither
conditional_block
routes.py
""" Analysis dashboards module. """ try: from collections.abc import Iterable except ImportError: from collections import Iterable import copy from datetime import datetime, timedelta import json import logging import re import numpy as np import pandas as pd from flask_login import login_required from flask...
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
""" Analysis dashboards module. """ try: from collections.abc import Iterable except ImportError: from collections import Iterable import copy from datetime import datetime, timedelta import json import logging import re import numpy as np import pandas as pd from flask_login import login_required from flask...
f, dt_from, dt_to): """ Performs temperature range analysis on a given pandas dataframe. Arguments: temp_df: dt_from: date range from dt_to: date range to Returns: sensor_names: a list of sensor names sensor_temp_ranges: json data with temperate ranges """ ...
ture_range_analysis(temp_d
identifier_name
routes.py
""" Analysis dashboards module. """ try: from collections.abc import Iterable except ImportError: from collections import Iterable import copy from datetime import datetime, timedelta import json import logging import re import numpy as np import pandas as pd from flask_login import login_required from flask...
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
""" Analysis dashboards module. """ try: from collections.abc import Iterable except ImportError: from collections import Iterable import copy from datetime import datetime, timedelta import json import logging import re import numpy as np import pandas as pd from flask_login import login_required from flask...
""" 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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
}) } /// 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
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
(&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
"use strict"; const fs = require("fs"); const util = require("util"); const {core, utils, values} = require("@ckb-lumos/base"); const {computeScriptHash} = utils; const {secp256k1Blake160} = require("@ckb-lumos/common-scripts"); const {locateCellDep, sealTransaction} = require("@ckb-lumos/helpers"); const {Cel...
{ 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
"use strict"; const fs = require("fs"); const util = require("util"); const {core, utils, values} = require("@ckb-lumos/base"); const {computeScriptHash} = utils; const {secp256k1Blake160} = require("@ckb-lumos/common-scripts"); const {locateCellDep, sealTransaction} = require("@ckb-lumos/helpers"); const {Cel...
(filename) { const readFile = util.promisify(fs.readFile); return await readFile(filename); } function readFileSync(filename) { return fs.readFileSync(filename); } async function readFileToHexString(filename) { const data = await readFile(filename); const dataSize = data.length; const hexStri...
readFile
identifier_name
index.js
"use strict"; const fs = require("fs"); const util = require("util"); const {core, utils, values} = require("@ckb-lumos/base"); const {computeScriptHash} = utils; const {secp256k1Blake160} = require("@ckb-lumos/common-scripts"); const {locateCellDep, sealTransaction} = require("@ckb-lumos/helpers"); const {Cel...
/** * Creates a signature for the provided message with the provided private key using the Secp256k1 algorithm. * * @param {String} privateKey A 256-bit Secp256k1 private key represented as a hex string. * @param {String} message A message to sign represented as a hex string. * * @return {String} A 6...
{ 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
import jsonpickle import json as serializer from pkg_resources import Requirement, resource_filename import os import csv from Crypto.Cipher import ARC4 import base64 import socket import getpass from solidfire.factory import ElementFactory from filelock import FileLock import sys def kv_string_to_dict(kv_string): ...
def print_result_as_json(objs, pickle=False): #print(jsonpickle.encode(objs)) nestedDict = serializer.loads(jsonpickle.encode(objs)) filteredDict = type(nestedDict)() if(pickle==False): remove_pickling(nestedDict, filteredDict) else: filteredDict = nestedDict print(serializer.d...
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