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
flap.py
FPS = 30 # tweak this to change how quickly the bird falls GRAVITY = 1 # how big the gaps between the pipes are GAP = 100 # how frequently the pipes spawn (sec) FREQ = 2 # how fast the bird flies at the pipes PIPE_SPEED = 3 # how powerful is a flap? FLAP_SPEED = 15 # set up asset folders game_dir = path.dirname(__file...
else: self.rect.top = y # has the bird passed this pipe? self.passed = False def update(self): # move self.rect.x += self.speed_x def offscreen(self): # test to see if the pipe has moved offscreen if self.rect.right < 0: return T...
self.rect.bottom = y
conditional_block
flap.py
= 30 # tweak this to change how quickly the bird falls GRAVITY = 1 # how big the gaps between the pipes are GAP = 100 # how frequently the pipes spawn (sec) FREQ = 2 # how fast the bird flies at the pipes PIPE_SPEED = 3 # how powerful is a flap? FLAP_SPEED = 15 # set up asset folders game_dir = path.dirname(__file__)...
(self): # gravity pulls downward self.speed_y += gravity # move self.rect.x += self.speed_x self.rect.y += self.speed_y if self.alive: # animate self.index += 1 if self.index >= len(self.frames): self.index = 0 ...
update
identifier_name
flap.py
FPS = 30 # tweak this to change how quickly the bird falls GRAVITY = 1 # how big the gaps between the pipes are GAP = 100 # how frequently the pipes spawn (sec) FREQ = 2 # how fast the bird flies at the pipes PIPE_SPEED = 3 # how powerful is a flap?
FLAP_SPEED = 15 # set up asset folders game_dir = path.dirname(__file__) img_dir = path.join(game_dir, 'img') snd_dir = path.join(game_dir, 'snd') class SpriteSheet: """Utility class to load and parse spritesheets""" def __init__(self, filename): self.sprite_sheet = pygame.image.load(filename).convert...
random_line_split
kubernetes_decorator.py
a step to execute on Kubernetes regardless of the ```--with``` specification. To use, annotate your step as follows: ``` @kubernetes @step def my_step(self): ... ``` Parameters ---------- cpu : int Number of CPUs required for this step. Defaults to 1. If @resour...
# We use the larger of @resources and @batch attributes # TODO: Fix https://github.com/Netflix/metaflow/issues/467 my_val = self.attributes.get(k) if not (my_val is None and v is None): self.attr...
continue
conditional_block
kubernetes_decorator.py
a step to execute on Kubernetes regardless of the ```--with``` specification. To use, annotate your step as follows: ``` @kubernetes @step def my_step(self): ... ``` Parameters ---------- cpu : int Number of CPUs required for this step. Defaults to 1. If @resour...
meta["kubernetes-pod-name"] = os
# variable. if "METAFLOW_KUBERNETES_WORKLOAD" in os.environ: meta = {}
random_line_split
kubernetes_decorator.py
step to execute on Kubernetes regardless of the ```--with``` specification. To use, annotate your step as follows: ``` @kubernetes @step def my_step(self): ... ``` Parameters ---------- cpu : int Number of CPUs required for this step. Defaults to 1. If @resource...
(self, flow, graph, step, decos, environment, flow_datastore, logger): # Executing Kubernetes jobs requires a non-local datastore. if flow_datastore.TYPE != "s3": raise KubernetesException( "The *@kubernetes* decorator requires --datastore=s3 at the moment." ) ...
step_init
identifier_name
kubernetes_decorator.py
step to execute on Kubernetes regardless of the ```--with``` specification. To use, annotate your step as follows: ``` @kubernetes @step def my_step(self): ... ``` Parameters ---------- cpu : int Number of CPUs required for this step. Defaults to 1. If @resource...
def runtime_step_cli( self, cli_args, retry_count, max_user_code_retries, ubf_context ): if retry_count <= max_user_code_retries: # After all attempts to run the user code have failed, we don't need # to execute on Kubernetes anymore. We can execute possible fallback ...
if not is_cloned: self._save_package_once(self.flow_datastore, self.package)
identifier_body
account_control.js
License for the specific language governing permissions and * limitations under the License. */ import("stringutils"); import("stringutils.*"); import("funhtml.*"); import("email.sendEmail"); import("cache_utils.syncedWithCache"); import("etherpad.helpers"); import("etherpad.utils.*"); import("etherpad.sessions.ge...
() { return _topDiv('signin-notice', 'accountSigninNotice'); } function _renderTemplate(name, data) { data.messageDiv = _messageDiv; data.errorDiv = _errorDiv; data.signinNotice = _signinNoticeDiv; data.tempFormData = getSession().tempFormData; renderFramed('pro/account/'+name+'.ejs', data); } //-----------...
_signinNoticeDiv
identifier_name
account_control.js
License for the specific language governing permissions and * limitations under the License. */ import("stringutils"); import("stringutils.*"); import("funhtml.*"); import("email.sendEmail"); import("cache_utils.syncedWithCache"); import("etherpad.helpers"); import("etherpad.utils.*"); import("etherpad.sessions.ge...
function render_guest_sign_in_post() { function _err(m) { if (m) { getSession().guestAccessError = m; response.redirect(request.url); } } var displayName = request.params.guestDisplayName; var localPadId = request.params.localPadId; if (!(displayName && displayName.length > 0)) { _er...
{ var localPadId = request.params.padId; var domainId = domains.getRequestDomainId(); var globalPadId = padutils.makeGlobalId(domainId, localPadId); var userId = padusers.getUserId(); pro_account_auto_signin.checkAutoSignin(); pad_security.clearKnockStatus(userId, globalPadId); _renderTemplate('signin-g...
identifier_body
account_control.js
License for the specific language governing permissions and * limitations under the License. */ import("stringutils"); import("stringutils.*"); import("funhtml.*"); import("email.sendEmail"); import("cache_utils.syncedWithCache"); import("etherpad.helpers"); import("etherpad.utils.*"); import("etherpad.sessions.ge...
if (password != passwordConfirm) { _redirOnError('Passwords did not match.'); } _redirOnError(pro_accounts.validateEmail(email)); _redirOnError(pro_accounts.validateFullName(fullName)); _redirOnError(pro_accounts.validatePassword(password)); pro_accounts.createNewAccount(null, fullName, email, password, tru...
getSession().tempFormData.email = email; getSession().tempFormData.fullName = fullName;
random_line_split
account_control.js
License for the specific language governing permissions and * limitations under the License. */ import("stringutils"); import("stringutils.*"); import("funhtml.*"); import("email.sendEmail"); import("cache_utils.syncedWithCache"); import("etherpad.helpers"); import("etherpad.utils.*"); import("etherpad.sessions.ge...
_renderTemplate('signin', { domain: pro_utils.getFullProDomain(), siteName: toHTML(pro_config.getConfig().siteName), email: getSession().tempFormData.email || "", password: getSession().tempFormData.password || "", rememberMe: getSession().tempFormData.rememberMe || false, showGuestBox: showG...
{ showGuestBox = true; }
conditional_block
gui_debugging.py
deltaP = [mean_power - P for P in trap_powers] dmags = [(dP / abs(dP)) * sqrt(abs(dP)) * L for dP in deltaP] mags = np.add(mags, dmags) print("Magnitudes: ", mags) break # self._update_magnitudes(mags) _ = analyze_image(im, ntraps, verbose=verbose) def _run_cam(wh...
print("WOW") break
conditional_block
gui_debugging.py
sqrt(abs(dP)) * L for dP in deltaP] mags = np.add(mags, dmags) print("Magnitudes: ", mags) break # self._update_magnitudes(mags) _ = analyze_image(im, ntraps, verbose=verbose) def _run_cam(which_cam, verbose=False): names = ['ThorCam', 'ChamberCam'] # False, True ## http...
(i): if cam.wait_for_frame(): im = cam.latest_frame() ax1.clear() ax1.imshow(im) ## Button: Automatic Exposure Adjustment ## def find_exposure(event): fix_exposure(cam, set_exposure, verbose) ## Button: Intensity Feedback ## def stabilize(event): # ...
animate
identifier_name
gui_debugging.py
sqrt(abs(dP)) * L for dP in deltaP] mags = np.add(mags, dmags) print("Magnitudes: ", mags) break # self._update_magnitudes(mags) _ = analyze_image(im, ntraps, verbose=verbose) def _run_cam(which_cam, verbose=False): names = ['ThorCam', 'ChamberCam'] # False, True ## http...
switch_cameras.on_clicked(switch_cam) set_exposure.on_changed(adjust_exposure) ## Begin Animation ## _ = animation.FuncAnimation(fig, animate, interval=100) plt.show() plt.close(fig) ########## Helper Functions ############### # noinspection PyPep8Naming def gaussian1d(x, x0, w0, A, offset): ...
stabilize_button.on_clicked(stabilize) # pause_play.on_clicked(playback) plot_snapshot.on_clicked(snapshot)
random_line_split
gui_debugging.py
mean_power = trap_powers.mean() rel_dif = 100 * trap_powers.std() / mean_power print(f'Relative Power Difference: {rel_dif:.2f} %') if rel_dif < 0.8: print("WOW") break deltaP = [mean_power - P for P in trap_powers] dmags = [(dP / abs(dP)) * sqrt...
""" Given a UC480 camera object (instrumental module) and a number indicating the number of trap objects, applies an iterative image analysis to individual trap adjustment in order to achieve a nearly homogeneous intensity profile across traps. """ L = 0.5 # Correction Rate mags = ...
identifier_body
operations.go
w", err) } op.store.session, err = session.NewStore() if err != nil { return nil, fmt.Errorf("failed to create web auth protocol session store: %w", err) } op.store.users, err = user.NewStore(config.Storage.Storage) if err != nil { return nil, fmt.Errorf("failed to open users store: %w", err) } return op...
{ common.WriteErrorResponsef(w, logger, http.StatusInternalServerError, "failed to get user data %s:", err.Error()) return nil, false }
conditional_block
operations.go
", err) } op.store.users, err = user.NewStore(config.Storage.Storage) if err != nil { return nil, fmt.Errorf("failed to open users store: %w", err) } return op, nil } // GetRESTHandlers get all controller API handler available for this service. func (o *Operation) GetRESTHandlers() []common.Handler { return ...
saveCookie
identifier_name
operations.go
authn.WebAuthn HubAuthURL string } // StorageConfig holds storage config. type StorageConfig struct { Storage ariesstorage.Provider SessionStore ariesstorage.Provider } type stores struct { users *user.Store cookies cookie.Store storage ariesstorage.Store session *session.Store } type httpClient i...
op.store.session, err = session.NewStore() if err != nil { return nil, fmt.Errorf("failed to create web auth protocol session store: %w", err) } op.store.users, err = user.NewStore(config.Storage.Storage) if err != nil { return nil, fmt.Errorf("failed to open users store: %w", err) } return op, nil } //...
{ op := &Operation{ store: &stores{ cookies: cookie.NewStore(config.Cookie), }, tlsConfig: config.TLSConfig, httpClient: &http.Client{Transport: &http.Transport{TLSClientConfig: config.TLSConfig}}, webauthn: config.Webauthn, walletDashboard: config.WalletDashboard, hubAuthURL: c...
identifier_body
operations.go
webauthn.WebAuthn HubAuthURL string } // StorageConfig holds storage config. type StorageConfig struct { Storage ariesstorage.Provider SessionStore ariesstorage.Provider } type stores struct { users *user.Store cookies cookie.Store storage ariesstorage.Store session *session.Store } type httpClien...
}, } registerOptions := func(credCreationOpts *protocol.PublicKeyCredentialCreationOptions) { credCreationOpts.User = webAuthnUser credCreationOpts.CredentialExcludeList = device.CredentialExcludeList() credCreationOpts.Attestation = protocol.PreferDirectAttestation } // generate PublicKeyCredentialCreati...
ID: device.WebAuthnID(), DisplayName: device.WebAuthnDisplayName(), CredentialEntity: protocol.CredentialEntity{ Name: device.WebAuthnName(),
random_line_split
main.go
IP: C.GoString(&pAlarmer.sDeviceIP[0]), Command: int(command)} // switch int(command) { // case COMM_ALARM_V30: // log.Println("ALARM") // i.AlarmType = int(C.getalarminfo(pAlarmInfo).dwAlarmType) // motions <- i // break // case COMM_DEV_STATUS_CHANGED: // log.Printf("COMM_DEV_STATUS_CHANGED") // break ...
b.Send(m.Sender, "Camera online.") } else { b.Send(m.Sender, fmt.Sprintf("Fail [%d].", res)) } } done <- 1 }) b.Handle(tb.OnText, func(m *tb.Message) { <-done if m.Sender.ID == *adminParam { if strings.HasPrefix(m.Text, "/dl_") { mm, _ := b.Send(admin, "Loading...") log.Println(m.Text...
b.Send(m.Sender, "Wait 3 sec.") time.Sleep(3 * time.Second) }
conditional_block
main.go
() string { return string(t) } // //export onmessagev30 // func onmessagev30(command C.int, pAlarmer *C.NET_DVR_ALARMER, pAlarmInfo *C.char, dwBufLen C.uint, pUserData unsafe.Pointer) { // i := AlarmItem{IP: C.GoString(&pAlarmer.sDeviceIP[0]), Command: int(command)} // switch int(command) { // case COMM_ALARM_V30:...
Recipient
identifier_name
main.go
: // log.Println("ALARM") // i.AlarmType = int(C.getalarminfo(pAlarmInfo).dwAlarmType) // motions <- i // break // case COMM_DEV_STATUS_CHANGED: // log.Printf("COMM_DEV_STATUS_CHANGED") // break // default: // log.Printf("Unknown Alarm [0x%x] !!!", command) // } // } // //export onmessage // func onme...
if filename, ok := videolist[m.Text[4:]]; ok { os.MkdirAll(filepath.Join(*datadirParam, strings.Split(filename, "/")[0]), 0755) fname := filepath.Join(*datadirParam, filename+".mpeg") p := &tb.Video{}
random_line_split
main.go
_, ma := hiklib.HikMotionArea(user) col := color.RGBA{255, 0, 0, 128} var dst *image.RGBA var b image.Rectangle f, err := os.Open(fname) if err == nil { defer f.Close() img, _, err := image.Decode(f) if err == nil { b = img.Bounds() dst = image.NewRGBA(image.Rect(0, 0, b...
// user = C.HLogin(C.CString(*ipParam), C.CString(*userParam), C.CString(*passParam), &dev) user, dev = hiklib.HikLogin(*ipParam, *userParam, *passParam) if int(user) > -1 { if *x1Param { hiklib.HikOnAlarmV30(user, *alarmParam, func(item hiklib.AlarmItem) { motions <- item }) } else { hiklib.HikOnAl...
identifier_body
sync_keys.py
2_ALPHABET[((data[idx + 2] & 0x0F) << 1) | ((data[idx + 3] & 0x80) >> 7)] result += ZBASE32_ALPHABET[(data[idx + 3] & 0x7C) >> 2] if idx + 4 == len(data): result += ZBASE32_ALPHABET[(data[idx + 3] & 0x03) << 3] break result += ZBASE32_ALPHABET[((data[idx + 3] & 0x03) << 3...
email = email.lower() # Download the key using WKD wkd_url = get_wkd_advanced_url(email) try: with urllib.request.urlopen(wkd_url) as response: raw_key = response.read() except urllib.error.URLError: ...
conditional_block
sync_keys.py
range(8): crc <<= 1 if (crc & 0x1000000) != 0: crc ^= 0x1864CFB assert 0 <= crc <= 0xFFFFFF return crc def opgp_crc24_b64(data: bytes) -> str: """Computes the CRC24 used by OpenPGP Message Format, encoded in base64""" crc = opgp_crc24(data) return "=" + bas...
() -> None: """Verify that the algorithm computing WKD URLs work""" assert len(ZBASE32_ALPHABET) == 32 # Test vector from https://github.com/matusf/z-base-32/blob/0.1.2/src/lib.rs assert zbase32_encode(b"asdasd") == "cf3seamuco" assert zbase32_decode("cf3seamuco") == b"asdasd" # Test vector fr...
self_check
identifier_name
sync_keys.py
1] & 0x3E) >> 1] if idx + 2 == len(data): result += ZBASE32_ALPHABET[(data[idx + 1] & 0x01) << 4] break result += ZBASE32_ALPHABET[((data[idx + 1] & 0x01) << 4) | ((data[idx + 2] & 0xF0) >> 4)] if idx + 3 == len(data): result += ZBASE32_ALPHABET[(data[idx + 2...
"""Sync all the keys and refresh the given file""" file_lines = [] with keys_path.open("r") as fkeys: for line in fkeys: line = line.strip() if not line or line.startswith("#"): # Keep comments and empty lines file_lines.append(line) ...
identifier_body
sync_keys.py
) -> str: """Craft an URL for WKD direct method""" local, domain = email.split("@", 1) domain = domain.lower() local_sha1 = hashlib.sha1(local.lower().encode("ascii")).digest() local_b32 = zbase32_encode(local_sha1) params = urllib.parse.urlencode({"l": local}) return f"https://{domain}/.wel...
print("-----END PGP PUBLIC KEY BLOCK-----", file=fkey) # Write the key ID in the file new_line = f"0x{key_id} {email}" if len(fields) > 2:
random_line_split
10_msaa.rs
&model_vertices) .unwrap(); // Create MVP uniform. let uniform_handle = renderer .load_uniform_buffer(DefaultForwardShaderLayout::default()) .unwrap(); // Load textures and create image. let model_texture_file = if use_glb { image::open(MODEL_TEXTURE_FILE_NAME_GLB).unwrap() } else { ima...
random_line_split
10_msaa.rs
_time = Instant::now(); let mut last_frame_time = start_time; let mut frame_number = 0; let mut fps_average = 0f32; let mut camera_height = -0.5f32; // Run the loop. event_loop.run_return(move |event, _, control_flow| { // By default continuously run this event loop, even if the OS hasn't // distr...
{ for &vert in [x, y, z].iter() { // We're only building a buffer of indices and vertices which contain position // and tex coord. let index_key = (vert.0, vert.1.unwrap()); if let Some(&vtx_index) = inserted_indices.get(&index_key) { // Already lo...
conditional_block
10_msaa.rs
() { simple_logger::init_with_level(Level::Info).unwrap(); main_loop(); } /// Takes full control of the executing thread and runs the event loop for it. fn main_loop() { let args: Vec<String> = std::env::args().collect(); let show_fps = args.contains(&"fps".to_owned()); let use_glb = args.contains(&"glb".to_...
main
identifier_name
10_msaa.rs
let mut ar = WIDTH as f32 / HEIGHT as f32; // Build Window. let mut event_loop = EventLoop::new(); let window = Arc::new( WindowBuilder::new() .with_inner_size(LogicalSize::new(WIDTH, HEIGHT)) .build(&event_loop) .unwrap(), ); // Build Renderer. let config = Config::builder() ....
{ let args: Vec<String> = std::env::args().collect(); let show_fps = args.contains(&"fps".to_owned()); let use_glb = args.contains(&"glb".to_owned()); let msaa_level = if args.contains(&"4x".to_owned()) { 4u8 } else if args.contains(&"8x".to_owned()) { 8u8 } else if args.contains(&"noaa".to_owned())...
identifier_body
QueueWorkerService.ts
console.log('bullqueue paused') }) .on('resumed', function (job) { // The queue has been resumed. console.log('bullqueue resumed') }) .on('cleaned', function (jobs, type) { // Old jobs have bee...
ventService.once(eventName, (data) => { this.logger.info(`ESL Send Stop Job:${data.jobId} ,My Job Is: ${args.id}`); if (data.jobId === args.id) { eslSendStop = true; } }) const startTime = new Date().getTime(); let i...
identifier_body
QueueWorkerService.ts
60 * 1000; // 最多执行30分钟 this.doneInComeCall(job, queueIndex, MaxDoneTime) .then(res => { this.logger.debug('doneInComeCall res:', res); done(null,res); }) .catch(err => { ...
stamp } = actJobOpts; console.log(`myJob:[${args.id},${args.opts.priority},${args.opts.timestamp}],compareJob:[${actJobId},${priority},${timestamp}]`); if (priority < args.opts.priority) { this.logger.info('=============存在优先级比我高的=============')...
conditional_block
QueueWorkerService.ts
如果已经存在,返回 */ add(tenantId: string, queueNumber: string): Queue { const qNameTopic = `esl_q_queue::${tenantId}::${queueNumber}`; if (this.queueTopics.indexOf(qNameTopic) < 0) { const queue = new BullQueue(qNameTopic, this.queueOptions); this.queueTopics.push(qNameTopic) ...
.reject(ex);
identifier_name
QueueWorkerService.ts
import { PBXExtensionController } from '../controllers/pbx_extension'; import { PBXAgentController } from '../controllers/pbx_agent'; import { UserEventController } from '../controllers/userEvent'; import { RedisOptions, Redis } from 'ioredis'; import Redlock = require('redlock'); import { Lock } from 'redlock'; @Inj...
import { EventService } from '../service/EventService'; import { TenantController } from '../controllers/tenant';
random_line_split
op.rs
impl<F: Float> DummyOp<F> { #[allow(dead_code)] pub(crate) fn new() -> Self { DummyOp { phantom: PhantomData, } } } impl<F: Float> Op<F> for DummyOp<F> { fn compute(&self, _: &mut ComputeContext<F>) -> Result<(), OpError> { Ok(()) } fn grad(&self, _: &mut Gra...
{ GradientContext { gy, y, graph, gxs: SmallVec::new(), } }
identifier_body
op.rs
//! .build(Sigmoid) //! } //! ``` //! use std::any::type_name; use std::fmt; use std::marker::PhantomData; use std::mem; use crate::ndarray_ext::{NdArrayView, NdArrayViewMut, RawNdArrayView}; use crate::smallvec::SmallVec as RawSmallVec; use crate::tensor::Tensor; use crate::{Float, NdArray}; use crate::op:...
{ NdArrayError(String, ndarray::ShapeError), IncompatibleShape(String), TypeUnsupported(String), InvalidDims(String), OutOfBounds(String), } impl std::error::Error for OpError {} impl fmt::Display for OpError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ...
OpError
identifier_name
op.rs
//! .build(Sigmoid) //! } //! ``` //! use std::any::type_name; use std::fmt; use std::marker::PhantomData; use std::mem; use crate::ndarray_ext::{NdArrayView, NdArrayViewMut, RawNdArrayView}; use crate::smallvec::SmallVec as RawSmallVec; use crate::tensor::Tensor; use crate::{Float, NdArray}; use crate::op:...
i, i ), }, OpInput::RdWrVariable(_) => { panic!( "Bad op impl: cannot perform mutable borrowing for input({}). Use input_mut() instead.", i ); } } } /// Grabs ...
None => panic!( "Bad op impl: input({})/input_mut({}) cannot be called twice",
random_line_split
de.sc.portal.env.dlg.mongo.js
rendererOptions: { showDataLabels: true, dataLabels: 'value', sliceMargin: 2, startAngle: -90, innerDiameter: 5, ringMargin: 5, shadow: true, showMarker: true, markerOptions: { show: true }, pointLabels: { show: true, location: 's' }, smooth: t...
random_line_split
mapfile.rs
State::Base } else { TileState::Generated } }, ) } pub(crate) fn read_texture( &self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, name: &str, ) -> Result<wgpu::Texture, Error> { let desc = self.lookup_texture(name)?.unwrap(); let textur...
{ let value = serde_json::to_vec(&desc).unwrap(); self.textures.insert(name, value)?; Ok(()) }
identifier_body
mapfile.rs
(&directory).expect(&format!( "Failed to open/create sled database. Deleting the '{}' directory may fix this", directory.display() )); db.insert("version", "1").unwrap(); Self { layers, tiles: db.open_tree("tiles").unwrap(), textures: d...
( &self, layer: LayerType, node: VNode, base: bool, ) -> Result<TileState, Error> { let filename = Self::tile_name(layer, node); let meta = self.lookup_tile_meta(layer, node); let exists = filename.exists(); let target_state = if base && exists { ...
reload_tile_state
identifier_name
mapfile.rs
= vec![0i16; data.len()]; let mut prev = 0; for (q, d) in qdata.iter_mut().zip(data.iter()) { let x = ((*d as i16) / 4) * 4; *q = x.wrapping_sub(prev); prev = x; } snap::write::FrameEncoder::ne...
mut f: F, ) -> Result<(), Error> { let prefix = bincode::serialize(&layer).unwrap();
random_line_split
run.py
_index, source_pop in enumerate(par.label): n_target = num_neurons[target_index] n_source = num_neurons[source_index] K[target_index][source_index] = np.log(1. - par.conn_probs[target_index][source_index]) / np.log( 1. - 1. / (n_tar...
def projectionwise_synapse_loss(self, proj, marocco): """ computes the synapse loss of a projection params: proj - a pyhmf.Projection marocco - the PyMarocco object after the mapping has run. returns: (nr of lost synapses, total synapses in projection) "...
pynn.run(1) pynn.end()
identifier_body
run.py
_index, source_pop in enumerate(par.label): n_target = num_neurons[target_index] n_source = num_neurons[source_index] K[target_index][source_index] = np.log(1. - par.conn_probs[target_index][source_index]) / np.log( 1. - 1. / (n_tar...
sourceSize = self.populations[sourcePop].size targetSize = self.populations[targetPop].size # In-degree scaling as described in Albada et al. (2015) "Scalability of Asynchronous Networks # Is Limited by One-to-One Mapping between Effective Connectivity ...
target = "inhibitory"
conditional_block
run.py
source_index, source_pop in enumerate(par.label): n_target = num_neurons[target_index] n_source = num_neurons[source_index] K[target_index][source_index] = np.log(1. - par.conn_probs[target_index][source_index]) / np.log( 1. - 1. /...
self.externalInputPops[layer[1:] + "e"] = pynn.Population( self.populations[layer[1:] + "e"].size, pynn.SpikeSourcePoisson, {'rate': rate_to_ex}) self.externalInputPops[layer[1:] + "i"] = pynn.Population( self.populations[layer[1:] + "i"].size, pyn...
for layer, amount in par.K_ext.items(): # rate is given in model with 8Hz # will not work for large networks, for now it is not used due to par.external_source rate_to_ex = par.bg_rate * amount["E"] * self.k_scale rate_to_in = par.bg_rate * amo...
random_line_split
run.py
_index, source_pop in enumerate(par.label): n_target = num_neurons[target_index] n_source = num_neurons[source_index] K[target_index][source_index] = np.log(1. - par.conn_probs[target_index][source_index]) / np.log( 1. - 1. / (n_tar...
(): parser = argparse.ArgumentParser() # scale factor of the whole network compared to the original one parser.add_argument('--scale', default=0.01, type=float) # size of one neueron in hw neurons parser.add_argument('--n_size', default=4, type=int) parser.add_argument('--k_scale', type=float) ...
main
identifier_name
a1_300068688.py.py
n' times print(str(yoda)) #prints 'yoda' ######################## # Question 2 ######################## ''' creates a function called is_prime that takes one argument and check to see whether it is prime or not, if it is a prime the function return true if not it returns else''' def is_prime(n): if ...
else: return reverse == string ######################## # Question 12 ######################## ''' creates a function called rps that is a game of rock, paper, scissors and takes two input paramteres that are strings that are either 'S' 'P' 'R' and returns a -1 if player 1 wins and a 1 if player ...
return reverse == string
conditional_block
a1_300068688.py.py
n' times print(str(yoda)) #prints 'yoda' ######################## # Question 2 ######################## ''' creates a function called is_prime that takes one argument and check to see whether it is prime or not, if it is a prime the function return true if not it returns else''' def is_prime(n): if ...
######################## # Question 6 ######################## ''' creates a function vowelCount that takes one argument which is a string and then prints out the number of vowels and what vowels are in the word''' def vowelCount(string): print('a, e, i, o, and u appear, respectively, ' + str(string.count('...
reverse1 = num%10 # gets you the number of the begining of the reversed integer reverse2 = (num%100)-reverse1 # gets you the number of the second number in the reversed inetger reverse1 = reverse1*100 # makes the number at the end now the begining reverse3 = num//100 #gives you last number in the revers...
identifier_body
a1_300068688.py.py
n' times print(str(yoda)) #prints 'yoda' ######################## # Question 2 ######################## ''' creates a function called is_prime that takes one argument and check to see whether it is prime or not, if it is a prime the function return true if not it returns else''' def is_prime(n): if ...
(letter): if letter== 'A' or'A-' or 'A+': #checks to see if it was an A, A+ or A- if letter == 'A': #assigns the corresponding number value to the letter and prints it print(str(4)) elif letter == 'A+': print(str(4+0.3)) elif letter== 'A-': print(s...
letter2number
identifier_name
a1_300068688.py.py
delim and repeats 'n' times print(str(yoda)) #prints 'yoda' ######################## # Question 2 ######################## ''' creates a function called is_prime that takes one argument and check to see whether it is prime or not, if it is a prime the function return true if not it returns else''' def is...
print(str(4+0.3)) elif letter== 'A-': print(str(4-0.3)) if letter == 'B' or 'B-' or 'B+': #checks to see if it was an B, B+ or B- if letter == 'B': #assigns the corresponding number value to the letter and prints it print(str(3.0)) elif letter == 'B+...
elif letter == 'A+':
random_line_split
eventsGetUtils.js
' | 'trashed', modifiedSince?: number, includeDeletions?: boolean, }; export type StoreQuery = { id: string, storeId: string, includeTrashed: boolean, expandChildren: boolean, excludedIds: Array<string>, }; let mall; /** * # Stream Query Flow * 1. coerceStreamParam: * - null `streams` is chan...
async function applyDefaultsForRetrieval(context: MethodContext, params: GetEventsParams, result: Result, next: ApiCallback) { _.defaults(params, { streams: [{ any: ['*'] }], tags: null, types: null, fromTime: null, toTime: null, sortAscending: false, skip: null, limit: null, stat...
if (typeof input === 'string') return true; if (! Array.isArray(input)) return false; for (const item of input) { if (typeof item !== 'string') return false; } return true; } }
identifier_body
eventsGetUtils.js
' | 'trashed', modifiedSince?: number, includeDeletions?: boolean, }; export type StoreQuery = { id: string, storeId: string, includeTrashed: boolean, expandChildren: boolean, excludedIds: Array<string>, }; let mall; /** * # Stream Query Flow * 1. coerceStreamParam: * - null `streams` is chan...
if (! context.acceptStreamsQueryNonStringified) { if (isStringifiedJSON(params.streams)) { try { params.streams = parseStreamsParams(params.streams); } catch (e) { return next(e); } } else if (isStringOrArrayOfStrings(params.streams)) { // good, do nothing } else { ...
return next(); }
conditional_block
eventsGetUtils.js
{ params.streams = parseStreamsParams(params.streams); } catch (e) { return next(e); } } else if (isStringOrArrayOfStrings(params.streams)) { // good, do nothing } else { return next(errors.invalidRequestStructure('Invalid "streams" parameter. It should be an array of st...
/** * - Create a copy of the params per query
random_line_split
eventsGetUtils.js
' | 'trashed', modifiedSince?: number, includeDeletions?: boolean, }; export type StoreQuery = { id: string, storeId: string, includeTrashed: boolean, expandChildren: boolean, excludedIds: Array<string>, }; let mall; /** * # Stream Query Flow * 1. coerceStreamParam: * - null `streams` is chan...
ntext: MethodContext, params: GetEventsParams, result: Result, next: ApiCallback) { try { params.arrayOfStreamQueries = streamsQueryUtils.transformArrayOfStringsToStreamsQuery(params.streams); } catch (e) { return next(errors.invalidRequestStructure(e, params.streams)); } next(); } function validateStr...
nsformArrayOfStringsToStreamsQuery(co
identifier_name
imax_logger.py
settings['run_text'] = new text_input.on_change("value", text_input_handler) textsource = ColumnDataSource(data=dict(time = [],msg = [])) columns = [ TableColumn(field="time", title="Time"), TableColumn(field="msg", title="Msg", width = 600)] data_table = DataTable(source=textsource, columns=columns, width=600)...
(t, msg): global data_table print('time and msg: ', t, msg) new_data = dict(time=[t], msg=[msg],) textsource.stream(new_data, 20) #adding the value is a scrolloff lines data_table.update() import imax_0 def check_device_status(): global device_dict #used by startstop btn handler to determine if imax star...
text_update
identifier_name
imax_logger.py
settings['run_text'] = new text_input.on_change("value", text_input_handler) textsource = ColumnDataSource(data=dict(time = [],msg = [])) columns = [ TableColumn(field="time", title="Time"), TableColumn(field="msg", title="Msg", width = 600)] data_table = DataTable(source=textsource, columns=columns, width=600)...
print('device found') text_update(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), device_str) #device was found, engage device, get parameters and dictionaries device_dict, read_data, settings_dict, data_out_packet = imax_0.start_imax() print('Loading settings) settings['settings_dict'] = se...
device_str = imax_0.find_my_device() #returns msg which has "No" in it ,if device not found if "No" in device_str: if datetime.datetime.now()> futuretime: text_update(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), 'Could not find device; check device and connection.') return Fal...
conditional_block
imax_logger.py
DC_radio_group.on_click(DC_radio_handler) select_cells = Select(title = "No. of Cells", value ="4", options = [str(i) for i in range(1,13)]) def select_cells_handler(attr, old, new): settings['cells'] = new select_cells.on_change('value', select_cells_handler) #imax discharge/charge # of cycles; imax limit is 5 ...
settings['DC'] = new
identifier_body
imax_logger.py
#Create the header for page notice1 = Div(text="""The data input here are for logging identification and saving conditions, which are already manually chosen on the imax. They do not set or reset the imax.""", sizing_mode = "scale_width") select_battype = Select(title = "Battery Type",...
'settings_dict':settings_dict, 'device_dict':device_dict }
random_line_split
network.py
:param filter_shape: shape of the convolution filter. :param stride: stride for the convolution :param padding: padding mode, either 'VALID' or 'SAME' :return: shape of the output tensor as a plain list of integers """ filter_shape = tf.TensorShape(filter_shape).as_list() filter_out = filter_sh...
else: def conv_op(inputs, weight, name='generic_convolution'): if padding_type=='SAME': padded_output = [padded_shape[0]] + output_shape[-3:] else: padded_output = padded_shape with tf.name_scope(name): if padded_output[0]...
def conv_op(inputs, weight, name='generic_convolution'): with tf.name_scope(name): if padding_type=='VALID' and np.sum(padding) > 0: inputs = tf.pad(inputs, padding, name='padding') return tf.nn.conv2d(inputs, weight, strides, padding_type, name='convoluti...
conditional_block
network.py
:param filter_shape: shape of the convolution filter. :param stride: stride for the convolution :param padding: padding mode, either 'VALID' or 'SAME' :return: shape of the output tensor as a plain list of integers """ filter_shape = tf.TensorShape(filter_shape).as_list() filter_out = filter_sh...
(input_shape, output_shape, filter_shape): """ Based on the desired input, output and filter shape, figure out the correct 2D convolution configuration to use including the type (normal or full convolution), stride size, padding type/size :param input_shape: :param output_shape: :param filter_sh...
conv2d_config
identifier_name
network.py
[1:3]) return batch + output_shape.astype(np.int).tolist() + [filter_out] def conv2d_config(input_shape, output_shape, filter_shape): """ Based on the desired input, output and filter shape, figure out the correct 2D convolution configuration to use including the type (normal or full convolution), str...
if step > 0 and 'updates_collections' not in kwargs: kwargs['updates_collections'] = 'dump' output = layers.batch_norm(inputs, *args, **kwargs) if add_summary: if tag is None: tag = inputs.op.name.split('/')[-1] tag = 'batch_norm/' + tag tf.histogram_summary(tag, inpu...
identifier_body
network.py
:param filter_shape: shape of the convolution filter. :param stride: stride for the convolution :param padding: padding mode, either 'VALID' or 'SAME' :return: shape of the output tensor as a plain list of integers """ filter_shape = tf.TensorShape(filter_shape).as_list() filter_out = filter_sh...
output = tf.slice(output, [0, padding[1][0], padding[2][0], 0], [-1] + output_shape[-3:], name='cropping') return output return filter_shape, conv_op def normalize_weights(w, dims=(0,), bias=1e-5): """ L2 normalize weights of the...
batch_size = tf.shape(inputs)[0] padded_output = [batch_size] + padded_output[1:] output = tf.nn.conv2d_transpose(inputs, weight, padded_output, strides, padding_type, name='transpose_convolution') if padding_type=='VALID' and np.sum(padding) > 0:
random_line_split
display.go
(win *winInfo) setTitle(position int, total int, path string) { win.window.SetTitle(winTitle + " - " + strconv.Itoa(position) + "/" + strconv.Itoa(total) + " - " + filepath.Base(path)) } // Create the texture from text using TTF func (win *winInfo) renderText(text string) (*sdl.Texture, error) { surface, err := win...
if render { win.renderer.Clear() win.renderer.Copy(curImg().texture, &src, &dst) if window.displayInfo { window.displayPictureInfo() } //window.displayBar() win.renderer.Present() } // Update the window title win.setTitle(slide.current+1, len(slide.list), curImg().path) // Preload and free images ...
dst = sdl.Rect{X: int32(ww/2 - int32(iw)/2), Y: int32(wh/2 - int32(ih)/2), W: int32(iw), H: int32(ih)}
random_line_split
display.go
win *winInfo) setTitle(position int, total int, path string) { win.window.SetTitle(winTitle + " - " + strconv.Itoa(position) + "/" + strconv.Itoa(total) + " - " + filepath.Base(path)) } // Create the texture from text using TTF func (win *winInfo) renderText(text string) (*sdl.Texture, error) { surface, err := win.f...
(fullScreen bool, slideshow bool) int { var event sdl.Event var src, dst sdl.Rect var err error var flags uint32 = sdl.WINDOW_SHOWN | sdl.WINDOW_RESIZABLE | sdl.WINDOW_ALLOW_HIGHDPI // Load the font library if err := ttf.Init(); err != nil { logger.Warning("Unable to open font lib") } window.window, err = s...
MainLoop
identifier_name
display.go
win *winInfo) setTitle(position int, total int, path string) { win.window.SetTitle(winTitle + " - " + strconv.Itoa(position) + "/" + strconv.Itoa(total) + " - " + filepath.Base(path)) } // Create the texture from text using TTF func (win *winInfo) renderText(text string) (*sdl.Texture, error) { surface, err := win.f...
var window winInfo // MainLoop initializes the SDL package and run the main loop func MainLoop(fullScreen bool, slideshow bool) int { var event sdl.Event var src, dst sdl.Rect var err error var flags uint32 = sdl.WINDOW_SHOWN | sdl.WINDOW_RESIZABLE | sdl.WINDOW_ALLOW_HIGHDPI // Load the font library if err :=...
{ runtime.LockOSThread() // Video only if err := sdl.Init(sdl.INIT_VIDEO); err != nil { logger.Warning(err.Error()) } }
identifier_body
display.go
texture.Destroy() } else { logger.Warning("OMG") } } func resetImg(index int) { if slide.list[index].texture != nil { slide.list[index].texture.Destroy() slide.list[index].texture = nil } } func (win *winInfo) loadAndFreeAround() { p1 := utils.Mod(slide.current-1, len(slide.list)) p2 := utils.Mod(slide....
{ window.window.SetFullscreen(0) window.fullscreen = false }
conditional_block
w_reGeorgSocksProxy.py
SocksProtocolNotImplemented(Exception): pass class RemoteConnectionFailed(Exception): pass class session(Thread): def __init__(self, pSocket, connectString): Thread.__init__(self) self.pSocket = pSocket self.connectString = connectString o = urlparse(connectString) ...
# 'GET / HTTP/1.1\r\nHost: 192.168.2.1\r\nUser-Agent: curl/7.58.0\r\nAccept: */*\r\n\r\n' data = self.pSocket.recv(READBUFSIZE) if not data: break header = {"X-CMD": "FORWARD", "Cookie": self.cookie, "Content-Type": "application/octet-st...
t(1)
identifier_name
w_reGeorgSocksProxy.py
class SocksProtocolNotImplemented(Exception): pass class RemoteConnectionFailed(Exception): pass class session(Thread): def __init__(self, pSocket, connectString): Thread.__init__(self) self.pSocket = pSocket self.connectString = connectString o = urlparse(connectString) ...
elif response_header.get("X-ERROR"): logger.error(response_header.get("X-ERROR")) else: logger.error("[%s:%s] HTTP [%d]" % (target, targetPort, response.status_code)) return cookie def closeRemoteSession(self): header = {"X-CMD": "...
response_header = response.headers if response.status_code == 200 and response_header.get("X-STATUS") == "OK": cookie = response_header.get("Set-Cookie") logger.info("[%s:%s] HTTP [200]: cookie [%s]" % (target, targetPort, cookie))
random_line_split
w_reGeorgSocksProxy.py
SocksProtocolNotImplemented(Exception): pass class RemoteConnectionFailed(Exception): pass class session(Thread): def __init__(self, pSocket, connectString): Thread.__init__(self) self.pSocket = pSocket self.connectString = connectString o = urlparse(connectString) ...
target, self.targetPort, response.status_code)) break # transferLog.info("[%s:%d] >>>> [%d]" % (self.target, self.port, len(data))) except timeout: continue except Exception, ex: raise ex self.closeRemoteSession() ...
getPort, response.status_code, status, response_header.get("x-error"))) break else: logger.error( "[%s:%d] HTTP [%d]: Shutting down" % (self.
conditional_block
w_reGeorgSocksProxy.py
80 self.httpScheme = o.scheme self.httpHost = o.netloc.split(":")[0] self.httpPath = o.path self.cookie = None def parseSocks5(self, sock): logger.debug("SocksVersion5 detected") # 02:00 nmethods, methods = (sock.recv(1), sock.recv(1)) # 05:00 ...
r.start() w = Thread(target=self.writer, args=()) w.start() w.join() r.join() except Exception, e: # 报错关闭连接 logger.error(format_exc()) self.closeRemoteSession() self.pSocket.close() def askgeorg(url...
identifier_body
activity_heartbeat_manager.rs
<JoinHandle<()>>>, } /// Used to supply heartbeat details to the heartbeat processor, which periodically sends them to /// the server. struct ActivityHeartbeatProcessorHandle { heartbeat_tx: Sender<Vec<common::Payload>>, join_handle: JoinHandle<()>, } /// Heartbeat processor, that aggregates and periodically ...
if !self.shutting_down.load(Ordering::Relaxed) { self.events .send(LifecycleEvent::Shutdown) .expect("should be able to send shutdown event"); self.shutting_down.store(true, Ordering::Relaxed); } let mut handle = self.join_handle.lock().awa...
/// processors to terminate gracefully. pub async fn shutdown(&self) { // If shutdown was called multiple times, shutdown signal has been sent already and consumer // might have been dropped already, meaning that sending to the channel may fail. // All we need to do is to simply await on...
random_line_split
activity_heartbeat_manager.rs
_self)] /// Creates a new instance of an activity heartbeat manager and returns a handle to the user, /// which allows to send new heartbeats and initiate the shutdown. pub fn new(sg: Arc<SG>) -> ActivityHeartbeatManagerHandle { let (shutdown_tx, shutdown_rx) = channel(false); let (events_tx...
{ let mut mock_gateway = MockServerGatewayApis::new(); mock_gateway .expect_record_activity_heartbeat() .returning(|_, _| Ok(RecordActivityTaskHeartbeatResponse::default())) .times(0); let hm = ActivityHeartbeatManager::new(Arc::new(mock_gateway)); hm....
identifier_body
activity_heartbeat_manager.rs
JoinHandle<()>>>, } /// Used to supply heartbeat details to the heartbeat processor, which periodically sends them to /// the server. struct ActivityHeartbeatProcessorHandle { heartbeat_tx: Sender<Vec<common::Payload>>, join_handle: JoinHandle<()>, } /// Heartbeat processor, that aggregates and periodically s...
Err(e) => { warn!("Error when recording heartbeat: {:?}", e) } } } } #[cfg(test)] mod test { use super::*; use crate::pollers::MockServerGatewayApis; use crate::protos::coresdk::common::Payload; use crate::protos::temporal::api::workflowservice::v1::...
{ self.cancels_tx .send(self.task_token.clone()) .expect("Receive half of heartbeat cancels not blocked"); }
conditional_block
activity_heartbeat_manager.rs
JoinHandle<()>>>, } /// Used to supply heartbeat details to the heartbeat processor, which periodically sends them to /// the server. struct ActivityHeartbeatProcessorHandle { heartbeat_tx: Sender<Vec<common::Payload>>, join_handle: JoinHandle<()>, } /// Heartbeat processor, that aggregates and periodically s...
(&mut self, heartbeat: ValidActivityHeartbeat) { match self.heartbeat_processors.get(&heartbeat.task_token) { Some(handle) => { handle .heartbeat_tx .send(heartbeat.details) .expect("heartbeat channel can't be dropped if we ...
record
identifier_name
msg_test.go
Price: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(0), gasPrice: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(-1), gasPrice: sdk.NewInt(100000), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt(-1), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt...
require.Equal(t, addr1, signer) require.NotEqual(t, addr2, signer) // msg atomic load signer, err = msg.VerifySig(chainID) require.NoError(t, err) require.Equal(t, addr1, signer) signers := msg.GetSigners() require.Equal(t, 1, len(signers)) require.True(t, addrSDKAddr1.Equals(signers[0])) // zero chainID ...
{ chainID, zeroChainID := big.NewInt(3), big.NewInt(0) priv1, _ := ethsecp256k1.GenerateKey() priv2, _ := ethsecp256k1.GenerateKey() addr1 := ethcmn.BytesToAddress(priv1.PubKey().Address().Bytes()) trimed := strings.TrimPrefix(addr1.Hex(), "0x") fmt.Printf("%s\n", trimed) addrSDKAddr1, err := sdk.AccAddressFro...
identifier_body
msg_test.go
Price: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(0), gasPrice: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(-1), gasPrice: sdk.NewInt(100000), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt(-1), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt...
(t *testing.T) { chainID := big.NewInt(3) priv, _ := ethsecp256k1.GenerateKey() addr := ethcmn.BytesToAddress(priv.PubKey().Address().Bytes()) msg := NewMsgEthereumTx(0, &addr, nil, 100000, nil, []byte("test")) err := msg.Sign(chainID, priv.ToECDSA()) require.Nil(t, err) require.True(t,
TestMsgEthereumTx_ChainID
identifier_name
msg_test.go
Price: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(0), gasPrice: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(-1), gasPrice: sdk.NewInt(100000), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt(-1), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt...
} func TestMsgEthereumTxRLPSignBytes(t *testing.T) { addr := ethcmn.BytesToAddress([]byte("test_address")) chainID := big.NewInt(3) msg := NewMsgEthereumTx(0, &addr, nil, 100000, nil, []byte("test")) hash := msg.RLPSignBytes(chainID) require.Equal(t, "5BD30E35AD27449390B14C91E6BCFDCAADF8FE44EF33680E3BC200FC0DC0...
{ msg := NewMsgEthereumTx(0, nil, tc.amount, 0, tc.gasPrice, nil) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "valid test %d failed: %s", i, tc.msg) } else { require.NotNil(t, msg.ValidateBasic(), "invalid test %d passed: %s", i, tc.msg) } }
conditional_block
msg_test.go
Price: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(0), gasPrice: sdk.NewInt(100000), expectPass: true}, {amount: sdk.NewInt(-1), gasPrice: sdk.NewInt(100000), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt(-1), expectPass: false}, {amount: sdk.NewInt(100), gasPrice: sdk.NewInt...
} for i, tc := range testCases { msg := NewMsgEthereumTx(0, nil, tc.amount, 0, tc.gasPrice, nil) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "valid test %d failed: %s", i, tc.msg) } else { require.NotNil(t, msg.ValidateBasic(), "invalid test %d passed: %s", i, tc.msg) } } } func TestMsgEt...
random_line_split
process_vm.rs
Drop for ProcessVM { fn drop(&mut self) { let mut mem_chunks = self.mem_chunks.write().unwrap(); // There are two cases when this drop is called: // (1) Process exits normally and in the end, drop process VM // (2) During creating process stage, process VM is ready but there are som...
{ return USER_SPACE_VM_MANAGER.msync(addr, size); }
identifier_body
process_vm.rs
elf_layout.extend(&segment_layout); elf_layout }) }) .collect(); // Make heap and stack 16-byte aligned let other_layouts = vec![ VMLayout::new(heap_size, 16)?, VMLayout::new(stack_size, ...
let segment_size = (segment.p_vaddr + segment.p_memsz) as usize; let segment_align = segment.p_align as usize; let segment_layout = VMLayout::new(segment_size, segment_align).unwrap();
random_line_split
process_vm.rs
{ let vm_option = VMMapOptionsBuilder::default() .size(elf_layout.size()) .align(elf_layout.align()) .perms(VMPerms::ALL) // set it to read | write | exec for simplicity .initializer(VMInitializer::ElfSpecific { ...
(&mut self) { let mut mem_chunks = self.mem_chunks.write().unwrap(); // There are two cases when this drop is called: // (1) Process exits normally and in the end, drop process VM // (2) During creating process stage, process VM is ready but there are some other errors when creating the ...
drop
identifier_name
KR_256_5x5_32_Team.py
2) def
(): time_str = dt.now().strftime('%Y-%m-%d-%H-%M-%S') experiment_id = 'base_{}'.format(time_str) return experiment_id def scheduler(epoch): if epoch == 150: K.set_value(model.optimizer.lr, 0.00014339) return K.get_value(model.optimizer.lr) def strong_aug(p=1): return Compose([ ...
get_experiment_id
identifier_name
KR_256_5x5_32_Team.py
def Maxout1(x): return tf.contrib.layers.maxout(x, 512) def Maxout2(x): return tf.contrib.layers.maxout(x, 512) def get_experiment_id(): time_str = dt.now().strftime('%Y-%m-%d-%H-%M-%S') experiment_id = 'base_{}'.format(time_str) return experiment_id def scheduler(epoch): if epoch == 150...
print('Random seeds initialized') random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) tf.set_random_seed(seed)
identifier_body
KR_256_5x5_32_Team.py
same", activation='linear', kernel_initializer=Orthogonal(gain=1.0), name='conv2d_9',bias_initializer=Constant(value=0.05),kernel_regularizer=regularizers.l2(0.0005))) model.add(BatchNormalization(name='batch_normalization_11')) model.add(LeakyReLU(alpha=0.01,name='leaky_re_lu_12')) model.add(Conv2D(...
plt.xlabel('epoch')
random_line_split
KR_256_5x5_32_Team.py
0014339) return K.get_value(model.optimizer.lr) def strong_aug(p=1): return Compose([ RandomRotate90(), Flip(), Transpose(), OneOf([ IAAAdditiveGaussianNoise(), GaussNoise(), ], p=0.2), OneOf([ MotionBlur(p=0.2), M...
try: layer.set_weights( pre_256_model.get_layer(name=layer.name).get_weights()) print("Succesfully transfered weights for layer {}".format(layer.name)) except: print("Could not transfer weights for layer {}".format(layer.name))
conditional_block
mongodb.go
StringIDToObjID(parsedFilter["_id"].(string)) if err != nil { /* log */ goto Done } } itemsMap, err = mh.getDocs(dbname,collectionname,parsedFilter) if err != nil { //log } Done: return itemsMap, err } func (mh *mongoDBHandler) InsertOne(dbname string, collectionname string, doc inte...
containsDup := false var errMsg string if v, ok := err.(mongo.WriteException); ok { var msgs []string for idx, werr:=range v.WriteErrors { //log stuff before anything gets altered fmt.Println("err.WriteErrors[",idx,"].Index=",werr.Index) fmt.Println("err.WriteErrors[",idx,"].Code=",werr.Code) ...
identifier_body
mongodb.go
updatedAt" : now, }) } initSysIndexes(mh.MongoProjectsDB,sysProjIndexModels) initSysIndexes(mh.MongoProjectsDB,userIndexModels) initSysIndexes(mh.MongoClient.Database(c.UsersDBName).Collection(c.UsersDBAuthCollection),authIndexModels) } func (mh *mongoDBHandler) initSystemUsers() ([]map[string]interface...
}
random_line_split
mongodb.go
:= mh.GetDocs(c.SysDBName, appConfig.DBConfig.MongoConfig.ProjectsColl, bson.M{"name":"trion"}) if err != nil { if _, ok := err.(c.NotFoundError); !ok
fmt.Println("To był not found, len(itemsMap)",len(itemsMap)) } now := time.Now() if len(itemsMap) == 0 { fmt.Println("Inserting Trion...") mh.InsertOne(c.SysDBName, appConfig.DBConfig.MongoConfig.ProjectsColl, bson.M{"name" : "trion", "type" : "system", "schema_rev": "1", "owner":u...
{ log.Fatal(err) }
conditional_block
mongodb.go
:= mh.GetDocs(c.SysDBName, appConfig.DBConfig.MongoConfig.ProjectsColl, bson.M{"name":"trion"}) if err != nil { if _, ok := err.(c.NotFoundError); !ok { log.Fatal(err) } fmt.Println("To był not found, len(itemsMap)",len(itemsMap)) } now := time.Now() if len(itemsMap) == 0 { fmt.Println("Insert...
) ([]map[string]interface{}, error) { var err error var sysAdmin m.UserDBModel var now time.Time var hashedPassword []byte // check if default system admin exists itemsMap, err := mh.GetDocs(c.UsersDBName, c.UsersDBUsersCollection, bson.M{"login":"sysadmin"}) if err !=nil { if _, ok := err.(c.NotFound...
nitSystemUsers(
identifier_name
startnode.go
ODEID string) { var ( CannotRead = make(chan bool, 1) GetName = make(chan bool, 1) stdin io.Writer stdout io.Reader ) for { AdminData, err := utils.ExtractPayload(*connToAdmin, AgentStatus.AESKey, NODEID, false) if err != nil { AdminOffline(reConn, monitor, listenPort, passive) go SendI...
} } //管理admin端下发的数据 func HandleConnFromAdmin(connToAdmin *net.Conn, monitor, listenPort, reConn string, passive bool, N
identifier_body
startnode.go
licenum] = AdminData.Info FileDataMap.Unlock() case "FORWARD": TryForward(AdminData.Info, AdminData.Clientid) case "FORWARDDATA": ForwardConnMap.RLock() if _, ok := ForwardConnMap.Payload[AdminData.Clientid]; ok { PortFowardMap.Lock() if _, ok := PortFowardMap.Payload[AdminData.C...
random_line_split
startnode.go
HandleConnFromAdmin(connToAdmin *net.Conn, monitor, listenPort, reConn string, passive bool, NODEID string) { var ( CannotRead = make(chan bool, 1) GetName = make(chan bool, 1) stdin io.Writer stdout io.Reader ) for { AdminData, err := utils.ExtractPayload(*connToAdmin, AgentStatus.AESKey, NOD...
tor, listenPort, passive) go SendInfo(NODEID) //重连后发送自身信息 go SendNote(NODEID) //重连后发送admin设置的备忘 continue } if AdminData.NodeId == NODEID { switch AdminData.Type { case "DATA": switch AdminData.Command { case "SOCKSDATA": SocksDataChanMap.RLock() if _, ok := SocksDataChanMap.Payload[...
ffline(reConn, moni
identifier_name
startnode.go
func HandleConnFromAdmin(connToAdmin *net.Conn, monitor, listenPort, reConn string, passive bool, NODEID string) { var ( CannotRead = make(chan bool, 1) GetName = make(chan bool, 1) stdin io.Writer stdout io.Reader ) for { AdminData, err := utils.ExtractPayload(*connToAdmin, AgentStatus.AESKey,...
respComm, _ := utils.ConstructPayload(utils.AdminId, "", "COMMAND", "FILESIZECONFIRM", " ", " ", 0, NODEID, AgentStatus.AESKey, false) ProxyChan.ProxyChanToUpperNode <- respComm share.File.ReceiveFileSize <- true case "FILESLICENUM": share.File.TotalSilceNum, _ = strconv.Atoi(AdminData.Info) r...
aMap, CannotRead, UploadFile, AgentStatus.AESKey, false, NODEID) } case "FILESIZE": filesize, _ := strconv.ParseInt(AdminData.Info, 10, 64) share.File.FileSize = filesize
conditional_block
console.go
Bright Yellow bg[104] = color{85, 85, 255} // Bright Blue bg[105] = color{255, 85, 255} // Bright Magenta bg[106] = color{85, 255, 255} // Bright Cyan bg[107] = color{255, 255, 255} // Bright White c, ok := bg[i] return c, ok } func New() *Console { c := &Console{} c.bgColor, _ = colorParserBg(40) c.fgC...
{ fmt.Println(err) }
conditional_block
console.go
255, 255} // Bright White c, ok := fg[i] return c, ok } func colorParserBg(i int) (color, bool) { bg := make(map[int]color, 16) bg[40] = color{0, 0, 0} // Black bg[41] = color{170, 0, 0} // Red bg[42] = color{0, 170, 0} // Green bg[43] = color{170, 85, 0} // Yellow bg[44] = color{0, 0, ...
c.fgColor, _ = colorParserFg(37) c.width = 80 * 9 c.height = 25 * 16 c.scale = 1.5 c.title = "term" c.cursorSetBlink = true c.img = image.NewRGBA(image.Rect(0, 0, c.width, c.height)) c.tmpScreen = ebiten.NewImage(c.width, c.height) c.font.bitmap = bitmap c.font.height = 16 c.font.width = 9 c.clear() re...
func New() *Console { c := &Console{} c.bgColor, _ = colorParserBg(40)
random_line_split
console.go
255, 255} // Bright White c, ok := fg[i] return c, ok } func colorParserBg(i int) (color, bool) { bg := make(map[int]color, 16) bg[40] = color{0, 0, 0} // Black bg[41] = color{170, 0, 0} // Red bg[42] = color{0, 170, 0} // Green bg[43] = color{170, 85, 0} // Yellow bg[44] = color{0, 0, 1...
(charID int) { c.videoTextMemory[c.cursor].fgColor = c.fgColor c.videoTextMemory[c.cursor].bgColor = c.bgColor c.videoTextMemory[c.cursor].charID = charID c.cursor++ c.cursorLimit() } func (c *Console) cursorLimit() { if c.cursor < 0 { c.cursor = 0 return } columns := 80 rows := 25 for c.cursor >= rows*c...
put
identifier_name
console.go
++ c.cursorLimit() } func (c *Console) cursorLimit() { if c.cursor < 0 { c.cursor = 0 return } columns := 80 rows := 25 for c.cursor >= rows*columns { c.cursor -= columns c.moveUp() } } func (c *Console) Print(msg string) { columns := 80 parseMode := false csi := false s := "" for i := 0; i < len...
{ if c.cursorSetBlink { if c.cursorBlinkTimer < 15 { fgColor, bgColor = bgColor, fgColor } c.drawChar(index, fgColor, bgColor, x, y) c.cursorBlinkTimer++ if c.cursorBlinkTimer > 30 { c.cursorBlinkTimer = 0 } return } c.drawChar(index, bgColor, fgColor, x, y) }
identifier_body
ledger_cleanup_service.rs
Handle}; use std::time::Duration; // - To try and keep the RocksDB size under 400GB: // Seeing about 1600b/shred, using 2000b/shred for margin, so 200m shreds can be stored in 400gb. // at 5k shreds/slot at 50k tps, this is 500k slots (~5 hours). // At idle, 60 shreds/slot this is about 4m slots (18 days) // Thi...
max_ledger_shreds, shreds.len(), total_shreds, iterate_time ); if (total_shreds as u64) < max_ledger_shreds { return (0, 0, 0); } let mut cur_shreds = 0; let mut lowest_slot_to_clean = shreds[0].0; for (slot, num...
{ let mut shreds = Vec::new(); let mut iterate_time = Measure::start("iterate_time"); let mut total_shreds = 0; let mut first_slot = 0; for (i, (slot, meta)) in blockstore.slot_meta_iterator(0).unwrap().enumerate() { if i == 0 { first_slot = slot; ...
identifier_body
ledger_cleanup_service.rs
Handle}; use std::time::Duration; // - To try and keep the RocksDB size under 400GB: // Seeing about 1600b/shred, using 2000b/shred for margin, so 200m shreds can be stored in 400gb. // at 5k shreds/slot at 50k tps, this is 500k slots (~5 hours). // At idle, 60 shreds/slot this is about 4m slots (18 days) // Thi...
() { solana_logger::setup(); let blockstore_path = get_tmp_ledger_path!(); let blockstore = Blockstore::open(&blockstore_path).unwrap(); let (shreds, _) = make_many_slot_entries(0, 50, 5); blockstore.insert_shreds(shreds, None, false).unwrap(); let blockstore = Arc::new(b...
test_cleanup
identifier_name
ledger_cleanup_service.rs
Handle}; use std::time::Duration; // - To try and keep the RocksDB size under 400GB: // Seeing about 1600b/shred, using 2000b/shred for margin, so 200m shreds can be stored in 400gb. // at 5k shreds/slot at 50k tps, this is 500k slots (~5 hours). // At idle, 60 shreds/slot this is about 4m slots (18 days) // Thi...
//send a signal to kill all but 5 shreds, which will be in the newest slots let mut last_purge_slot = 0; sender.send(50).unwrap(); LedgerCleanupService::cleanup_ledger(&receiver, &blockstore, 5, &mut last_purge_slot, 10) .unwrap(); //check that 0-40 don't exist ...
let blockstore = Arc::new(blockstore); let (sender, receiver) = channel();
random_line_split