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 |
|---|---|---|---|---|
pageserver.rs | ").zip(get_arg("relish-storage-region"))
{
Some(RelishStorage::AwsS3 {
bucket_name,
bucket_region,
access_key_id: get_arg("relish-storage-access-key"),
secret_access_key: get_arg("relish-storage-secret-access-key"),
})
... |
auth_validation_public_key_path,
auth_type,
relish_storage_config,
})
}
}
fn main() -> Result<()> {
let arg_matches = App::new("Zenith page server")
.about("Materializes WAL stream to pages and serves them to the postgres")
.arg(
Arg::wit... | random_line_split | |
executor.rs | config::{CrateProperties, is_completed};
use doc_decoder::DocData;
use lib_configs;
/// Options passed to `exec_all`,
/// as in `cpp_to_rust_generator::config::Config`.
pub struct ExecConfig {
pub write_dependencies_local_paths: bool,
pub cache_usage: CacheUsage,
pub write_cache: bool,
pub debug_logging_config... | type1.doc = Some(doc.0);
if let CppTypeKind::Enum { ref mut values } = type1.kind {
let enum_namespace = if let Some(index) = type1.name.rfind("::") {
type1.name[0..index + 2].to_string()
} else {
String::new()
... | for type1 in &mut cpp_data.types {
match parser.doc_for_type(&type1.name) {
Ok(doc) => {
// log::debug(format!("Found doc for type: {}", type1.name)); | random_line_split |
executor.rs | "ui_tools".to_string(),
"3d_core".to_string(),
"3d_render".to_string(),
"3d_input".to_string(),
"3d_logic".to_string(),
"3d_extras".to_string()]
} else {
libs
};
let mut configs: Vec<Config> = Vec::new();
for sublib_name in final_libs {
let lib_cache_dir = c... | find_methods_docs | identifier_name | |
set3.rs | _base64_string("VGhpcyBvdGhlciBoaXMgaGVscGVyIGFuZCBmcmllbmQ=")?);
base64_strings.push(from_base64_string("V2FzIGNvbWluZyBpbnRvIGhpcyBmb3JjZTs=")?);
base64_strings.push(from_base64_string("SGUgbWlnaHQgaGF2ZSB3b24gZmFtZSBpbiB0aGUgZW5kLA==")?);
base64_strings.push(from_base64_string("U28gc2Vuc2l0aXZlIGhpcyBuYXR1cmUg... | {
let key: Vec<_> = MersenneTwister::new(seed as u32).keystream().take(data.len()).collect();
fixed_xor(data, &key)
} | identifier_body | |
set3.rs | HRlZW50aC1jZW50dXJ5IGhvdXNlcy4=")?);
base64_strings.push(from_base64_string("SSBoYXZlIHBhc3NlZCB3aXRoIGEgbm9kIG9mIHRoZSBoZWFk")?);
base64_strings.push(from_base64_string("T3IgcG9saXRlIG1lYW5pbmdsZXNzIHdvcmRzLA==")?);
base64_strings.push(from_base64_string("T3IgaGF2ZSBsaW5nZXJlZCBhd2hpbGUgYW5kIHNhaWQ=")?);
base6... | for ciphertext in ciphertexts {
println!("{:?}", ciphertext.len());
concated_ciphertext.extend(&ciphertext[..min_length]); | random_line_split | |
set3.rs | _string("VGhpcyBvdGhlciBtYW4gSSBoYWQgZHJlYW1lZA==")?);
base64_strings.push(from_base64_string("QSBkcnVua2VuLCB2YWluLWdsb3Jpb3VzIGxvdXQu")?);
base64_strings.push(from_base64_string("SGUgaGFkIGRvbmUgbW9zdCBiaXR0ZXIgd3Jvbmc=")?);
base64_strings.push(from_base64_string("VG8gc29tZSB3aG8gYXJlIG5lYXIgbXkgaGVhcnQs")?);
... | generate_password_reset_token | identifier_name | |
set3.rs | xored with previous ciphertext block
// creates an intermediate state.
// however, if a server leaks information about the padding of a block
// (by returning 500 when a block is not padded for example)
// then we can calculate this intermediate state and xor the previous
// real ciphertext block with the i... |
}
}
}
let vec = Vec::from(result);
if is_pkcs7_padded(&vec) {
unpad_pkcs7(&vec)
} else {
Ok(vec)
}
}
pub fn get_base64_strings() -> Result<Vec<Vec<u8>>> {
let mut base64_strings = Vec::new();
base64_strings.push(from_base64_string("SSBoYXZlIG1ldCB0aGVtIGF0IGNsb3NlIG9mIGRheQ==")?);
b... | {
result.push_front(previous_block[i] ^ z ^ padding);
c1_suffix.push_front(z);
break;
} | conditional_block |
mm.rs | amount of virtual memory to reserve, including the guard
// size.
let reserve_size = GUARD_PAGE_SIZE.checked_add(size as u64)
.expect("Integer overflow on virtual region size");
// Get a new virtual region that is free
let ret = VirtAddr(
NEXT_FREE_VADDR.fetch_add(reserve_size, Ord... | {
/// Virtual address of the next `FreeListNode`
next: usize,
/// Number of free slots in `free_mem`
free_slots: usize,
/// Virtual addresses of free allocations
free_addrs: [*mut u8; 0],
}
/// A free list which holds free entries of `size` bytes in a semi-linked list
/// table thingy.
p... | FreeListNode | identifier_name |
mm.rs | 96 {
// Special case, if the allocation fits within a page, we can
// directly return virtual addresses to our physical memory
// map. This is significantly better for TLBs and caches than
// to create new page tables for allocating a new virtual
... | /// Print the allocation statistics to the screen
pub fn print_alloc_stats() {
// Get total amount of physical memory | random_line_split | |
mm.rs | ] {
let end = size.checked_sub(1).and_then(|x| {
x.checked_add(paddr.0)
}).expect("Integer overflow on read_phys");
assert!(end < KERNEL_PHYS_WINDOW_SIZE,
"Physical address outside of window");
// Return out a slice to this physical memory as mutable
core::slice::from_raw_parts(... | {
// Check if there is room for this allocation in the free stack,
// or if we need to create a new stack
if self.head == 0 ||
(*(self.head as *const FreeListNode)).free_slots == 0 {
// No free slots, create a new stack out of the freed vaddr
... | conditional_block | |
main.rs | packing)
// Above there are 9 u16 numbers which is 9 x 2 bytes
// We add one more u16 to square this
/* padding */ 0,
];
const SECOND_INDICES: &[u16] = &[
0, 1, 4,
2, 3, 4,
// WGPU requires 4 bytes buffer alignment (packing)
// Above there are 9 u16 numbers which is 9 x 2 bytes
// We ad... | {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
sc_desc: wgpu::SwapChainDescriptor,
swap_chain: wgpu::SwapChain,
size: winit::dpi::PhysicalSize<u32>,
mouse_pos: cgmath::Point2<f64>,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buf... | State | identifier_name |
main.rs | packing)
// Above there are 9 u16 numbers which is 9 x 2 bytes
// We add one more u16 to square this
/* padding */ 0,
];
const SECOND_INDICES: &[u16] = &[
0, 1, 4,
2, 3, 4,
// WGPU requires 4 bytes buffer alignment (packing)
// Above there are 9 u16 numbers which is 9 x 2 bytes
// We ad... | let diffuse_rgba = diffuse_image.as_rgba8().expect("Can't transform image info");
use image::GenericImageView;
let dimensions = diffuse_image.dimensions();
let texture_size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
// All textures... | random_line_split | |
main.rs | let dimensions = diffuse_image.dimensions();
let texture_size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
// All textures are stored as 3D, 2D textures have depth of 1.
depth_or_array_layers: 1,
};
let diffuse_texture = ... | {
(&self.index_buffer, self.num_indices)
} | conditional_block | |
main.rs | VULKAN
let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
// This is unsafe because on some Linux systems lifetime of the window might not be as long
// as the lifetime of the program. See: https://github.com/gfx-rs/wgpu/issues/1463
let surface = unsafe { instance.create_sur... | {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc);
} | identifier_body | |
PEATSAplugin.py | 1)
Button(jobdlg,text='Load Mutations from File',command=loadmuts).pack(fill=X,expand=1)
balloon.bind(mutlist, 'Enter one mutation per line in the form\n A:0003:ALA or A3A')
f=Frame(jobdlg); f.pack(fill=X,expand=1)
Button(f,text='Submit',command=submit).pack(side=LEFT,fill=X,expa... | if self.matrices[m] != None:
self.showMatrix(fr,self.matrices[m], m) | conditional_block | |
PEATSAplugin.py | states.log',interval=60)
print '\nConnection to server made sucessfully.\n'
return
def createMutationList(self, filename=None):
self.mutationList = Core.Data.MutationListFile(create=False)
return
def fetchJob(self):
"""Get job from it's db I... | (text):
if not hasattr(self.DB.meta,'peatsa_jobs'):
return 1
if text in self.DB.meta.peatsa_jobs:
return -1
else:
return 1
def close():
jobdlg.destroy()
def loadmuts():
filename=tkFileDial... | validatename | identifier_name |
PEATSAplugin.py |
def manageJobsButtons(self, parent):
fr1 = Frame(parent)
Button(fr1,text='View Results',command=self.showAllResults,bg='#ccFFFF').pack(side=TOP,fill=BOTH,expand=1)
fr1.pack(fill=BOTH)
Button(fr1,text='Merge Results',command=self.mergeCurrent).pack(side=TOP,fill=BOTH,expand=1)
... | random_line_split | ||
PEATSAplugin.py | 'both':
# calcs = ['stability','binding']
if calcmenu.getcurselection() == 'pka':
calcs = ['scan']
else:
calcs = [calcmenu.getcurselection()]
mutationlist = mutlist.getvalue().split('\n')
mutationlist.remove('')
... | """add a space to the end of the word"""
word = word + " "
st.insert('end', word)
end_index = st.index('end')
begin_index = "%s-%sc" % (end_index, len(word) + 1)
st.tag_add(tag, begin_index, end_index)
st.tag_config(tag, foreground=fg, background=bg)
return | identifier_body | |
Weather.py |
def getTargetNames(self):
""" Get target names
Returns:
Target names
"""
return self.targetNames
def getNrTargets(self):
""" Get number of targets
Returns:
Number of targets
"""
return self.targetNames.size
def getF... | """ Get number of weather observations read from file
Returns:
Number of weather observations
"""
return len(self.data) | identifier_body | |
Weather.py | if (offset):
if not (offset[0] and offset[1]):
return 0
coords = self._getNewCoords(coords, offset)
# iterate through weather stations
for s in self.stationData:
# get distance between point and station
distance = self._getDistanc... | _getRelTime | identifier_name | |
Weather.py | of a chosen feature with a given list of new values
Args:
feature (str): selected feature
newValues (list(str)): New set of values to overwrite old data
Returns:
0 for success
"""
self.data[:,self._getFIdx(feature)] = newValues
return 0
d... |
elif (streamHeader == 'BASIC'):
self.dataStream = 2
else:
print "Error: unecognised data stream from file %s" % (self.wfile)
return -1
# read data
inputData = []
for line in weatherData:
entries = line.split()
inputD... | self.dataStream = 1 | conditional_block |
Weather.py | a chosen feature with a given list of new values
Args:
feature (str): selected feature
newValues (list(str)): New set of values to overwrite old data
Returns:
0 for success
"""
self.data[:,self._getFIdx(feature)] = newValues
return 0
def ... | return stats[:,features]
else:
return stats
def findStations(self, coords=[], offset=[], minThreshold=10, maxThreshold=100):
""" Find the nearet observation station to a given location
Args:
coords (list(str1, str2)): Latitude and Longitude of location
... | features = [self._getFIdx(f) for f in features] | random_line_split |
TD_Functions.py | 5)
def source_feature(seq_rec):
feature = None
for f in seq_rec.features:
if f.type == 'source':
feature = f
break
if not feature:
feature = SeqFeature(FeatureLocation(0,len(seq_rec.seq)),
type = 'source')
seq_rec.features.append... | nue
| conditional_block | |
TD_Functions.py | K = DUP/((P-DUP)*(D-DUP))
#initial corrections
dH += delta_H('ini', 'ini')
dS += delta_S('ini', 'ini')
#test for AT terminals
if seq_str[0] == 'A' or seq_str[0] == 'T':
dH += delta_H('ter', 'ter')
dS += delta_S('ter', 'ter')
if seq_str[-1] == 'A' or seq_str[-1] == 'T':
... | random_line_split | ||
TD_Functions.py | )
#utility functions
def print_exception(e):
print "Exception occurred: " + str(type(e)) + " : " + e.__str__()
###############################################################################
#standard PCR conditions
C_Mg = 1.5 #mM
C_Na = 50 #mM; should be above 0.05M and below 1.1M
C_dNTP = 0 #mM
C_DNA... | def
def calculate_Tr(seq_rec, r):
primer_Tr = NN_Tr(seq_rec.seq, r)
feature = source_feature(seq_rec)
add_PCR_conditions(feature)
feature.qualifiers['T-'+str(r)] = str(primer_Tr)
return primer_Tr
#end def
def calculate_Tm(seq_rec):
primer_Tm = NN_Tm(seq_rec.seq)
... | feature.qualifiers['C_Na'] = str(C_Na)+ ' mM'
feature.qualifiers['C_Mg'] = str(C_Mg)+ ' mM'
feature.qualifiers['C_dNTP'] = str(C_dNTP)+' mM'
feature.qualifiers['C_DNA'] = str(C_DNA)+ ' nM'
feature.qualifiers['C_Primer'] = str(C_Prim)+' uM'
feature.qual... | identifier_body |
TD_Functions.py | #utility functions
def print_exception(e):
print "Exception occurred: " + str(type(e)) + " : " + e.__str__()
###############################################################################
#standard PCR conditions
C_Mg = 1.5 #mM
C_Na = 50 #mM; should be above 0.05M and below 1.1M
C_dNTP = 0 #mM
C_DNA = ... | conc_str = ''
spacer = max(len(str(C_Na)),
len(str(C_Mg)),
len(str(C_dNTP)),
len(str(C_DNA)),
len(str(C_Prim)),
len(str(C_DMSO)))
conc_str += 'C(Na) = ' + str(C_Na) + ' '*(spacer-len(str(C_Na))) +' mM\n'
conc_s... | t_PCR_conditions():
| identifier_name |
upload.rs | std::sync::Arc;
let mut builder = ureq::builder();
if let Ok(proxy) = http_proxy() {
let proxy = ureq::Proxy::new(proxy)?;
builder = builder.proxy(proxy);
};
let mut tls_builder = native_tls::TlsConnector::builder();
if let Some(ca_bundle) = tls_ca_bundle() {
let mut reader... | Err(keyring::Error::NoEntry)
| Err(keyring::Error::NoStorageAccess(_)) | random_line_split | |
upload.rs | UploadError {
fn from(error: native_tls::Error) -> Self {
UploadError::TlsError(error)
}
}
/// A pip registry such as pypi or testpypi with associated credentials, used
/// for uploading wheels
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Registry {
/// The username
pub username: String,
... | config
}
fn load_pypi_cred_from_config(config: &Ini, registry_name: &str) -> Option<(String, String)> {
if let (Some(username), Some(password)) = (
config.get(registry_name, "username"),
config.get(registry_name, "password"),
) {
return Some((username, password));
}
None
}
/// ... | config_path.push(".pypirc");
if let Ok(pypirc) = fs::read_to_string(config_path.as_path()) {
let _ = config.read(pypirc);
}
}
| conditional_block |
upload.rs | UploadError {
fn from(error: native_tls::Error) -> Self {
UploadError::TlsError(error)
}
}
/// A pip registry such as pypi or testpypi with associated credentials, used
/// for uploading wheels
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Registry {
/// The username
pub username: String,
... | // Attempts to fetch the password from the keyring (if enabled)
/// and falls back to the interactive password prompt.
fn get_password(_username: &str) -> String {
#[cfg(feature = "keyring")]
{
let service = env!("CARGO_PKG_NAME");
let keyring = keyring::Entry::new(service, _username);
i... | Registry {
username,
password,
url,
}
}
}
/ | identifier_body |
upload.rs | UploadError {
fn from(error: native_tls::Error) -> Self {
UploadError::TlsError(error)
}
}
/// A pip registry such as pypi or testpypi with associated credentials, used
/// for uploading wheels
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Registry {
/// The username
pub username: String,
... | : String,
}
#[derive(Debug, Deserialize)]
struct OidcTokenResponse {
value: String,
}
#[derive(Debug, Deserialize)]
struct MintTokenResponse {
token: String,
}
/// Trusted Publisher support for GitHub Actions
fn resolve_pypi_token_via_oidc(registry_url: &str) -> Result<Option<String>> {
if env::var_os("G... | ponse {
audience | identifier_name |
armature.py | .frames.append(frame)
self.animation.values.append(currentBoneMatrix)
self.previousBoneMatrix = currentBoneMatrix
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def set_rest_pose(self, editBone):
self.rest = Bone.get_matrix(editBone, self.matrix_wor... |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@staticmethod
def get_matrix(bpyBone, matrix_world, doParentMult):
SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
if (bpyBone.parent and doParentMult):
r... | return Bone.get_matrix(self.posedBone, self.matrix_world, doParentMult) | identifier_body |
armature.py |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def append_animation_pose(self, frame, force = False):
currentBoneMatrix = self.get_bone_matrix()
if (force or not same_matrix4(currentBoneMatrix, self.previousBoneMatrix)):
self.animation.frames.append(f... | self.animation = Animation(ANIMATIONTYPE_MATRIX, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
self.previousBoneMatrix = None | conditional_block | |
armature.py | .frames.append(frame)
self.animation.values.append(currentBoneMatrix)
self.previousBoneMatrix = currentBoneMatrix
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def set_rest_pose(self, editBone):
self.rest = Bone.get_matrix(editBone, self.matrix_wor... | (bpyBone, matrix_world, doParentMult):
SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
if (bpyBone.parent and doParentMult):
return (SystemMatrix * matrix_world * bpyBone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bpyBone.matrix)... | get_matrix | identifier_name |
armature.py | if (bpyBone.parent and doParentMult):
return (SystemMatrix * matrix_world * bpyBone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bpyBone.matrix)
else:
return SystemMatrix * matrix_world * bpyBone.matrix
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ... | random_line_split | ||
poller.py | import requests
import key as k
import logging
BCOEFFICIENT = 3950 # thermistor beta coefficient
THERMISTORNOMINAL = 10000
TEMPERATURENOMINAL = 25.0
SERIESRESISTOR = 10000
# a1 = blue and white, which is bed temp
# a2 = white and orange, which is tank temp
interval = 60 # seconds between samples
greenPin = 'P8_13'
blu... | # temp1 = adc.read_raw(thermistor1)
temp1 = adc.read_raw(thermistor1)
time.sleep(1)
print 'temp1 raw %s' % temp1
temp1 = convert_thermistor_special(temp1)
readings['bedTemp'] = temp1
print 'converted bed_temp is %s' % temp1
# # do conversion per
# # http://learn.adafruit.com/the... | random_line_split | |
poller.py | (1)
# photo = adc.read(photoPin) # have to read twice due to bbio bug
photo = 1.0-adc.read(photoPin) # reverse range so that 0 is darkest
print 'photo is %s' % photo
time.sleep(1)
# temp1 = adc.read_raw(thermistor1)
temp1 = adc.read_raw(thermistor1)
time.sleep(1)
print 't... | print 'we are in the first %s minutes of the hour, so pump should be on.' % PUMP_DURATION
gpio.output(pumpPin,gpio.HIGH) | conditional_block | |
poller.py | import requests
import key as k
import logging
BCOEFFICIENT = 3950 # thermistor beta coefficient
THERMISTORNOMINAL = 10000
TEMPERATURENOMINAL = 25.0
SERIESRESISTOR = 10000
# a1 = blue and white, which is bed temp
# a2 = white and orange, which is tank temp
interval = 60 # seconds between samples
greenPin = 'P8_13'
blu... | time.sleep(1)
print 'temp1 raw %s' % temp1
temp1 = convert_thermistor_special(temp1)
readings['bedTemp'] = temp1
print 'converted bed_temp is %s' % temp1
# # do conversion per
# # http://learn.adafruit.com/thermistor/using-a-thermistor
# temp2 = adc.read_raw(thermistor2)
temp2 ... | print 'sensor read'
global readings
readings = {}
# value = ADC.read("AIN1")
# adc returns value from 0 to 1.
# use read_raw(pin) to get V values
# tank = adc.read(tankPin)
tank = adc.read(tankPin) # have to read twice due to bbio bug
print 'tank is %s' % tank
time.sleep(1)
... | identifier_body |
poller.py | import requests
import key as k
import logging
BCOEFFICIENT = 3950 # thermistor beta coefficient
THERMISTORNOMINAL = 10000
TEMPERATURENOMINAL = 25.0
SERIESRESISTOR = 10000
# a1 = blue and white, which is bed temp
# a2 = white and orange, which is tank temp
interval = 60 # seconds between samples
greenPin = 'P8_13'
blu... | ():
print 'state_display'
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Load default font.
# font = ImageFont.load_default()
# Alternatively load a TTF font.
# Some other nice... | do_state_display | identifier_name |
ddpg.py | , activation='softmax', weights_init=w_init)
return in_states, out_actions
def train(self, inputs, a_gradient):
self.sess.run(self.optimize, feed_dict={
self.onnet_in_states: inputs,
self.action_gradient: a_gradient
})
def predict(self, inp_states):
out_... | choose_action | identifier_name | |
ddpg.py | _num_trainable_vars(self):
return self.num_trainable_vars
class CriticNetwork(object):
"""
Input to the network is the state and action, output is Q(s,a).
The action must be obtained from the output of the Actor network.
"""
def __init__(self, sess, num_actor_vars):
self.sess = ... | with tf.Session() as sess:
# TODO: reduce network sizes. keep all states stop editing this ver, add dropout in successor
env = gym.make(ENV_NAME)
np.random.seed(RANDOM_SEED)
tf.set_random_seed(RANDOM_SEED)
env.seed(RANDOM_SEED)
# Ensure action bound is symmetric
#... | identifier_body | |
ddpg.py | ACTION_PROB_DIMS = 2
ACTION_BOUND = 1
ACTION_SPACE = [0, 1]
# ===========================
# Utility Parameters
# ===========================
# Render gym env during training
RENDER_ENV = True
# Use Gym Monitor
GYM_MONITOR_EN = True
# Gym environment
ENV_NAME = 'CartPole-v0'
# Directory for storing gym results
MONITO... | # Soft target update param
TAU = 0.05
STATE_DIM = 4
ACTION_DIM = 1 | random_line_split | |
ddpg.py |
class CriticNetwork(object):
"""
Input to the network is the state and action, output is Q(s,a).
The action must be obtained from the output of the Actor network.
"""
def __init__(self, sess, num_actor_vars):
self.sess = sess
self.s_dim = STATE_DIM
self.a_dim = ACTION_D... | tf.app.run() | conditional_block | |
lab3.py |
size_field = match.group(9)
if size_field == '-':
size = long(0)
else:
size = long(match.group(9))
return (Row(
host = match.group(1),
client_identd = match.group(2),
user_id = match.group(3),
date_time = parse_apache_time(match.group(4... | return (logline, 0) | conditional_block | |
lab3.py | print 'Read {} lines, successfully parsed {} lines, failed to parse {} lines'.format((parsed_logs.count(), access_logs.count(), failed_logs.count()))
return parsed_logs, access_logs, failed_logs
parsed_logs, access_logs, failed_logs = parseLogs()
APACHE_ACCESS_LOG_PATTERN = '^(\S+) (\S+) (\S+).*\[([\w:\/]+... | """ Read and parse log file """
parsed_logs = (sc
.textFile(logFile)
.map(parseApacheLogLine)
.cache())
access_logs = (parsed_logs
.filter(lambda s: s[1] == 1)
.map(lambda s: s[0])
.cache())
f... | identifier_body | |
lab3.py | /winvn/readme.txt', 633), (u'/pub/winvn/release.txt', 494), (u'/shuttle/missions/STS-69/mission-STS-69.html', 431), (u'/images/nasa-logo.gif', 319), (u'/elv/DELTA/uncons.htm', 178), (u'/shuttle/missions/sts-68/ksc-upclose.gif', 156), (u'/history/apollo/sa-1/sa-1-patch-small.gif', 146), (u'/images/crawlerway-logo.gif', ... | Test.assertTrue(hourRecordsSorted.is_cached, 'incorrect hourRecordsSorted.is_cached')
hoursWithErrors404 = hourRecordsSorted.map(lambda x: x[0]).takeOrdered(30) | random_line_split | |
lab3.py | ():
""" Read and parse log file """
parsed_logs = (sc
.textFile(logFile)
.map(parseApacheLogLine)
.cache())
access_logs = (parsed_logs
.filter(lambda s: s[1] == 1)
.map(lambda s: s[0])
.cache()... | parseLogs | identifier_name | |
lib.rs | , doing so will **`panic!`**.
///
/// If you do implement this method, also make sure to implement `implements_poll_child`
/// such that it returns true if you want it to be used on `self` specifically.
fn poll_child_mut(&mut self, _id: ID) { }
fn implements_poll_child(&self) -> bool { false }
... |
fn cod(&self) {
let _ = self.clone();
}
}
pub struct Child<T: NodeClone> {
inner_ref: Rc<T>,
}
pub struct ParentID(ID);
impl From<ID> for ParentID {
fn from(id: ID) -> Self { ParentID(id) }
}
impl From<&Header> for ParentID {
fn from(header: &Header) -> Self { ParentID(header.id) }
}
imp... | {
Rc::new(self.clone())
} | identifier_body |
lib.rs | , doing so will **`panic!`**.
///
/// If you do implement this method, also make sure to implement `implements_poll_child`
/// such that it returns true if you want it to be used on `self` specifically.
fn poll_child_mut(&mut self, _id: ID) { }
fn implements_poll_child(&self) -> bool { false }
... | (&self) -> Rc<T> {
Rc::clone(&self.inner_ref)
}
pub fn get_id(&self) -> ID {
self.inner_ref.header().id
}
pub fn set_parent(&mut self, parent: impl Into<ParentID>) {
self.make_mut().header_mut().parent_id = Some(parent.into().0);
}
/// Deep clone and set new parent... | get_ref | identifier_name |
lib.rs | , doing so will **`panic!`**.
///
/// If you do implement this method, also make sure to implement `implements_poll_child`
/// such that it returns true if you want it to be used on `self` specifically.
fn poll_child_mut(&mut self, _id: ID) { }
fn implements_poll_child(&self) -> bool { false }
... | // so going to an old state after catching an unwind _should_ be fine.
if std::thread::panicking() { return }
CONTEXT.with(|c| {
Context::poll(c, PollReason::Drop, Rc::clone(&self.inner_ref));
});
}
}
pub struct MakeMutRef<'a, T: NodeClone> {
child: &'a mut Child<T>
... | }
impl<T: NodeClone> Drop for Child<T> {
fn drop(&mut self) {
// XXX: This should only create inconsistencies in the newest version of the data, | random_line_split |
bundle.py | key_network(self) -> str:
return "network"
def key_network_def(self) -> str:
return "network_def"
def key_train_trainer_max_epochs(self) -> str:
return "train#trainer#max_epochs"
def key_train_dataset_data(self) -> str:
return "train#dataset#data"
def key_train_handl... | (self) -> str:
return "experiment_name"
def key_run_name(self) -> str:
return "run_name"
def key_displayable_configs(self) -> Sequence[str]:
return ["displayable_configs"]
class BundleTrainTask(TrainTask):
def __init__(
self,
path: str,
conf: Dict[str, str... | key_experiment_name | identifier_name |
bundle.py | -> str:
return "train#handlers"
def key_validate_dataset_data(self) -> str:
return "validate#dataset#data"
def key_tracking(self) -> str:
return "tracking"
def key_tracking_uri(self) -> str:
return "tracking_uri"
def key_experiment_name(self) -> str:
return "... | overrides[self.const.key_experiment_name()] = tracking_experiment_name | conditional_block | |
bundle.py | model_dict_key="model",
load_strict=False,
):
self.valid: bool = False
self.conf = conf
self.const = const if const else BundleConstants()
self.enable_tracking = enable_tracking
self.model_dict_key = model_dict_key
self.load_strict = load_strict
conf... | if not config_paths:
logger.warning(
f"Ignore Multi-GPU Training; No multi-gpu train config {self.const.multi_gpu_configs()} exists" | random_line_split | |
bundle.py | key_network(self) -> str:
return "network"
def key_network_def(self) -> str:
return "network_def"
def key_train_trainer_max_epochs(self) -> str:
return "train#trainer#max_epochs"
def key_train_dataset_data(self) -> str:
return "train#dataset#data"
def key_train_handl... |
def key_tracking(self) -> str:
return "tracking"
def key_tracking_uri(self) -> str:
return "tracking_uri"
def key_experiment_name(self) -> str:
return "experiment_name"
def key_run_name(self) -> str:
return "run_name"
def key_displayable_configs(self) -> Sequenc... | return "validate#dataset#data" | identifier_body |
__init__.py | (0, self.height)
if not self.bomb_map[x][y] and not self._count_adjacent_bombs(x, y):
self.click(x, y)
break
tries += 1
def create_image(self, cheat=False) -> PIL.Image.Image:
w = self.width * self.cell_size
h = self.height * self.cell_size
... | config.add(bomb_chance)
commands.add(start)
commands.add(click)
commands.add(flag)
commands.add(cheat) | identifier_body | |
__init__.py | _text(draw, x, y, text, *args, font, **kwargs):
w, h = draw.textsize(text, font=font)
draw.text((x - w / 2, y - h / 2), text, *args, font=font, **kwargs)
def load_tile_graphics():
images = {}
for play in Play:
with pkg_resources.resource_stream(__name__, "assets/{}.png".format(play.name.lower(... |
else:
raise CommandError("You can't click that cell!")
def _in_bounds(self, x, y):
return 0 <= x < self.width and 0 <= y < self.height
def _is_bomb(self, x, y):
return self._in_bounds(x, y) and self.bomb_map[x][y]
def _count_adjacent_bombs(self, x, y):
return ... | self.state = State.WON | conditional_block |
__init__.py | _text(draw, x, y, text, *args, font, **kwargs):
w, h = draw.textsize(text, font=font)
draw.text((x - w / 2, y - h / 2), text, *args, font=font, **kwargs)
def load_tile_graphics():
images = {}
for play in Play:
with pkg_resources.resource_stream(__name__, "assets/{}.png".format(play.name.lower(... | (message):
"""
Starts a game of minesweeper.
Example::
mine start
"""
key = (message.transport.id, message.server.id, message.channel.id)
if key in cache:
game = cache[key]
else:
game = Game(12, 12, scoped_config.get(bomb_chance, message.channel) / 100, random.Ran... | start | identifier_name |
__init__.py | _text(draw, x, y, text, *args, font, **kwargs):
w, h = draw.textsize(text, font=font)
draw.text((x - w / 2, y - h / 2), text, *args, font=font, **kwargs)
def load_tile_graphics():
images = {}
for play in Play:
with pkg_resources.resource_stream(__name__, "assets/{}.png".format(play.name.lower(... |
def _in_bounds(self, x, y):
return 0 <= x < self.width and 0 <= y < self.height
def _is_bomb(self, x, y):
return self._in_bounds(x, y) and self.bomb_map[x][y]
def _count_adjacent_bombs(self, x, y):
return sum([
self._is_bomb(x - 1, y),
self._is_bomb(x, y - ... | self._clear_cell(x, y, set())
if self.remaining_unknown == 0:
self.state = State.WON
else:
raise CommandError("You can't click that cell!") | random_line_split |
lsh.py |
def jaccard_sim(X, Y):
"""Jaccard similarity between two sets"""
x = set(X)
y = set(Y)
return float(len(x & y)) / len(x | y)
def jaccard_dist(X, Y):
"""Jaccard distance between two sets"""
return 1 - jaccard_sim(X, Y)
class Signature(object):
"""Signature Base class."""
def __init_... | yield hash(s) | conditional_block | |
lsh.py | (s, k):
"""Generate k-length shingles of string s"""
k = min(len(s), k)
for i in range(len(s) - k + 1):
yield s[i:i+k]
def hshingle(s, k):
"""Generate k-length shingles then hash"""
for s in shingle(s, k):
yield hash(s)
def jaccard_sim(X, Y):
"""Jaccard similarity between two s... | shingle | identifier_name | |
lsh.py | 1 - jaccard_sim(X, Y) | class Signature(object):
"""Signature Base class."""
def __init__(self, dim):
self.dim = dim
self.hashes = self.hash_functions()
def hash_functions(self):
"""Returns dim different hash functions"""
pass
def sign(self, object):
"""Return the signature for object... | random_line_split | |
lsh.py | 1 - jaccard_sim(X, Y)
class Signature(object):
"""Signature Base class."""
def __init__(self, dim):
self.dim = dim
self.hashes = self.hash_functions()
def hash_functions(self):
"""Returns dim different hash functions"""
pass
def sign(self, object):
"""Return... |
# Add to unionfind structure
self.unionfind[label]
# Get signature
sig = self.signer.sign(s)
# Union labels with same LSH key in same band
for band_idx, hshval in enumerate(self.hasher.hash(sig)):
self.hashmaps[band_idx][hshval].append(label)
se... | """Clusters sets with Jaccard similarity above threshold with high
probability.
Algorithm based on Rajaraman, "Mining of Massive Datasets":
1. Generate set signature
2. Use LSH to map similar signatures to same buckets
3. Use UnionFind to merge buckets containing same values
"""
def __init_... | identifier_body |
denoising_autoencoder.py | , corruption=0.3):
"""
input_dimension: The dimension of the input vectors.
hidden_dimension: How many hidden nodes to map to.
input_batch: Optional. Input data.
output_batch: Optional. A vector of labels corresponding to each input vector.
output_dimension: How many labels there are.
symbolic_input: Opti... |
return self.weights.get_value(borrow=True)
def train_model(self
, epochs=100
, minibatch_size=20
, yield_every_iteration=False):
"""
Train the model against the given data.
epochs: How long to train for.
minibatch_size: How large each minibatch is.
yield_every_iteration: When to yield.
"""
if... | def get_weight_matrix(self):
"""
Get the weight matrix.
""" | random_line_split |
denoising_autoencoder.py | , corruption=0.3):
"""
input_dimension: The dimension of the input vectors.
hidden_dimension: How many hidden nodes to map to.
input_batch: Optional. Input data.
output_batch: Optional. A vector of labels corresponding to each input vector.
output_dimension: How many labels there are.
symbolic_input: Opti... | (self
, epochs=100
, minibatch_size=20
, yield_every_iteration=False):
"""
Train the model against the given data.
epochs: How long to train for.
minibatch_size: How large each minibatch is.
yield_every_iteration: When to yield.
"""
if self.input_batch is None:
raise ValueError("Denoising autoe... | train_model | identifier_name |
denoising_autoencoder.py | , corruption=0.3):
"""
input_dimension: The dimension of the input vectors.
hidden_dimension: How many hidden nodes to map to.
input_batch: Optional. Input data.
output_batch: Optional. A vector of labels corresponding to each input vector.
output_dimension: How many labels there are.
symbolic_input: Opt... | self.learning_rate*lr_weight_gradient),
(self.label_bias, self.label_bias -
self.learning_rate*lr_bias_gradient)]
return updates
def initialise_theano_functions(self):
"""
Compile Theano functions for symbolic variables.
"""
index = theano.tensor.lscalar("i")
batch_size = theano.tensor.lscal... | """
Get a list of updates to make when the model is trained.
"""
da_cost = self.get_cost()
weight_gradient = theano.tensor.grad(da_cost, self.weights)
bias_gradient = theano.tensor.grad(da_cost, self.bias)
reverse_bias_gradient = theano.tensor.grad(da_cost, self.reverse_bias)
lr_cost = self.get_lr_cost... | identifier_body |
denoising_autoencoder.py | self.corruption = corruption
self.input_batch = input_batch
self.activation = theano.tensor.nnet.sigmoid
self.learning_rate = learning_rate
self.initialise_corrupted_input()
self.initialise_parameters()
self.initialise_theano_functions()
def initialise_corrupted_input(self):
self.symbolic_corrupted_in... | print epoch, cost
print "wrong {:.02%} of the time".format(
float(da.validate_model(validation_images, validation_labels))) | conditional_block | |
webapp.py | dev"
:returns: A major.minor.patch[.sub] version string or "dev".
"""
# Note: if you install from a cloned git repository
# (e.g. pip install ./tk-core), the version number
# will be picked up from the most recently added tag.
try:
version_git = subprocess.check_output(
["gi... | # /sg2jira/default[/Task/123]
# /jira2sg/default/Issue/KEY-123
# /admin/reset
try:
parsed = parse.urlparse(self.path)
# Extract additional query parameters.
# What they could be is still TBD, may be things like `dry_run=1`?
parameters = {}
... | """ | random_line_split |
webapp.py | pass
return "dev"
class SgJiraBridgeBadRequestError(Exception):
"""
Custom exception so we can differentiate between errors we raise that
should return 4xx error codes and errors in the application which should
return 500 error codes.
"""
pass
class Server(ThreadingMixIn, Base... | """
Helper to extract a version number for the sg-jira-bridge module.
This will attenmpt to extract the version number from git if installed from
a cloned repo. If a version is unable to be determined, or the process
fails for any reason, we return "dev"
:returns: A major.minor.patch[.sub] version... | identifier_body | |
webapp.py |
# discard empty values coming from '/' at the end or multiple
# contiguous '/'.
path_parts = [x for x in self.path[1:].split("/") if x]
if not path_parts:
self.post_response(
200,
"The server is alive",
HMTL_TEMPLATE % ("The se... | log_error | identifier_name | |
webapp.py | the SG Jira Bridge method.
"""
return self._sg_jira.reset(*args, **kwargs)
@property
def sync_settings_names(self):
"""
Return the list of sync settings this server handles.
"""
return self._sg_jira.sync_settings_names
class RequestHandler(BaseHTTPServer.BaseH... | entity_type = payload.get("entity_type")
entity_key = payload.get("entity_id") | conditional_block | |
test.ts | securely at run time, either from a
* file on you server or using a service like AWS Secrets Manager.
*
* Create a function that fetches the secret key like below,
* and returns it via the callback or as a promise.
* Be sure to decode from base64 if needed.
*/
// tslint:disable-next-line:max-line-length
const T... | body: '"Unauthorised: JsonWebTokenError jwt audience invalid. expected: F42ED082-799F-476B-B77E | testApi(t, api, {
context: { method: 'GET', path: '/greeting' },
headers: { Authorization: 'bearer ' + TOKEN_RS512 }
}, { | random_line_split |
main.rs | /2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
//($id : expr) => ( format!("http://localhost:8000/ws/2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
}
macro_rules! musicbrainz_file {
($id : expr) => ( format!("mb_{}.json", $id))
}
macro_rules! cover_art_url {
($id : expr) => ( format!("http:/... |
}
#[allow(unused_must_use)]
#[allow(dead_code)]
fn save_response_to_file(url : &str, content : &str, provider : &Provider) {
let fs = provider.fs();
let id = provider.extract_id(url);
fs.store(&provider.format_file_name(&id), content);
}
trait Meshup {
fn artist_resource_by_id (&self, id : &str) -> Str... | {
std::fs::create_dir_all(Path::new(&self.directory));
let path = Path::new(&self.directory).join(id);
if !path.exists() {
File::create(path)
.and_then(|mut f| f.write_all(content.as_bytes()));
};
} | identifier_body |
main.rs | directory : String
}
#[allow(dead_code)]
#[allow(unused_must_use)]
impl SimpleFs {
fn read(&self, id: String) -> Result<String, TypedIOError> {
std::fs::create_dir_all(Path::new(&self.directory));
let path = Path::new(&self.directory).join(id);
read_resource_from_file(path.as_path())
... | fs | identifier_name | |
main.rs | macro_rules! musicbrainz_file {
($id : expr) => ( format!("mb_{}.json", $id))
}
macro_rules! cover_art_url {
($id : expr) => ( format!("http://coverartarchive.org/release-group/{}", $id) )
}
macro_rules! cover_art_file {
($id : expr) => ( format!("ca_{}.json", $id) )
}
#[allow(dead_code)]
#[allow(unused_must_use)... | ($id : expr) => ( format!("http://musicbrainz.org/ws/2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
//($id : expr) => ( format!("http://localhost:8000/ws/2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
}
| random_line_split | |
memory.rs | .
pub const DOOR_APPEARANCE: u8 = 0x30;
pub const WALL_APPEARANCE: u8 = 0x31;
pub const FLOOR_COLOR: u8 = 0x32;
// u8 to add/subtract from depth when stairs are used; normally 1.
pub const STAIRS_DELTA: u8 = 0x33;
// u8 to add to timers each turn if non-zero; normally 0xff.
pub const TIMER_DELTA: u8 = 0x34;
// s8 to... | world.player.timer_delta = value,
DAMAGE_OFFSET =>
world.player.damage_offset = unsafe { transmute(value) },
0x36 =>
// TODO: ???
{},
0x37 =>
// TODO: ???
{},
TEXT_SYNC =>
world.player.text_sync = val... |
STAIRS_DELTA =>
world.player.stairs_delta = value,
TIMER_DELTA => | random_line_split |
memory.rs | .
pub const DOOR_APPEARANCE: u8 = 0x30;
pub const WALL_APPEARANCE: u8 = 0x31;
pub const FLOOR_COLOR: u8 = 0x32;
// u8 to add/subtract from depth when stairs are used; normally 1.
pub const STAIRS_DELTA: u8 = 0x33;
// u8 to add to timers each turn if non-zero; normally 0xff.
pub const TIMER_DELTA: u8 = 0x34;
// s8 to... | (world: &World, address: u8) -> u8 {
match address {
PLAYER_APPEARANCE =>
world.player_appearance_byte,
_ if address >= PLAYER_NAME && address < MONSTERS =>
world.player.name[(address - PLAYER_NAME) as usize],
_ if address >= MONSTERS && address < SPELL_MEMORY => {
... | peek | identifier_name |
memory.rs | .
pub const DOOR_APPEARANCE: u8 = 0x30;
pub const WALL_APPEARANCE: u8 = 0x31;
pub const FLOOR_COLOR: u8 = 0x32;
// u8 to add/subtract from depth when stairs are used; normally 1.
pub const STAIRS_DELTA: u8 = 0x33;
// u8 to add to timers each turn if non-zero; normally 0xff.
pub const TIMER_DELTA: u8 = 0x34;
// s8 to... | monster.venomous = value & 0b0010 != 0;
monster.corrupted = value & 0b0001 != 0;
},
MONSTER_POSITION => monster.position = Point::of_byte(value),
MONSTER_HP => monster.hp = value,
_ => unreachable!()
}... | {
match address {
PLAYER_APPEARANCE => {
let old_sprite = Sprite::of_byte(world.player_appearance_byte, true);
let new_sprite = Sprite::of_byte(value, true);
report_player_appearance_change(world, old_sprite, new_sprite);
world.player_appearance_byte = value;
... | identifier_body |
client.rs | vy", format!("{}", x.v.1)),
("status", params_to_json(&x.status)),
("heat", format!("{}", x.heat)),
("max_heat", format!("{}", x.max_heat)),
("max_accelarate", format!("{}", x.max_accelarate)),
("commands", format!("[{}]", commands.connect(","))),
])
}
#[derive(Debug, Clone)]
pub enum Command {
Accelerate(... | at!(
"[3, {}, [{}, {}, {}, {}]]",
self.player_key, energy, power, cool, life
));
parse(resp)
}
pub fn command(&self, cs: &[ | identifier_body | |
client.rs | for c in &x.commands {
commands.push(command_to_json(&c));
}
map_to_json(vec![
("role", format!("{}", x.role)),
("x", format!("{}", x.pos.0)),
("y", format!("{}", x.pos.1)),
("vx", format!("{}", x.v.0)),
("vy", format!("{}", x.v.1)),
("status", params_to_json(&x.status)),
("heat", format!("{}", x.hea... | {
if let Ok(_) = env::var("JUDGE_SERVER") {
return;
}
let t = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(t) => t.as_nanos(),
_ => 0,
};
let msg = format!("###GUI\t{}\t{}\t{}\t{}\n", t, self.player_key, name, msg);
let mut printed = false;
if let Some(f) = &self.file {
... | tr) | identifier_name |
client.rs | e[3]), get_num(&e[4])))
},
),
3 => {
let params = get_list(&e[1])
.unwrap()
.into_iter()
.map(|e| get_num(&e))
.collect::<Vec<_>>();
Command::Split(
-1,
Params {
energy: params[0],
power: params[1],
cool: params[2],
life: params[3],
},
)
... | let max_accelarate = get_num(&s[7]);
// [1, 1, [256, 1, [448, 2, 128], [16, 128], []], [1, [16, 128], [[[1, 0, <34, -46>, <0, 2>, [445, 0, 0, 1], 8, 128, 2], [[0, <0, -1>]]], [[0, 1, <-34, 48>, <0, 0>, [445, 0, 0, 1], 8, 128, 2], [[0, <0, -1>]]]]]] | random_line_split | |
xds.go | or when the xDS
// server does not return any security configuration. Attempts to create
// client credentials without a fallback credentials will fail.
FallbackCreds credentials.TransportCredentials
}
// NewClientCredentials returns a new client-side transport credentials
// implementation which uses xDS APIs to ... | (opts ClientOptions) (credentials.TransportCredentials, error) {
if opts.FallbackCreds == nil {
return nil, errors.New("missing fallback credentials")
}
return &credsImpl{
isClient: true,
fallback: opts.FallbackCreds,
}, nil
}
// credsImpl is an implementation of the credentials.TransportCredentials
// inter... | NewClientCredentials | identifier_name |
xds.go | or when the xDS
// server does not return any security configuration. Attempts to create
// client credentials without a fallback credentials will fail.
FallbackCreds credentials.TransportCredentials
}
// NewClientCredentials returns a new client-side transport credentials
// implementation which uses xDS APIs to ... |
return nil
}
func (hi *HandshakeInfo) makeTLSConfig(ctx context.Context) (*tls.Config, error) {
hi.mu.Lock()
// Since the call to KeyMaterial() can block, we read the providers under
// the lock but call the actual function after releasing the lock.
rootProv, idProv := hi.rootProvider, hi.identityProvider
hi.m... | {
return errors.New("xds: CertificateProvider to fetch identity certificate is missing, cannot perform TLS handshake. Please check configuration on the management server")
} | conditional_block |
xds.go | target or when the xDS
// server does not return any security configuration. Attempts to create
// client credentials without a fallback credentials will fail.
FallbackCreds credentials.TransportCredentials
}
// NewClientCredentials returns a new client-side transport credentials
// implementation which uses xDS A... |
// handshakeAttrKey is the type used as the key to store HandshakeInfo in
// the Attributes field of resolver.Address.
type handshakeAttrKey struct{}
// SetHandshakeInfo returns a copy of addr in which the Attributes field is
// updated with hInfo.
func SetHandshakeInfo(addr resolver.Address, hInfo *HandshakeInfo) re... | // interface which uses xDS APIs to fetch its security configuration.
type credsImpl struct {
isClient bool
fallback credentials.TransportCredentials
} | random_line_split |
xds.go | or when the xDS
// server does not return any security configuration. Attempts to create
// client credentials without a fallback credentials will fail.
FallbackCreds credentials.TransportCredentials
}
// NewClientCredentials returns a new client-side transport credentials
// implementation which uses xDS APIs to ... |
// credsImpl is an implementation of the credentials.TransportCredentials
// interface which uses xDS APIs to fetch its security configuration.
type credsImpl struct {
isClient bool
fallback credentials.TransportCredentials
}
// handshakeAttrKey is the type used as the key to store HandshakeInfo in
// the Attribut... | {
if opts.FallbackCreds == nil {
return nil, errors.New("missing fallback credentials")
}
return &credsImpl{
isClient: true,
fallback: opts.FallbackCreds,
}, nil
} | identifier_body |
oscillator.py | 2 * pi * c / (lamp * 1e-9) + Omega
lami = 1e9 * 2 * pi * c / (omegai)
WDMS_pars = ([lamp, lams], # WDM up downs in wavelengths [m]
[lami, lams],
[lami, lamp],
[lami, lams])
WDM_vec = [WDM(i[0], i[1], sim_wind.fv, c,fopa)
... | create_file_structure(kk)
_temps = create_destroy(inside_var, str(kk))
_temps.prepare_folder()
large_dic['lams'] = lams[kk]
large_dic['master_index'] = kk
large_dic[outside_var_key] = variable
if profiler_bool:
for i in range(len(D_ins)):
form... | conditional_block | |
oscillator.py |
U_original_pump = np.copy(U)
# Pass the original pump through the WDM1, port1 is in to the loop, port2
noise_new = noise_obj.noise_func_freq(int_fwm, sim_wind)
u, U = WDM_vec[0].pass_through((U, noise_new))[0]
ro = -1
t_total = 0
factors_xpm, factors_fwm,gama,tsh, w_tiled = \
... | random_line_split | ||
oscillator.py | er(index, int_fwm, sim_wind, u, U, P0_p1,
P0_s, f_p, f_s, ro, mode_names, master_index, str(ro) + '3', pulse_pos_dict[3], D_pic[3], plots)
# Splice7 after WDM2 for the signal
noise_new = noise_obj.noise_func_freq(int_fwm, sim_wind)
(u, U) = splicers_vec[2].pass_through(
... | "-----------------------------Stable parameters----------------------------"
# Number of computing cores for sweep
num_cores = arguments_determine(1)
# maximum tolerable error per step in integration
maxerr = 1e-13
ss = 1 # includes self steepening term
Df_ba... | identifier_body | |
oscillator.py | ami = 1e9 * 2 * pi * c / (omegai)
WDMS_pars = ([lamp, lams], # WDM up downs in wavelengths [m]
[lami, lams],
[lami, lamp],
[lami, lams])
WDM_vec = [WDM(i[0], i[1], sim_wind.fv, c,fopa)
for i in WDMS_pars] # WDM up downs in w... | __init__ | identifier_name | |
server.go | , map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
//GetReper recupera il reperibile attuale per la piattaforma
//pass... | tp.ResponseWriter, r *http.Request) {
//Crea p come tipo Notifica con i suoi structs
var p Notifica
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&p); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
//fmt.Println(p) //debug
ho... | eNotificaNoVoiceCall(w ht | identifier_name |
server.go | ")
w.WriteHeader(code)
w.Write(response)
}
//GetReper recupera il reperibile attuale per la piattaforma
//passata come argomento
func GetReper(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
w.Header().Set("Expires", time.Unix(0, 0).Format(http.TimeFormat))... | random_line_split | ||
server.go | ulare := r.PostFormValue("cellulare")
piattaforma := r.PostFormValue("piattaforma")
oggi := time.Now().Format("20060102")
err := reperibili.AddRuota(nome, cognome, cellulare, piattaforma, oggi, "gruppo6")
if err != nil {
fmt.Println("errorone", err.Error(), cellulare)
return
}
fmt.Println("inserito reperibi... | a := time.Now()
giorno := ora.Weekday()
//Partiamo che non siamo in FOB
ok = false
switch giorno {
//Se è sabato siamo in fob
case time.Saturday:
//fmt.Println("E' sabato")
ok = true
//Se è domenica siamo in fob
case time.Sunday:
//fmt.Println("E' Domenica")
ok = true
//Se invece è un giorno feriale d... | identifier_body | |
server.go | allora esce
tot := 1800 ///1800 secondi uguale mezz'ora
if lastint+(tot) > int(oraepoch) {
err = fmt.Errorf("Troppe chiamate al reperibile per %s, è permessa una sola chiamata ogni %d secondi", piattaforma, tot)
return err
}
return nil
}
//CreateNotificaNoVoiceCall riceve gli alerts dei nagios
func CreateNoti... | orf("Cellulare con poche cifre: %v", len(value))
log.Println(err.Error())
return "", err
}
//cell10cifre pr | conditional_block | |
mod.rs | found that certain wavelengths of light, which are usually absorbed by water,
//! weakened when the planet was in the way, indicating not only does K2-18b have an atmosphere, but the atmosphere
//! contains water in vapour form. The team from UCL then analyzed the Montreal team's data using their own software
//! and ... | //! ```ignore
//! # use rust_bert::pipelines::sequence_classification::Label;
//! let output = [
//! [
//! Label {
//! text: "politics".to_string(),
//! score: 0.972,
//! id: 0,
//! sentence: 0,
//! },
//! Label {
//! text: "public ... | //! # Ok(())
//! # }
//! ```
//!
//! outputs: | random_line_split |
backfill.py | # Finished iterating over all available accounts
break
# Decode account
path_to_leaf, address_hash_nibbles, encoded_account = next_account_info
account = rlp.decode(encoded_account, sedes=Account)
# Iterate over all missing hashes of... | # 2. Look for more missing nodes in neighboring accounts and their storage, etc.
#
# 1 and 2 are a little more cleanly handled outside this iterator, so we just
# exit and let the caller deal with it.
return
async def _missing_byte... | #
# In response to these situations, we might like to:
# 1. Debug log? | random_line_split |
backfill.py | # Finished iterating over all available accounts
break
# Decode account
path_to_leaf, address_hash_nibbles, encoded_account = next_account_info
account = rlp.decode(encoded_account, sedes=Account)
# Iterate over all missing hashes of... | (
self,
address_hash_nibbles: Nibbles,
account: Account,
starting_main_root: Hash32) -> AsyncIterator[TrackedRequest]:
storage_node_iterator = self._missing_storage_hashes(
address_hash_nibbles,
account.storage_root,
starting_m... | _missing_subcomponent_hashes | identifier_name |
backfill.py | explicitly marked for review again. The
hash/prefix will be marked for review asking a peer for the data.
Will exit when all known node hashes are already actively being
requested, or if there are no more missing nodes.
"""
if storage_root == BLANK_NODE_HASH:
# Not... | active_storage_completion = sum(
self._complete_trie_fraction(store_tracker)
for store_tracker in self._storage_trackers.values()
) / num_storage_trackers | conditional_block | |
backfill.py | ening_queue.readd_peasant(peer, GAP_BETWEEN_TESTS)
self._insert_results(request_hashes, nodes)
finally:
for request in request_data:
request.tracker.mark_for_review(request.prefix)
def _insert_results(
self,
requested_hashes: Tuple[Hash32, ...... | def __init__(self) -> None:
self._trie_fog = fog.HexaryTrieFog()
self._active_prefixes: Set[Nibbles] = set()
# cache of nodes used to speed up trie walking
self._node_frontier_cache = fog.TrieFrontierCache()
def mark_for_review(self, prefix: Nibbles) -> None:
# Calling this... | identifier_body | |
copy_up.go | file is
// written to.
//
// Lock ordering: Dirent.mu -> Inode.overlay.copyMu -> Inode.mu.
//
// Caveats:
//
// If any step in copying up a file fails, copyUp cleans the upper
// filesystem of any partially up-to-date file. If this cleanup fails,
// the overlay may be in an unacceptable, inconsistent state, so copyU... | {
// Remember which mappings we added so we can remove them on failure.
allAdded := make(map[memmap.MappableRange]memmap.MappingsOfRange)
for seg := next.Inode.overlay.mappings.FirstSegment(); seg.Ok(); seg = seg.NextSegment() {
added := make(memmap.MappingsOfRange)
for m := range seg.Value() {
if err :... | conditional_block | |
copy_up.go | upper
// filesystem.
//
// Synchronization:
//
// copyUp synchronizes with rename(2) using renameMu to ensure that
// parentage does not change while a file is being copied. In the context
// of rename(2), copyUpLockedForRename should be used to avoid deadlock on
// renameMu.
//
// The following operations synchroni... |
// copyUpLocked creates a copy of next in the upper filesystem of parent.
//
// copyUpLocked must be called with d.Inode.overlay.copyMu locked.
//
// Returns a generic error on failure.
//
// Preconditions:
// - parent.Inode.overlay.upper must be non-nil.
// - next.Inode.overlay.copyMu must be locked writable.
// - n... | {
// Fail fast on Inode types we won't be able to copy up anyways. These
// Inodes may block in GetFile while holding copyMu for reading. If we
// then try to take copyMu for writing here, we'd deadlock.
t := d.Inode.overlay.lower.StableAttr.Type
if t != RegularFile && t != Directory && t != Symlink {
return sys... | identifier_body |
copy_up.go | the upper
// filesystem.
//
// Synchronization:
//
// copyUp synchronizes with rename(2) using renameMu to ensure that
// parentage does not change while a file is being copied. In the context
// of rename(2), copyUpLockedForRename should be used to avoid deadlock on
// renameMu.
//
// The following operations synch... | if err != nil {
log.Warningf("copy up failed to read symlink value: %v", err)
return syserror.EIO
}
if err := parentUpper.CreateLink(ctx, root, link, next.name); err != nil {
log.Warningf("copy up failed to create symlink: %v", err)
return syserror.EIO
}
childUpper, err := parentUpper.Lookup(ctx, ... | link, err := childLower.Readlink(ctx) | random_line_split |
copy_up.go | d is in the upper filesystem.
return nil
}
d.Inode.overlay.copyMu.RUnlock()
// Find the next component to copy up. We will work our way
// down to the last component of d and finally copy it.
next := findNextCopyUp(ctx, d)
// Attempt to copy.
if err := doCopyUp(ctx, next); err != nil {
return err... | copyContentsLocked | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.