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
flap.py
# Flap # KidsCanCode 2014 # Flappy bird in pygame # For educational purposes only # Art from http://lanica.co/flappy-clone/ # Music from opengameart.org (http://opengameart.org/content/cheerful-1-choro-bavario-happy-loop) # Copyright 2009 MSTR "Choro Bavario" <http://www.jamendo.com/en/artist/349242/mstr> # Copyrig...
def draw_ground(): # draw the ground tiles, moving at the same speed as pipes for image in ground_list: image.x -= PIPE_SPEED if image.right <= 0: # if the image has completely moved off the screen, move it to the right image.left = 2 * ground.get_width() + image.right ...
background_rect.bottom = HEIGHT + 20 background_rect.left = 0 screen.blit(background, background_rect) if background_rect.width < WIDTH: background_rect.left = background_rect.width screen.blit(background, background_rect)
identifier_body
flap.py
# Flap # KidsCanCode 2014 # Flappy bird in pygame # For educational purposes only # Art from http://lanica.co/flappy-clone/ # Music from opengameart.org (http://opengameart.org/content/cheerful-1-choro-bavario-happy-loop) # Copyright 2009 MSTR "Choro Bavario" <http://www.jamendo.com/en/artist/349242/mstr> # Copyrig...
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
# Flap # KidsCanCode 2014 # Flappy bird in pygame # For educational purposes only # Art from http://lanica.co/flappy-clone/ # Music from opengameart.org (http://opengameart.org/content/cheerful-1-choro-bavario-happy-loop) # Copyright 2009 MSTR "Choro Bavario" <http://www.jamendo.com/en/artist/349242/mstr> # Copyrig...
(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
# Flap # KidsCanCode 2014 # Flappy bird in pygame # For educational purposes only # Art from http://lanica.co/flappy-clone/ # Music from opengameart.org (http://opengameart.org/content/cheerful-1-choro-bavario-happy-loop) # Copyright 2009 MSTR "Choro Bavario" <http://www.jamendo.com/en/artist/349242/mstr> # Copyrig...
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
import os import platform import sys import requests from metaflow import util from metaflow.decorators import StepDecorator from metaflow.exception import MetaflowException from metaflow.metadata import MetaDatum from metaflow.metadata.util import sync_local_metadata_to_datastore from metaflow.metaflow_config import...
# 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
import os import platform import sys import requests from metaflow import util from metaflow.decorators import StepDecorator from metaflow.exception import MetaflowException from metaflow.metadata import MetaDatum from metaflow.metadata.util import sync_local_metadata_to_datastore from metaflow.metaflow_config import...
meta["kubernetes-pod-name"] = os.environ["METAFLOW_KUBERNETES_POD_NAME"] meta["kubernetes-pod-namespace"] = os.environ[ "METAFLOW_KUBERNETES_POD_NAMESPACE" ] meta["kubernetes-pod-id"] = os.environ["METAFLOW_KUBERNETES_POD_ID"] meta["kubernetes-...
# variable. if "METAFLOW_KUBERNETES_WORKLOAD" in os.environ: meta = {}
random_line_split
kubernetes_decorator.py
import os import platform import sys import requests from metaflow import util from metaflow.decorators import StepDecorator from metaflow.exception import MetaflowException from metaflow.metadata import MetaDatum from metaflow.metadata.util import sync_local_metadata_to_datastore from metaflow.metaflow_config import...
(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
import os import platform import sys import requests from metaflow import util from metaflow.decorators import StepDecorator from metaflow.exception import MetaflowException from metaflow.metadata import MetaDatum from metaflow.metadata.util import sync_local_metadata_to_datastore from metaflow.metaflow_config import...
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
/** * Copyright 2009 Google 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
() { 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
/** * Copyright 2009 Google 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
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
/** * Copyright 2009 Google 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
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
/** * Copyright 2009 Google 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
_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
## For Cam Control ## from instrumental import instrument, u import matplotlib.animation as animation from matplotlib.widgets import Button, Slider from scipy.optimize import curve_fit ## Other ## import time import matplotlib.pyplot as plt import numpy as np from math import sqrt MAX_EXP = 150 def stabilize_intens...
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
## For Cam Control ## from instrumental import instrument, u import matplotlib.animation as animation from matplotlib.widgets import Button, Slider from scipy.optimize import curve_fit ## Other ## import time import matplotlib.pyplot as plt import numpy as np from math import sqrt MAX_EXP = 150 def stabilize_intens...
(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
## For Cam Control ## from instrumental import instrument, u import matplotlib.animation as animation from matplotlib.widgets import Button, Slider from scipy.optimize import curve_fit ## Other ## import time import matplotlib.pyplot as plt import numpy as np from math import sqrt MAX_EXP = 150 def stabilize_intens...
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
## For Cam Control ## from instrumental import instrument, u import matplotlib.animation as animation from matplotlib.widgets import Button, Slider from scipy.optimize import curve_fit ## Other ## import time import matplotlib.pyplot as plt import numpy as np from math import sqrt MAX_EXP = 150 def stabilize_intens...
def _run_cam(which_cam, verbose=False): names = ['ThorCam', 'ChamberCam'] # False, True ## https://instrumental-lib.readthedocs.io/en/stable/uc480-cameras.html ## cam = instrument(names[which_cam]) ## Cam Live Stream ## cam.start_live_video(framerate=10 * u.hertz) exp_t = cam._get_exposure...
""" 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
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package device import ( "bytes" "context" "crypto/tls" "encoding/json" "encoding/pem" "fmt" "net/http" "strings" "github.com/duo-labs/webauthn.io/session" "github.com/duo-labs/webauthn/protocol" "github.co...
displayName := strings.Split(fmt.Sprintf("%v", userSub), "@")[0] userData.FamilyName = displayName return userData, true } func (o *Operation) saveCookie(w http.ResponseWriter, r *http.Request, usr, cookieName string) { logger.Debugf("device cookie begin %s", usr) deviceSession, err := o.store.cookies.Open(r...
{ common.WriteErrorResponsef(w, logger, http.StatusInternalServerError, "failed to get user data %s:", err.Error()) return nil, false }
conditional_block
operations.go
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package device import ( "bytes" "context" "crypto/tls" "encoding/json" "encoding/pem" "fmt" "net/http" "strings" "github.com/duo-labs/webauthn.io/session" "github.com/duo-labs/webauthn/protocol" "github.co...
(w http.ResponseWriter, r *http.Request, usr, cookieName string) { logger.Debugf("device cookie begin %s", usr) deviceSession, err := o.store.cookies.Open(r) if err != nil { common.WriteErrorResponsef(w, logger, http.StatusInternalServerError, "failed to read user session cookie: %s", err.Error()) return }...
saveCookie
identifier_name
operations.go
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package device import ( "bytes" "context" "crypto/tls" "encoding/json" "encoding/pem" "fmt" "net/http" "strings" "github.com/duo-labs/webauthn.io/session" "github.com/duo-labs/webauthn/protocol" "github.co...
// GetRESTHandlers get all controller API handler available for this service. func (o *Operation) GetRESTHandlers() []common.Handler { return []common.Handler{ common.NewHTTPHandler(registerBeginPath, http.MethodGet, o.beginRegistration), common.NewHTTPHandler(registerFinishPath, http.MethodPost, o.finishRegistr...
{ 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
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package device import ( "bytes" "context" "crypto/tls" "encoding/json" "encoding/pem" "fmt" "net/http" "strings" "github.com/duo-labs/webauthn.io/session" "github.com/duo-labs/webauthn/protocol" "github.co...
}, } 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
package main import ( "encoding/json" "flag" "fmt" "image" "image/color" "image/draw" "image/jpeg" "log" "math" "os" "path/filepath" "strconv" "strings" "time" "github.com/google/uuid" "github.com/sarjsheff/hiklib" ffmpeg "github.com/u2takey/ffmpeg-go" tb "gopkg.in/tucnak/telebot.v2" ) var ipParam ...
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
package main import ( "encoding/json" "flag" "fmt" "image" "image/color" "image/draw" "image/jpeg" "log" "math" "os" "path/filepath" "strconv" "strings" "time" "github.com/google/uuid" "github.com/sarjsheff/hiklib" ffmpeg "github.com/u2takey/ffmpeg-go" tb "gopkg.in/tucnak/telebot.v2" ) var ipParam ...
() 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
package main import ( "encoding/json" "flag" "fmt" "image" "image/color" "image/draw" "image/jpeg" "log" "math" "os" "path/filepath" "strconv" "strings" "time" "github.com/google/uuid" "github.com/sarjsheff/hiklib" ffmpeg "github.com/u2takey/ffmpeg-go" tb "gopkg.in/tucnak/telebot.v2" ) var ipParam ...
if _, err := os.Stat(fname); os.IsNotExist(err) { opts := ffmpeg.KwArgs{ "format": "mp4", //"fs": strconv.Itoa(*previewsizeParam), "vcodec": "copy", //"libx264", "preset": "ultrafast", "acodec": "none", "movflags": "+faststart", } // C.HSave...
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
package main import ( "encoding/json" "flag" "fmt" "image" "image/color" "image/draw" "image/jpeg" "log" "math" "os" "path/filepath" "strconv" "strings" "time" "github.com/google/uuid" "github.com/sarjsheff/hiklib" ffmpeg "github.com/u2takey/ffmpeg-go" tb "gopkg.in/tucnak/telebot.v2" ) var ipParam ...
func main() { log.Println("HIKBOT v0.0.4") flag.Parse() if *ipParam == "" || *userParam == "" || *passParam == "" || *adminParam == 0 || *tkeyParam == "" { flag.PrintDefaults() } else { motions = make(chan hiklib.AlarmItem, 100) log.Printf("%s\n", hiklib.HikVersion()) if Login() > -1 { defer hiklib.HikL...
// 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
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- # Copyright (c) 2022 Nicolas Iooss # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights...
for url in fields[2:]: # Check URL, and only keep the first valid key with urllib.request.urlopen(url) as response: armored_key = response.read() try: new_raw_key = unarmor_gpg(armored_key) except Value...
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
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- # Copyright (c) 2022 Nicolas Iooss # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights...
() -> 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
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- # Copyright (c) 2022 Nicolas Iooss # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights...
if __name__ == "__main__": self_check() sync_keys(KEYS_PATH)
"""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
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- # Copyright (c) 2022 Nicolas Iooss # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights...
new_line += " " + " ".join(fields[2:]) file_lines.append(new_line) # Refresh the file with keys_path.open("w") as fout: print("\n".join(file_lines), file=fout) if __name__ == "__main__": self_check() sync_keys(KEYS_PATH)
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
use itertools::izip; use log::{info, warn, Level}; use sarekt::{ self, error::{SarektError, SarektResult}, image_data::ImageData, renderer::{ buffers_and_images::{ BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode, }, config::{Config, MsaaConfig}, drawabl...
for geo in obj_set.objects[0].geometry.iter() { // For every set of geometry (regardless of material for now). for shape in geo.shapes.iter() { // For every face/shape in the set of geometry. match shape.primitive { obj::obj::Primitive::Triangle(x, y, z) => { for &vert in [x, y, ...
random_line_split
10_msaa.rs
use itertools::izip; use log::{info, warn, Level}; use sarekt::{ self, error::{SarektError, SarektResult}, image_data::ImageData, renderer::{ buffers_and_images::{ BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode, }, config::{Config, MsaaConfig}, drawabl...
_ => warn!("Unsupported primitive!"), } } } info!( "Vertices/indices in model: {}, {}", vertices.len(), indices.len() ); (vertices, Some(indices)) } /// Returns (vertices, vertex_indicies, texture_coordinate indices) fn load_glb_model(gltf_file_path: &str) -> (Vec<DefaultForward...
{ 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
use itertools::izip; use log::{info, warn, Level}; use sarekt::{ self, error::{SarektError, SarektResult}, image_data::ImageData, renderer::{ buffers_and_images::{ BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode, }, config::{Config, MsaaConfig}, drawabl...
() { 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
use itertools::izip; use log::{info, warn, Level}; use sarekt::{ self, error::{SarektError, SarektResult}, image_data::ImageData, renderer::{ buffers_and_images::{ BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode, }, config::{Config, MsaaConfig}, drawabl...
/// Handles all winit window specific events. fn main_loop_window_event( event: &WindowEvent, _id: &WindowId, control_flow: &mut winit::event_loop::ControlFlow, renderer: &mut VulkanRenderer, ar: &mut f32, ) -> SarektResult<()> { match event { WindowEvent::CloseRequested => { // When the window system...
{ 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
import { Injectable, Injector, ReflectiveInjector } from 'injection-js'; import BullQueue = require('bull'); import { Queue, Job, QueueOptions } from 'bull'; // import { deepstreamQuarantine } from 'deepstream.io-client-js'; import { LoggerService } from '../service/LogService'; import { ConfigService } from '../serv...
millisecond) }) } catch (ex) { return Promise.reject(ex); } } }
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
import { Injectable, Injector, ReflectiveInjector } from 'injection-js'; import BullQueue = require('bull'); import { Queue, Job, QueueOptions } from 'bull'; // import { deepstreamQuarantine } from 'deepstream.io-client-js'; import { LoggerService } from '../service/LogService'; import { ConfigService } from '../serv...
tch (queue.queue.strategy) { case 'round-robin': { data = await this.roundRobinStrategy({ members, queueNumber, tenantId ...
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
import { Injectable, Injector, ReflectiveInjector } from 'injection-js'; import BullQueue = require('bull'); import { Queue, Job, QueueOptions } from 'bull'; // import { deepstreamQuarantine } from 'deepstream.io-client-js'; import { LoggerService } from '../service/LogService'; import { ConfigService } from '../serv...
} } async lockMember({ tenantId, member }) { try { const key = `esl::queue::member::locked::${tenantId}::${member}`; //await redisQC.setnx(key, member); // await redisQC.expire(key, 60); const ttl = 3 * 1000; const lock = await this.redlo...
.reject(ex);
identifier_name
QueueWorkerService.ts
import { Injectable, Injector, ReflectiveInjector } from 'injection-js'; import BullQueue = require('bull'); import { Queue, Job, QueueOptions } from 'bull'; // import { deepstreamQuarantine } from 'deepstream.io-client-js'; import { LoggerService } from '../service/LogService'; import { ConfigService } from '../serv...
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
//! # Implementing differentiable operations //! //! Many of well-known ops are pre-defined in [crate::tensor_ops], but you can also //! implement custom ops by hand. //! See also [crate::tensor::TensorBuilder]. //! //! ``` //! use ndarray; //! use autograd as ag; //! use autograd::op::OpError; //! use autograd::tensor...
// Call Op::grad and return `gxs` pub(crate) fn compute_input_grads(mut self) -> SmallVec<Option<Tensor<'graph, T>>> { let id = self.y.id; // steal op let stolen = self.graph().access_inner_mut(id).op.take().unwrap(); // call Op::grad stolen.grad(&mut self); /...
{ GradientContext { gy, y, graph, gxs: SmallVec::new(), } }
identifier_body
op.rs
//! # Implementing differentiable operations //! //! Many of well-known ops are pre-defined in [crate::tensor_ops], but you can also //! implement custom ops by hand. //! See also [crate::tensor::TensorBuilder]. //! //! ``` //! use ndarray; //! use autograd as ag; //! use autograd::op::OpError; //! use autograd::tensor...
{ 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
//! # Implementing differentiable operations //! //! Many of well-known ops are pre-defined in [crate::tensor_ops], but you can also //! implement custom ops by hand. //! See also [crate::tensor::TensorBuilder]. //! //! ``` //! use ndarray; //! use autograd as ag; //! use autograd::op::OpError; //! use autograd::tensor...
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
de.sc.portal.env.dlg.mongo = {}; de.sc.portal.env.dlg.mongo.mu = "104P116D116O112Q58H47L47M115T101E110H45Y115L111D97Y45I115S97C108R101V115J58W115I99S52U119G111R114J108P100N64F109G99Y104U112T51N54L51H97U46C103J108D111U98Q97M108H45T105K110V116N114K97T46N110C101R116H58E50T56X48N49A55D47"; de.sc.portal.env.dlg.mongo.dlg_...
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
use crate::cache::TERRA_DIRECTORY; use crate::terrain::quadtree::node::VNode; use crate::terrain::tile_cache::{LayerParams, LayerType, TextureFormat}; use anyhow::Error; use serde::{Deserialize, Serialize}; use std::fs::{self, File}; use std::io::{BufReader, BufWriter, Read, Write}; use std::path::PathBuf; use vec_map:...
}
{ let value = serde_json::to_vec(&desc).unwrap(); self.textures.insert(name, value)?; Ok(()) }
identifier_body
mapfile.rs
use crate::cache::TERRA_DIRECTORY; use crate::terrain::quadtree::node::VNode; use crate::terrain::tile_cache::{LayerParams, LayerType, TextureFormat}; use anyhow::Error; use serde::{Deserialize, Serialize}; use std::fs::{self, File}; use std::io::{BufReader, BufWriter, Read, Write}; use std::path::PathBuf; use vec_map:...
( &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
use crate::cache::TERRA_DIRECTORY; use crate::terrain::quadtree::node::VNode; use crate::terrain::tile_cache::{LayerParams, LayerType, TextureFormat}; use anyhow::Error; use serde::{Deserialize, Serialize}; use std::fs::{self, File}; use std::io::{BufReader, BufWriter, Read, Write}; use std::path::PathBuf; use vec_map:...
for i in self.tiles.scan_prefix(&prefix) { let (k, v) = i?; let meta = bincode::deserialize::<TileMeta>(&v)?; let node = bincode::deserialize::<(LayerType, VNode)>(&k)?.1; f(node, meta)?; } Ok(()) } fn lookup_texture(&self, name: &str) -> ...
mut f: F, ) -> Result<(), Error> { let prefix = bincode::serialize(&layer).unwrap();
random_line_split
run.py
#!/usr/bin/env python import argparse from datetime import datetime import json import numpy as np import pyhmf as pynn import pyhalco_hicann_v2 as C from pymarocco import PyMarocco from pymarocco import Defects from pysthal.command_line_util import init_logger init_logger("ERROR", []) import params as par import ...
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
#!/usr/bin/env python import argparse from datetime import datetime import json import numpy as np import pyhmf as pynn import pyhalco_hicann_v2 as C from pymarocco import PyMarocco from pymarocco import Defects from pysthal.command_line_util import init_logger init_logger("ERROR", []) import params as par import ...
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
#!/usr/bin/env python import argparse from datetime import datetime import json import numpy as np import pyhmf as pynn import pyhalco_hicann_v2 as C from pymarocco import PyMarocco from pymarocco import Defects from pysthal.command_line_util import init_logger init_logger("ERROR", []) import params as par import ...
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
#!/usr/bin/env python import argparse from datetime import datetime import json import numpy as np import pyhmf as pynn import pyhalco_hicann_v2 as C from pymarocco import PyMarocco from pymarocco import Defects from pysthal.command_line_util import init_logger init_logger("ERROR", []) import params as par import ...
(): 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
#Family name: Jared Amos # Student number: 300068688 # Course: IT1 1120G # Assignment Number 1 ######################## # Question 1 ######################## ''' creates a function called repeat that takes 3 arguments, the fist argument is a string type and and the second is a integer value 'n' and the th...
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
#Family name: Jared Amos # Student number: 300068688 # Course: IT1 1120G # Assignment Number 1 ######################## # Question 1 ######################## ''' creates a function called repeat that takes 3 arguments, the fist argument is a string type and and the second is a integer value 'n' and the th...
######################## # 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
#Family name: Jared Amos # Student number: 300068688 # Course: IT1 1120G # Assignment Number 1 ######################## # Question 1 ######################## ''' creates a function called repeat that takes 3 arguments, the fist argument is a string type and and the second is a integer value 'n' and the th...
(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
#Family name: Jared Amos # Student number: 300068688 # Course: IT1 1120G # Assignment Number 1 ######################## # Question 1 ######################## ''' creates a function called repeat that takes 3 arguments, the fist argument is a string type and and the second is a integer value 'n' and the th...
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
/** * @license * Copyright (C) 2020-2021 Pryv S.A. https://pryv.com * * This file is part of Open-Pryv.io and released under BSD-Clause-3 License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redi...
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
/** * @license * Copyright (C) 2020-2021 Pryv S.A. https://pryv.com * * This file is part of Open-Pryv.io and released under BSD-Clause-3 License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redi...
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
/** * @license * Copyright (C) 2020-2021 Pryv S.A. https://pryv.com * * This file is part of Open-Pryv.io and released under BSD-Clause-3 License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redi...
* - Add specific stream queries to each of them */ async function findEventsFromStore(filesReadTokenSecret: string, isStreamIdPrefixBackwardCompatibilityActive: boolean, isTagsBackwardCompatibilityActive: boolean, context: MethodContext, params: GetEventsParams, result: Result, next: ApiCallback) { if (params....
/** * - Create a copy of the params per query
random_line_split
eventsGetUtils.js
/** * @license * Copyright (C) 2020-2021 Pryv S.A. https://pryv.com * * This file is part of Open-Pryv.io and released under BSD-Clause-3 License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redi...
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
""" Bokah interface for Imax B6 mini charnger Requires: bokeh - pip install bokuh but calls imax_0.py; see imax_0.py for additional necessary library packages """ import sys import time import datetime from bokeh.models import ColumnDataSource, Slider, DataTable, TableColumn from bokeh.plotting import Figure, output_f...
(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
""" Bokah interface for Imax B6 mini charnger Requires: bokeh - pip install bokuh but calls imax_0.py; see imax_0.py for additional necessary library packages """ import sys import time import datetime from bokeh.models import ColumnDataSource, Slider, DataTable, TableColumn from bokeh.plotting import Figure, output_f...
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
""" Bokah interface for Imax B6 mini charnger Requires: bokeh - pip install bokuh but calls imax_0.py; see imax_0.py for additional necessary library packages """ import sys import time import datetime from bokeh.models import ColumnDataSource, Slider, DataTable, TableColumn from bokeh.plotting import Figure, output_f...
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
""" Bokah interface for Imax B6 mini charnger Requires: bokeh - pip install bokuh but calls imax_0.py; see imax_0.py for additional necessary library packages """ import sys import time import datetime from bokeh.models import ColumnDataSource, Slider, DataTable, TableColumn from bokeh.plotting import Figure, output_f...
#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
## Collection of utils for building networks import numpy as np import tensorflow as tf from tensorflow.contrib import layers from atflow import constraints def conv2d_output_shape(input_shape, filter_shape, stride, padding): """ Computes the shape of the output tensor from conv2d operation with the given co...
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
## Collection of utils for building networks import numpy as np import tensorflow as tf from tensorflow.contrib import layers from atflow import constraints def conv2d_output_shape(input_shape, filter_shape, stride, padding): """ Computes the shape of the output tensor from conv2d operation with the given co...
(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
## Collection of utils for building networks import numpy as np import tensorflow as tf from tensorflow.contrib import layers from atflow import constraints def conv2d_output_shape(input_shape, filter_shape, stride, padding): """ Computes the shape of the output tensor from conv2d operation with the given co...
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
## Collection of utils for building networks import numpy as np import tensorflow as tf from tensorflow.contrib import layers from atflow import constraints def conv2d_output_shape(input_shape, filter_shape, stride, padding): """ Computes the shape of the output tensor from conv2d operation with the given co...
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
package core //#include <stdlib.h> import "C" import ( "fmt" "os" "path/filepath" "runtime" "strconv" "github.com/n0dev/go-slideshow/core/picture" "github.com/n0dev/go-slideshow/core/picture/exif" "github.com/n0dev/go-slideshow/logger" "github.com/n0dev/go-slideshow/utils" "github.com/veandco/go-sdl2/img"...
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
package core //#include <stdlib.h> import "C" import ( "fmt" "os" "path/filepath" "runtime" "strconv" "github.com/n0dev/go-slideshow/core/picture" "github.com/n0dev/go-slideshow/core/picture/exif" "github.com/n0dev/go-slideshow/logger" "github.com/n0dev/go-slideshow/utils" "github.com/veandco/go-sdl2/img"...
(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
package core //#include <stdlib.h> import "C" import ( "fmt" "os" "path/filepath" "runtime" "strconv" "github.com/n0dev/go-slideshow/core/picture" "github.com/n0dev/go-slideshow/core/picture/exif" "github.com/n0dev/go-slideshow/logger" "github.com/n0dev/go-slideshow/utils" "github.com/veandco/go-sdl2/img"...
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
package core //#include <stdlib.h> import "C" import ( "fmt" "os" "path/filepath" "runtime" "strconv" "github.com/n0dev/go-slideshow/core/picture" "github.com/n0dev/go-slideshow/core/picture/exif" "github.com/n0dev/go-slideshow/logger" "github.com/n0dev/go-slideshow/utils" "github.com/veandco/go-sdl2/img"...
} else { fmt.Printf("%d\n", t.Keysym.Sym) } } } if update { window.loadCurrentImage(true) update = false } } return 0 }
{ window.window.SetFullscreen(0) window.fullscreen = false }
conditional_block
w_reGeorgSocksProxy.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from traceback import format_exc import time import argparse from urlparse import urlparse from socket import * from threading import Thread import requests from handle_log import logger # Constants SOCKTIMEOUT = 5 RESENDTIMEOUT = 300 VER = "\x05" METHOD = "\x00" SUCCESS ...
# '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
#!/usr/bin/env python # -*- coding: utf-8 -*- from traceback import format_exc import time import argparse from urlparse import urlparse from socket import * from threading import Thread import requests from handle_log import logger # Constants SOCKTIMEOUT = 5 RESENDTIMEOUT = 300 VER = "\x05" METHOD = "\x00" SUCCESS ...
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
#!/usr/bin/env python # -*- coding: utf-8 -*- from traceback import format_exc import time import argparse from urlparse import urlparse from socket import * from threading import Thread import requests from handle_log import logger # Constants SOCKTIMEOUT = 5 RESENDTIMEOUT = 300 VER = "\x05" METHOD = "\x00" SUCCESS ...
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
#!/usr/bin/env python # -*- coding: utf-8 -*- from traceback import format_exc import time import argparse from urlparse import urlparse from socket import * from threading import Thread import requests from handle_log import logger # Constants SOCKTIMEOUT = 5 RESENDTIMEOUT = 300 VER = "\x05" METHOD = "\x00" SUCCESS ...
Exception, e: return False else: if response: text = response.text.strip() if response.status_code == 200 and text == "Georg says, 'All seems fine'": logger.info(text) return True else: return False if __name__ == '__main_...
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
use crate::task_token::TaskToken; use crate::{ errors::ActivityHeartbeatError, protos::{ coresdk::{common, ActivityHeartbeat, PayloadsExt}, temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse, }, ServerGatewayApis, }; use std::{ collections::HashMap, sync::{ ...
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
use crate::task_token::TaskToken; use crate::{ errors::ActivityHeartbeatError, protos::{ coresdk::{common, ActivityHeartbeat, PayloadsExt}, temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse, }, ServerGatewayApis, }; use std::{ collections::HashMap, sync::{ ...
fn record_heartbeat( hm: &ActivityHeartbeatManagerHandle, task_token: Vec<u8>, i: u8, delay: Duration, ) { hm.record( ActivityHeartbeat { task_token, details: vec![Payload { metadata: Default::default(), ...
{ 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
use crate::task_token::TaskToken; use crate::{ errors::ActivityHeartbeatError, protos::{ coresdk::{common, ActivityHeartbeat, PayloadsExt}, temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse, }, ServerGatewayApis, }; use std::{ collections::HashMap, sync::{ ...
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
use crate::task_token::TaskToken; use crate::{ errors::ActivityHeartbeatError, protos::{ coresdk::{common, ActivityHeartbeat, PayloadsExt}, temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse, }, ServerGatewayApis, }; use std::{ collections::HashMap, sync::{ ...
(&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
package types import ( "bytes" "fmt" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" "math/big" "strings" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/okex/exchain/ap...
func TestMsgEthereumTx_ChainID(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....
{ 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
package types import ( "bytes" "fmt" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" "math/big" "strings" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/okex/exchain/ap...
(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, chainID.Cmp(msg.ChainID(...
TestMsgEthereumTx_ChainID
identifier_name
msg_test.go
package types import ( "bytes" "fmt" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" "math/big" "strings" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/okex/exchain/ap...
} 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
package types import ( "bytes" "fmt" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" "math/big" "strings" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/okex/exchain/ap...
} 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
use super::*; use super::chunk::*; use super::user_space_vm::USER_SPACE_VM_MANAGER; use super::vm_area::VMArea; use super::vm_perms::VMPerms; use super::vm_util::{ FileBacked, VMInitializer, VMMapAddr, VMMapOptions, VMMapOptionsBuilder, VMRemapOptions, }; use crate::config; use crate::ipc::SHM_MANAGER; use crate::...
pub fn msync_by_file(&self, sync_file: &FileRef) { return USER_SPACE_VM_MANAGER.msync_by_file(sync_file); } // Return: a copy of the found region pub fn find_mmap_region(&self, addr: usize) -> Result<VMRange> { USER_SPACE_VM_MANAGER.find_mmap_region(addr) } } bitflags! { pub ...
{ return USER_SPACE_VM_MANAGER.msync(addr, size); }
identifier_body
process_vm.rs
use super::*; use super::chunk::*; use super::user_space_vm::USER_SPACE_VM_MANAGER; use super::vm_area::VMArea; use super::vm_perms::VMPerms; use super::vm_util::{ FileBacked, VMInitializer, VMMapAddr, VMMapOptions, VMMapOptionsBuilder, VMRemapOptions, }; use crate::config; use crate::ipc::SHM_MANAGER; use crate::...
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
use super::*; use super::chunk::*; use super::user_space_vm::USER_SPACE_VM_MANAGER; use super::vm_area::VMArea; use super::vm_perms::VMPerms; use super::vm_util::{ FileBacked, VMInitializer, VMMapAddr, VMMapOptions, VMMapOptionsBuilder, VMRemapOptions, }; use crate::config; use crate::ipc::SHM_MANAGER; use crate::...
(&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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 16 01:59:12 2020 @author: visionlab """ import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D,BatchNormalization,Dense, Dropout, Flatten, LeakyReLU, Lambda from custom_pooling import...
(): 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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 16 01:59:12 2020 @author: visionlab """ import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D,BatchNormalization,Dense, Dropout, Flatten, LeakyReLU, Lambda from custom_pooling import...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 16 01:59:12 2020 @author: visionlab """ import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D,BatchNormalization,Dense, Dropout, Flatten, LeakyReLU, Lambda from custom_pooling import...
plt.legend([ 'validation'], loc='upper left') plt.show() #plt.savefig('model validation_kappa.png')
plt.xlabel('epoch')
random_line_split
KR_256_5x5_32_Team.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 16 01:59:12 2020 @author: visionlab """ import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D,BatchNormalization,Dense, Dropout, Flatten, LeakyReLU, Lambda from custom_pooling import...
#model.add_loss( sample_loss(y_true, y_pred, Homotopy ) ) adam = Adam(lr=0.0014339, beta_1=0.9, beta_2=0.999, epsilon=0.1, decay=1e-6, amsgrad=True) model.compile(loss='mse', optimizer=adam, metrics=['mae', 'acc']) model.summary() #weight checking #a = pre_128_model.layers[0].get_weights()[0] #b = model....
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
package repository import ( //"gopkg.in/mgo.v2/bson" //"gopkg.in/mgo.v2" c "github.com/MichalRybinski/Trion/common" m "github.com/MichalRybinski/Trion/common/models" "fmt" //"encoding/json" "context" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.m...
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
package repository import ( //"gopkg.in/mgo.v2/bson" //"gopkg.in/mgo.v2" c "github.com/MichalRybinski/Trion/common" m "github.com/MichalRybinski/Trion/common/models" "fmt" //"encoding/json" "context" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.m...
func initSysIndexes(coll *mongo.Collection, iModel []mongo.IndexModel) { indexName, err := coll.Indexes().CreateMany( context.Background(), iModel, ) fmt.Println("indexName: ",indexName, " err: ",err) } var sysProjIndexModels = []mongo.IndexModel{ { Keys: bson.D{{"name", 1},{"owner", 1}}, ...
}
random_line_split
mongodb.go
package repository import ( //"gopkg.in/mgo.v2/bson" //"gopkg.in/mgo.v2" c "github.com/MichalRybinski/Trion/common" m "github.com/MichalRybinski/Trion/common/models" "fmt" //"encoding/json" "context" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.m...
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
package repository import ( //"gopkg.in/mgo.v2/bson" //"gopkg.in/mgo.v2" c "github.com/MichalRybinski/Trion/common" m "github.com/MichalRybinski/Trion/common/models" "fmt" //"encoding/json" "context" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.m...
) ([]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
package agent import ( "fmt" "io" "net" "os" "strconv" "strings" "Stowaway/node" "Stowaway/share" "Stowaway/utils" ) //startnode启动代码 //todo:可以为startnode加入一个保护机制,在startnode启动时可以设置是否开启此机制 //即当有节点异常断线时,可设置是否让startnode暂时断开与第二级节点的连接 //防止异常断线是由于管理员发现节点引起的,并根据connection进行逐点反查从而顺藤摸瓜找到入口点startnode,使得渗透测试者失去内网的入口点 //...
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
package agent import ( "fmt" "io" "net" "os" "strconv" "strings" "Stowaway/node" "Stowaway/share" "Stowaway/utils" ) //startnode启动代码 //todo:可以为startnode加入一个保护机制,在startnode启动时可以设置是否开启此机制 //即当有节点异常断线时,可设置是否让startnode暂时断开与第二级节点的连接 //防止异常断线是由于管理员发现节点引起的,并根据connection进行逐点反查从而顺藤摸瓜找到入口点startnode,使得渗透测试者失去内网的入口点 //...
} else { // 检查是否是admin发来的,分配给自己子节点的ID命令,是的话将admin分配的序号记录 if AdminData.Route == "" && AdminData.Command == "ID" { AgentStatus.WaitForIDAllocate <- AdminData.NodeId //将此节点序号递交,以便启动HandleConnFromLowerNode函数 node.NodeInfo.LowerNode.Lock() node.NodeInfo.LowerNode.Payload[AdminData.NodeId] = node.NodeInfo...
random_line_split
startnode.go
package agent import ( "fmt" "io" "net" "os" "strconv" "strings" "Stowaway/node" "Stowaway/share" "Stowaway/utils" ) //startnode启动代码 //todo:可以为startnode加入一个保护机制,在startnode启动时可以设置是否开启此机制 //即当有节点异常断线时,可设置是否让startnode暂时断开与第二级节点的连接 //防止异常断线是由于管理员发现节点引起的,并根据connection进行逐点反查从而顺藤摸瓜找到入口点startnode,使得渗透测试者失去内网的入口点 //...
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
package agent import ( "fmt" "io" "net" "os" "strconv" "strings" "Stowaway/node" "Stowaway/share" "Stowaway/utils" ) //startnode启动代码 //todo:可以为startnode加入一个保护机制,在startnode启动时可以设置是否开启此机制 //即当有节点异常断线时,可设置是否让startnode暂时断开与第二级节点的连接 //防止异常断线是由于管理员发现节点引起的,并根据connection进行逐点反查从而顺藤摸瓜找到入口点startnode,使得渗透测试者失去内网的入口点 //...
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
package console import ( "fmt" "image" "strconv" "strings" "github.com/hajimehoshi/ebiten/v2" ) type color struct { R byte G byte B byte } type char struct { charID int fgColor color bgColor color blink bool } type Console struct { videoTextMemory [25 * 80]char fgColor color bgColor ...
} c.cursor += i * columns c.cursorLimit() parseMode = false csi = false case v == 'C' && csi: // Cursor forward i := 1 if s != "" { var err error i, err = strconv.Atoi(s) if err != nil { fmt.Println(err) } } c.cursor += i c.cursorLimit() parseMode = false csi ...
{ fmt.Println(err) }
conditional_block
console.go
package console import ( "fmt" "image" "strconv" "strings" "github.com/hajimehoshi/ebiten/v2" ) type color struct { R byte G byte B byte } type char struct { charID int fgColor color bgColor color blink bool } type Console struct { videoTextMemory [25 * 80]char fgColor color bgColor ...
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
package console import ( "fmt" "image" "strconv" "strings" "github.com/hajimehoshi/ebiten/v2" ) type color struct { R byte G byte B byte } type char struct { charID int fgColor color bgColor color blink bool } type Console struct { videoTextMemory [25 * 80]char fgColor color bgColor ...
(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
package console import ( "fmt" "image" "strconv" "strings" "github.com/hajimehoshi/ebiten/v2" ) type color struct { R byte G byte B byte } type char struct { charID int fgColor color bgColor color blink bool } type Console struct { videoTextMemory [25 * 80]char fgColor color bgColor ...
func (c *Console) drawChar(index int, fgColor, bgColor color, x, y int) { var ( a int b int lColor color ) x = x * 9 y = y * 16 for b = 0; b < 16; b++ { for a = 0; a < 9; a++ { if a == 8 { color := bgColor if index >= 192 && index <= 223 { color = lColor } c.set(a+x, b+y...
{ 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
//! The `ledger_cleanup_service` drops older ledger data to limit disk space usage use solana_ledger::blockstore::Blockstore; use solana_ledger::blockstore_db::Result as BlockstoreResult; use solana_measure::measure::Measure; use solana_metrics::datapoint_debug; use solana_sdk::clock::Slot; use std::string::ToString; ...
pub fn cleanup_ledger( new_root_receiver: &Receiver<Slot>, blockstore: &Arc<Blockstore>, max_ledger_shreds: u64, last_purge_slot: &mut u64, purge_interval: u64, ) -> Result<(), RecvTimeoutError> { let mut root = new_root_receiver.recv_timeout(Duration::from_secs...
{ 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
//! The `ledger_cleanup_service` drops older ledger data to limit disk space usage use solana_ledger::blockstore::Blockstore; use solana_ledger::blockstore_db::Result as BlockstoreResult; use solana_measure::measure::Measure; use solana_metrics::datapoint_debug; use solana_sdk::clock::Slot; use std::string::ToString; ...
() { 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