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
nc_read_functions.py
= varObj[logicSlices] if (len(ncDims) == 3) and (stageredDim > 0): if stageredDim == 1: varData = (varData[:, 0:-1, :] + varData[:, 1:, :]) * 0.5 elif stageredDim == 2: varData = (varData[:, :, 0:-1] + varData[:, :, 1:]) * 0.5 elif (len(ncDims) == 4) and (stageredDim >...
(ncfid, iTimes, iBT, iSN, iWE): ''' Memory efficient function to extract the height (averaged in time) of WRF output The height is provided in 3D (i.e. bottom-top, north-south, west-east) Parameters ---------- ncfid : file id file of the netcdf. iTimes : int, logic index of the times to extract form the ...
get_nc_coordinates
identifier_name
nc_read_functions.py
= (1 / fc) * getVarEff(ncfid, 'RV_TEND_PGF', iTimes, iBT, iSN, iWE) dOut['UADV'] = (1 / fc) * getVarEff(ncfid, 'RU_TEND_ADV', iTimes, iBT, iSN, iWE) dOut['VADV'] = (1 / fc) * getVarEff(ncfid, 'RV_TEND_ADV', iTimes, iBT, iSN, iWE) dOut['POT_ADV'] = getVarEff(ncfid, 'T_TEND_ADV', iTim...
lat = ncfid.variables.get('XLAT')[0, :, 0] lon = ncfid.variables.get('XLONG')[0, 0, :] # makes sure central box coordinates lie inside wrf domain box if (min(abs(lat - lat_s)) > max(np.diff(lat))) | (min(abs(lon - lon_s)) > max(np.diff(lon))): raise Exception("ERROR: lat | lon chosen is outside wrf...
identifier_body
nc_read_functions.py
elif iStr.startswith('west'): logicSlices.append(iWE) # Extract and unstager the data varData = varObj[logicSlices] if (len(ncDims) == 3) and (stageredDim > 0): if stageredDim == 1: varData = (varData[:, 0:-1, :] + varData[:, 1:, :]) * 0.5 elif stag...
logicSlices.append(iSN)
conditional_block
nc_read_functions.py
= varObj[logicSlices] if (len(ncDims) == 3) and (stageredDim > 0): if stageredDim == 1: varData = (varData[:, 0:-1, :] + varData[:, 1:, :]) * 0.5 elif stageredDim == 2: varData = (varData[:, :, 0:-1] + varData[:, :, 1:]) * 0.5 elif (len(ncDims) == 4) and (stageredDim >...
iWE : int CENTERED (i.e. unstaggered) indexes of desired weast-east coordinates. Returns ------- out : ndarray numpy array with the height above sea level ''' nz = len(iBT) + 1 ltmp = getVarEff(ncfid, 'XLAT', iTimes, iBT, iSN, iWE).mean(axis=0) LAT = np.tile(ltmp, (nz, 1, 1)) ltmp = getVarE...
iSN : int CENTERED (i.e. unstaggered) indexes of desired south-north coordinates.
random_line_split
types.rs
pub structural_type: StructuralType, } /// Represents a structural type in a WebAssembly module. #[derive(Debug, Clone)] pub enum StructuralType { /// The type is for a function. Func(FuncType), /// The type is for an array. Array(ArrayType), /// The type is for a struct. Struct(StructType)...
/// The list of supertype indexes. As of GC MVP, there can be at most one supertype. pub supertype_idx: Option<u32>, /// The structural type of the subtype.
random_line_split
types.rs
/// Represents a type of an array in a WebAssembly module. #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct ArrayType(pub FieldType); /// Represents a type of a struct in a WebAssembly module. #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct StructType { /// Struct fields. pub fields: Box<[FieldT...
{ /// The `i8` type. I8, /// The `i16` type. I16, /// A value type. Val(ValType), } /// The type of a core WebAssembly value. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)] pub enum ValType { /// The `i32` type. I32, /// The `i64` type. I64, /// The `f3...
StorageType
identifier_name
types.rs
I32, /// The `i64` type. I64, /// The `f32` type. F32, /// The `f64` type. F64, /// The `v128` type. /// /// Part of the SIMD proposal. V128, /// A reference type. /// /// The `funcref` and `externref` type fall into this category and the full /// generalization ...
{ self.bytes.push(0x5f); fields.len().encode(&mut self.bytes); for f in fields.iter() { self.field(&f.element_type, f.mutable); } self.num_added += 1; self }
identifier_body
bid.rs
re, } impl Target { /// Returns the score this target would give on success. pub fn multiplier(self) -> i32 { match self { Target::Prise => 1, Target::Garde => 2, Target::GardeSans => 4, Target::GardeContre => 6, } } pub fn to_str(self) -...
(&self) -> &Vec<cards::Hand> { &self.players } /// The current player passes his turn. /// /// Returns the new auction state : /// /// * `AuctionState::Cancelled` if all players passed /// * `AuctionState::Over` if 5 players passed in a row /// * The previous state otherwise ...
hands
identifier_name
bid.rs
re, } impl Target { /// Returns the score this target would give on success. pub fn multiplier(self) -> i32 { match self { Target::Prise => 1, Target::Garde => 2, Target::GardeSans => 4, Target::GardeContre => 6, } } pub fn to_str(self) -...
Ok(()) } fn get_player_status(&self, pos: pos::PlayerPos) -> BidStatus { self.players_status[pos.to_n()] } fn set_player_status(&mut self, pos: pos::PlayerPos, status: BidStatus) { self.players_status[pos.to_n()] = status; } /// Returns the player that is expected to...
{ if target.multiplier() <= contract.target.multiplier() { return Err(BidError::NonRaisedTarget); } }
conditional_block
bid.rs
re, } impl Target { /// Returns the score this target would give on success. pub fn multiplier(self) -> i32 { match self { Target::Prise => 1, Target::Garde => 2, Target::GardeSans => 4, Target::GardeContre => 6, } } pub fn to_str(self) -...
} impl Auction { /// Starts a new auction, starting with the player `first`. pub fn new(first: pos::PlayerPos) -> Self { let count = first.count as usize; let (hands, dog) = super::deal_hands(count); Auction { contract: None, players_status: vec![BidStatus::Todo...
{ match *self { BidError::AuctionClosed => write!(f, "auctions are closed"), BidError::TurnError => write!(f, "invalid turn order"), BidError::NonRaisedTarget => write!(f, "bid must be higher than current contract"), BidError::AuctionRunning => write!(f, "the auct...
identifier_body
bid.rs
re, } impl Target { /// Returns the score this target would give on success. pub fn multiplier(self) -> i32 { match self { Target::Prise => 1, Target::Garde => 2, Target::GardeSans => 4, Target::GardeContre => 6, } } pub fn to_str(self) -...
let contract = Contract::new(pos, target, slam); self.contract = Some(contract); self.set_player_status(pos, BidStatus::Bid); // If we're all the way to the top, there's nowhere else to go if self.no_player_left() || target == Target::GardeContre { self.state = Auct...
// Reset previous bidder status if let Some(contract) = self.contract.clone() { self.set_player_status(contract.author, BidStatus::Todo); }
random_line_split
bot.py
ules and enjoy your stay. Do d.help to check out the bot'.format(member, server)) kats = bot.get_channel('313863292126756864') if member.server.id == '294262760752152576': await bot.send_message(kats, '{0.mention} Welcome to **Dragons and Kats**! Have a great time here and enjoy yourselves!!!:wink: !'.form...
to_code_block
identifier_name
bot.py
(game=discord.Game(name='Currently WIP | Darkness')) await asyncio.sleep(10) await bot.change_presence(game=discord.Game(name='d.support | d.invite')) await asyncio.sleep(25) @bot.command(pass_context=True) async def help(ctx): await bot.delete_messag...
kats = bot.get_channel('313863292126756864') if member.server.id == '294262760752152576': await bot.send_message(kats, '{0.mention} Welcome to **Dragons and Kats**! Have a great time here and enjoy yourselves!!!:wink: !'.format(member)) else: print('Member joined {}, but message not sent'.forma...
await bot.send_message(darkness, 'Welcome {0.mention} to {}. Please read #info-and-rules and enjoy your stay. Do d.help to check out the bot'.format(member, server))
conditional_block
bot.py
servers = len(bot.servers) embed.add_field(name='Author', value='<@300396755193954306>') embed.add_field(name='Servers', value=servers) embed.add_field(name='Prefix', value='d.') embed.set_footer(text='Powered by discord.py') embed.set_thumbnail(url='http://data.whicdn.com/i...
x = await bot.say('```py\n%s\n```' % value) except: x = await bot.say('```py\n\'Result was too long.\'```') try:
random_line_split
bot.py
.Embed(color=0x00FFFF) em.set_author(name='Help - {}'.format(cmd)) async def send_cmd_help(ctx): if ctx.invoked_subcommand: pages = bot.formatter.format_help_for(ctx, ctx.invoked_subcommand) for page in pages: # page = page.strip('```css').strip('```') await bot.send_m...
dev = '@-= shadeyg56™ =-#1702' user = ctx.message.author await bot.send_message(dev, '{} sent the following message: {}'.format(user, msg)) await bot.say('Your message has been sent. It will be checked by the dev asap. If your message was a troll or you keep resending/spamming a message you will be blacklis...
identifier_body
trigger.go
"TriggerReconcileFailed" triggerUpdateStatusFailed = "TriggerUpdateStatusFailed" subscriptionDeleteFailed = "SubscriptionDeleteFailed" subscriptionCreateFailed = "SubscriptionCreateFailed" ) type reconciler struct { client client.Client dynamicClient dynamic.Interface recorder record.EventRecorder...
(trigger *v1alpha1.Trigger) (*v1alpha1.Trigger, error) { ctx := context.TODO() objectKey := client.ObjectKey{Namespace: trigger.Namespace, Name: trigger.Name} latestTrigger := &v1alpha1.Trigger{} if err := r.client.Get(ctx, objectKey, latestTrigger); err != nil { return nil, err } triggerChanged := false if...
updateStatus
identifier_name
trigger.go
alpha1.Subscription{}} { err = c.Watch(&source.Kind{Type: t}, &handler.EnqueueRequestForOwner{OwnerType: &v1alpha1.Trigger{}, IsController: true}) if err != nil { return nil, err } } // Watch for Broker changes. E.g. if the Broker is deleted and recreated, we need to reconcile // the Trigger again. if err...
{ return r.getChannel(ctx, b, labels.SelectorFromSet(broker.IngressChannelLabels(b))) }
identifier_body
trigger.go
"TriggerReconcileFailed" triggerUpdateStatusFailed = "TriggerUpdateStatusFailed" subscriptionDeleteFailed = "SubscriptionDeleteFailed" subscriptionCreateFailed = "SubscriptionCreateFailed" ) type reconciler struct { client client.Client dynamicClient dynamic.Interface recorder record.EventRecorder...
// Watch Triggers. if err = c.Watch(&source.Kind{Type: &v1alpha1.Trigger{}}, &handler.EnqueueRequestForObject{}); err != nil { return nil, err } // Watch all the resources that the Trigger reconciles. for _, t := range []runtime.Object{&corev1.Service{}, &istiov1alpha3.VirtualService{}, &v1alpha1.Subscription...
{ return nil, err }
conditional_block
trigger.go
"TriggerReconcileFailed" triggerUpdateStatusFailed = "TriggerUpdateStatusFailed" subscriptionDeleteFailed = "SubscriptionDeleteFailed" subscriptionCreateFailed = "SubscriptionCreateFailed" ) type reconciler struct { client client.Client dynamicClient dynamic.Interface recorder record.EventRecorder...
logging.FromContext(ctx).Error("Error reconciling Trigger", zap.Error(reconcileErr)) r.recorder.Eventf(trigger, corev1.EventTypeWarning, triggerReconcileFailed, "Trigger reconciliation failed: %v", reconcileErr) } else { logging.FromContext(ctx).Debug("Trigger reconciled") r.recorder.Event(trigger, corev1.Even...
if reconcileErr != nil {
random_line_split
mod.rs
type Body: MessageBody<B>; /// The type corresponding to this message type. /// /// The value of the "type" field in the ICMP header corresponding to /// messages of this type. const TYPE: I::IcmpMessageType; /// Parse a `Code` from an 8-bit number. /// /// Parse a `Code` from the ...
{ c.add_bytes(src_ip.bytes()); c.add_bytes(dst_ip.bytes()); let icmpv6_len = mem::size_of::<Header<M>>() + message_body.len(); let mut len_bytes = [0; 4]; NetworkEndian::write_u32(&mut len_bytes, icmpv6_len.try_into().ok()?); c.add_bytes(&len_bytes[..]); c.add_byt...
conditional_block
mod.rs
function. If it's called, it // doesn't make sense for the program to continue executing; if we did, // it would cause bugs in the caller. unimplemented!() } } /// An ICMP or ICMPv6 packet /// /// 'IcmpPacketType' is implemented by `Icmpv4Packet` and `Icmpv6Packet` pub trait IcmpPacketType...
new
identifier_name
mod.rs
(Debug)] pub struct OriginalPacket<B>(B); impl<B: ByteSlice + Deref<Target = [u8]>> OriginalPacket<B> { /// Returns the the body of the original packet. pub fn body<I: IcmpIpExt>(&self) -> &[u8] { // TODO(joshlf): Can these debug_asserts be triggered by external input? let header_len = I::heade...
{ type Error = ParseError; fn parse_metadata(&self) -> ParseMetadata {
random_line_split
calc_codon_usage.py
_diff=0.2, group_dpercentile=10, wt_gi='gi|556503834|ref|NC_000913.3|', gi_index=None, verbose=False): #read fasta files seqs = {} if isinstance(fasta, str): gene = "".join(os.path.basename(fasta).split(".")[:-1]) seqs[gene] = read_fasta(fasta) elif isinstance(fasta, (list, tuple)): for path in fasta: gene...
gene_group_labels = ['%05.3f:%05.3f' % (groups[i][0], groups[i][1]) \ if i > 0 else 'ND' for i in range(len(groups))] except IOError: #this is the first run, get general usage info rerun_flag = True groups = ['all'] def get_gene_group(gene): return 0 gene_group_labels = ['all'] except KeyError: ...
if len(seqs[gene]) == 0: return 0 else: x = get_frac_rare(seqs[gene]) for i in range(1, len(groups)): if x >= groups[i][0] and x <= groups[i][1]: return i
identifier_body
calc_codon_usage.py
_diff=0.2, group_dpercentile=10, wt_gi='gi|556503834|ref|NC_000913.3|', gi_index=None, verbose=False): #read fasta files seqs = {} if isinstance(fasta, str): gene = "".join(os.path.basename(fasta).split(".")[:-1]) seqs[gene] = read_fasta(fasta) elif isinstance(fasta, (list, tuple)): for path in fasta: gene...
abundances = {line.split()[0] : float(line.split()[1]) for line in f if len(line) > 1 and line[0] != '#'} except Exception as e: abundances = {} ''' if gi_index != None: with open(gi_index, 'r') as f: gi_index = {line.split()[0] : ' '.join(line.split()[1:]) \ for line in f if len(line) > 1 and lin...
with open(abundances, 'r') as f:
random_line_split
calc_codon_usage.py
elif rare_model == 'cmax_norm': if codon_usage[c] / max(codon_usage[cc] for cc in aa_codons[codon_to_aa[c]]) <= rare_threshold: return True else: return False def calc_codon_usage(fasta, abundances=None, output="", rare_model='no_norm', rare_threshold=0.1, max_len_diff=0.2, group_dpercentile=10, wt_gi='gi|...
return False
conditional_block
calc_codon_usage.py
(codon_usage, rare_model, rare_threshold, c): if rare_model == 'no_norm': if codon_usage[c] <= rare_threshold: return True else: return False elif rare_model == 'cmax_norm': if codon_usage[c] / max(codon_usage[cc] for cc in aa_codons[codon_to_aa[c]]) <= rare_threshold: return True else: return Fal...
israre
identifier_name
remote_cache.rs
_cache_client, headers, platform, cache_read, cache_write, eager_fetch, warnings_behavior, read_errors_counter: Arc::new(Mutex::new(BTreeMap::new())), write_errors_counter: Arc::new(Mutex::new(BTreeMap::new())), }) } /// Create a REAPI `Tree` protobuf for an outp...
else { tree.children.push(directory) } } Ok(Some(tree)) } pub(crate) async fn extract_output_file( root_directory_digest: Digest, file_path: RelativePath, store: &Store, ) -> Result<Option<FileNode>, String> { // Traverse down from the root directory digest to find the dir...
{ tree.root = Some(directory); }
conditional_block
remote_cache.rs
_path: RelativePath, store: &Store, ) -> Result<Option<Tree>, String> { // Traverse down from the root directory digest to find the directory digest for // the output directory. let mut current_directory_digest = root_directory_digest; for next_path_component in directory_path.as_ref().components(...
.map_err(status_to_str)?;
random_line_split
remote_cache.rs
_proto_locally(&self.store, &tree).await?; digests.insert(tree_digest); action_result .output_directories .push(remexec::OutputDirectory { path: output_directory.to_owned(), tree_digest: Some(tree_digest.into()), }); } for output_file in &command.output_...
extract_compatible_request
identifier_name
bare_index.rs
= if !exists { let mut opts = git2::RepositoryInitOptions::new(); opts.external_template(false); let repo = git2::Repository::init_opts(&index.path, &opts)?; { let mut origin_remote = repo .find_remote("origin") .or...
(&mut self) -> Result<(), Error> { { let mut origin_remote = self .rt .repo .find_remote("origin") .or_else(|_| self.rt.repo.remote_anonymous(&self.inner.url))?; origin_remote.fetch( &[ "...
retrieve
identifier_name
bare_index.rs
> { type Item = CrateRef<'a>; fn next(&mut self) -> Option<Self::Item> { while let Some(last) = self.stack.pop() { match last.as_tree() { None => return Some(CrateRef(last)), Some(tree) => { for entry in tree.iter().rev() { ...
{ let krate = repo .crate_("sval") .expect("Could not find the crate sval in the index"); let version = krate .versions() .iter() .find(|v| v.version() == "0.0.1") .expect("Version 0.0.1 of sval does...
identifier_body
bare_index.rs
pub fn with_path(path: PathBuf, url: &str) -> Self { Self { path, url: url.to_owned(), } } /// Creates an index for the default crates.io registry, using the same /// disk location as cargo itself. #[inline] pub fn new_cargo_default() -> Self { //...
/// Creates a bare index at the provided path with the specified repository URL. #[inline]
random_line_split
encode.rs
None => continue, }; for edge in deps.iter() { if let Some(to_depend_on) = lookup_id(edge)? { g.link(id.clone(), to_depend_on); } } } g }; let replacements = { ...
{ let source = if id.source_id().is_path() { None } else { Some(id.source_id().with_precise(None)) }; EncodablePackageId { name: id.name().to_string(), version: id.version().to_string(), source: source, } }
identifier_body
encode.rs
packages = self.package.unwrap_or(Vec::new()); if let Some(root) = self.root { packages.insert(0, root); } packages }; // `PackageId`s in the lock file don't include the `source` part // for workspace members, so we reconstruct proper ids. ...
(s: &str) -> CraftResult<EncodablePackageId> { let regex = Regex::new(r"^([^ ]+) ([^ ]+)(?: \(([^\)]+)\))?$").unwrap(); let captures = regex.captures(s).ok_or_else(|| internal("invalid serialized PackageId"))?; let name = captures.at(1).unwrap(); let version = captures.at(2).unwrap(); ...
from_str
identifier_name
encode.rs
packages = self.package.unwrap_or(Vec::new()); if let Some(root) = self.root { packages.insert(0, root); } packages }; // `PackageId`s in the lock file don't include the `source` part // for workspace members, so we reconstruct proper ids. ...
} } } g }; let replacements = { let mut replacements = HashMap::new(); for &(ref id, ref pkg) in live_pkgs.values() { if let Some(ref replace) = pkg.replace { assert!(pkg.dependencies...
for edge in deps.iter() { if let Some(to_depend_on) = lookup_id(edge)? { g.link(id.clone(), to_depend_on);
random_line_split
MCObserver.py
the job will run interactively in the local directory. If the user wishes to submit the jobs to swif the option "swif=1" must be supplied. # # SWIF DOCUMENTATION: # https://scicomp.jlab.org/docs/swif # https://scicomp.jlab.org/docs/swif-cli # https://scicomp.jlab.org/help/swif/add-job.txt #consider phase! # #########...
runnum=0 runmax=-1 spawnNum=10 numOverRide=False if(len(argv) !=0): numOverRide=True numprocesses_running=subprocess.check_output(["echo `ps all -u "+runner_name+" | grep MCObserver.py | grep -v grep | wc -l`"], shell=True) print(int(numprocesses_ru...
identifier_body
MCObserver.py
wishes to retain the files created by any step you can supply the cleangenr8=0, cleangeant=0, cleanmcsmear=0, or cleanrecon=0 options. By default all but the reconstruction files # are cleaned. # # The reconstruction step is multi-threaded, for this step, if enabled, the script will use 4 threads. This th...
(argv): runnum=0 runmax=-1 spawnNum=10 numOverRide=False if(len(argv) !=0): numOverRide=True numprocesses_running=subprocess.check_output(["echo `ps all -u "+runner_name+" | grep MCObserver.py | grep -v grep | wc -l`"], shell=True) print(in...
main
identifier_name
MCObserver.py
wishes to retain the files created by any step you can supply the cleangenr8=0, cleangeant=0, cleanmcsmear=0, or cleanrecon=0 options. By default all but the reconstruction files # are cleaned. # # The reconstruction step is multi-threaded, for this step, if enabled, the script will use 4 threads. This th...
print(int(numprocesses_running)) if(int(numprocesses_running) <2 or numOverRide): while(runnum<runmax or runmax==-1): runnum=runnum+1 try: queryosgjobs="SELECT
if(len(argv) !=0): numOverRide=True numprocesses_running=subprocess.check_output(["echo `ps all -u "+runner_name+" | grep MCObserver.py | grep -v grep | wc -l`"], shell=True)
random_line_split
MCObserver.py
lddb.jlab.org" dbuser = 'mcuser' dbpass = '' dbname = 'gluex_mc' try: dbcnx=MySQLdb.connect(host=dbhost, user=dbuser, db=dbname) dbcursor=dbcnx.cursor(MySQLdb.cursors.DictCursor) except: print("WARNING: CANNOT CONNECT TO DATABASE. JOBS WILL NOT BE CONTROLLED OR MONITORED") pass runner...
if spawns[i].is_alive(): #print("join "+str(i)) spawns[i].join()
conditional_block
connector.js
Body = "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px black; }" // addStyle(customSelectionStyle); var now = Date.now(); var minusDay = 0.5 ...
timeline = new vis.Timeline(container); timeline.setOptions(options); timeline.setGroups(groups); timeline.setItems(items); timeline.on("click", (e) => { connector.onClick(e) }); timeline.on("dblclick", (e) => { connector.onDoubleClick(e); }); timeline.on('sel...
}; // create a Timeline var container = document.getElementById("visualization");
random_line_split
connector.js
= "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px black; }" // addStyle(customSelectionStyle); var now = Date.now(); var minusDay = 0.5 ...
var selectedStyle = styletags[i].innerHTML; // console.log(styletags[i].innerHTML) if(selectedStyle.includes(styleName)){ // console.log("Contains" +styletags[i].innerHTML +"||"); return true; } else{ ...
++) {
identifier_name
connector.js
= "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px black; }" // addStyle(customSelectionStyle); var now = Date.now(); var minusDay = 0.5 ...
s = data.usesItems console.log("Items", items); groups = data.usesGroups lastSelectedItem = data.lastSelectedItem windowStartTime = data.windowStartTime windowEndTime = data.windowEndTime console.log("State data: ", data); items.forE...
var selectedStyle = styletags[i].innerHTML; // console.log(styletags[i].innerHTML) if(selectedStyle.includes(styleName)){ // console.log("Contains" +styletags[i].innerHTML +"||"); return true; } else{ // consol...
identifier_body
connector.js
= "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px black; }" // addStyle(customSelectionStyle); var now = Date.now(); var minusDay = 0.5 ...
entHeight - leftHeight); if (targetOffset + height > currentScrollHeight + leftHeight || targetOffset < currentScrollHeight) { animateScroll(currentScrollHeight, offset, duration, timeline); timeline.setSelection(eventId); timeline.focus(eventId); } }; ...
ight + leftHeight) { offset += eventTop(event, group) + height - leftHeight + timeline.itemSet.options.margin.item.vertical; } } offset = Math.min(offset, cont
conditional_block
test_conv_layer.py
result = activation(result) # expand dimensions from K, time_steps, batch_size to (K, 1, time_steps, 1, batch_size) result = np.expand_dims(np.expand_dims(result, axis=1), axis=3) return result # TODO: Remove these to conftest.py @pytest.fixture(params=[1]) def input_size(request): return request...
for k in range(K): for n in range(batch_size): result[k, t, n] = np.sum(inputs[:, t:t + filter_width, n] * filters[:, :, k])
conditional_block
test_conv_layer.py
time_steps, batch_size to (K, 1, time_steps, 1, batch_size) result = np.expand_dims(np.expand_dims(result, axis=1), axis=3) return result # TODO: Remove these to conftest.py @pytest.fixture(params=[1]) def input_size(request): return request.param @pytest.fixture(params=[16]) def output_size(request): ...
@pytest.mark.xfail(reason='1d conv not supported') def test_axis_preservation(conv1d_placeholder, output_size): """ Test that axes into a conv are the same as axes out""" conv_layer = Convolution((3, output_size), lambda x: 1) output = conv_layer(conv1d_placeholder) assert output.axes == conv1d_place...
""" Test that 'same' always results in out_size = np.ceil(in_size / stride) """ conv_layer = Convolution((3, output_size), lambda x: 1, strides=stride, padding="same") output = conv_layer(conv1d_placeholder) output_width = output.axes.find_by_name("W")[0].length assert output_width == np.ceil(width / fl...
identifier_body
test_conv_layer.py
time_steps, batch_size to (K, 1, time_steps, 1, batch_size) result = np.expand_dims(np.expand_dims(result, axis=1), axis=3) return result # TODO: Remove these to conftest.py @pytest.fixture(params=[1]) def input_size(request): return request.param @pytest.fixture(params=[16]) def output_size(request): ...
(dilation): """Test that the dilated convolution layer output matches expected. This test compares the maximum output value to an expected max output value. The expected value is computed based on the dilation parameter. The test also checks that the output size matches the expected size based on the di...
test_dilated_conv
identifier_name
test_conv_layer.py
, time_steps, batch_size to (K, 1, time_steps, 1, batch_size) result = np.expand_dims(np.expand_dims(result, axis=1), axis=3) return result # TODO: Remove these to conftest.py @pytest.fixture(params=[1]) def input_size(request): return request.param @pytest.fixture(params=[16]) def output_size(request):...
N_filters = 1 image_channels = 3 model = Sequential([Convolution((conv_size, conv_size, N_filters), filter_init=ConstantInit(val=init_val), padding=pad, dilation=dilation)]) X = np.ones(shape=(batch_size, 3, image_size, image_size))...
conv_size = 3 pad = 3
random_line_split
controller.go
interested in, as well // as syncing informer caches and starting workers. It will block until stopCh // is closed, at which point it will shutdown the workqueue and wait for // workers to finish processing their current work items. func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error { defer utilr...
).Set(float64(idleWorkers)) workersCurrent.WithLabelValues( name, namespace, queueName,
random_line_split
controller.go
an event recorder for recording Event resources to the // Kubernetes API. recorder record.EventRecorder // defaultMaxDisruption // it is the default value for the maxDisruption in the WPA spec. // This specifies how much percentage of pods can be disrupted in a // single scale down acitivity. // Can be expresse...
else if err != nil { return err } currentWorkers = *deployment.Spec.Replicas availableWorkers = deployment.Status.AvailableReplicas } else if replicaSetName != "" { // Get the ReplicaSet with the name specified in WorkerPodAutoScaler.spec replicaSet, err := c.replicaSetList
{ return fmt.Errorf("deployment %s not found in namespace %s", deploymentName, workerPodAutoScaler.Namespace) }
conditional_block
controller.go
an event recorder for recording Event resources to the // Kubernetes API. recorder record.EventRecorder // defaultMaxDisruption // it is the default value for the maxDisruption in the WPA spec. // This specifies how much percentage of pods can be disrupted in a // single scale down acitivity. // Can be expresse...
(ctx context.Context) bool { obj, shutdown := c.workqueue.Get() if shutdown { return false } // We wrap this block in a func so we can defer c.workqueue.Done. err := func(obj interface{}) error { // We call Done here so the workqueue knows we have finished // processing this item. We also must remember to ...
processNextWorkItem
identifier_name
controller.go
an event recorder for recording Event resources to the // Kubernetes API. recorder record.EventRecorder // defaultMaxDisruption // it is the default value for the maxDisruption in the WPA spec. // This specifies how much percentage of pods can be disrupted in a // single scale down acitivity. // Can be expresse...
workerPodAutoScalersLister: workerPodAutoScalerInformer.Lister(), workerPodAutoScalersSynced: workerPodAutoScalerInformer.Informer().HasSynced, workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "WorkerPodAutoScalers"), recorder: recorder,...
{ // Create event broadcaster // Add sample-controller types to the default Kubernetes Scheme so Events can be // logged for sample-controller types. utilruntime.Must(samplescheme.AddToScheme(scheme.Scheme)) klog.V(4).Info("Creating event broadcaster") eventBroadcaster := record.NewBroadcaster() eventBroadcaste...
identifier_body
generate.py
float, help='Threshold for tag binarization') parser.add_argument('-s', action='store', dest='lstm_size', type= int, help='Number of hidden units in LSTM model') parser.add_argument('-m', action='store', dest='model_file', help='Model File Name') # parser.add_argument('-d', action='store', dest='gpu', help='GPU to use...
return prev_words_input def beam_search(captioning_model, prev_words_input, other_inputs, k): top_k_predictions = [copy.deepcopy(prev_words_input) for _ in range(k)] top_k_score = np.array([[0.0]*top_k_predictions[0].shape[0]]*k) # First Iteration predictions = captioning_model.predict(oth...
predictions = captioning_model.predict(other_inputs + [prev_words_input]) for idx,video in enumerate(test): prev_words_input[idx][itr+1] = np.argmax(predictions[idx])
conditional_block
generate.py
float, help='Threshold for tag binarization') parser.add_argument('-s', action='store', dest='lstm_size', type= int, help='Number of hidden units in LSTM model') parser.add_argument('-m', action='store', dest='model_file', help='Model File Name') # parser.add_argument('-d', action='store', dest='gpu', help='GPU to use...
TAG_TYPE = results.tag_type THRESHOLD = results.tag_threshold LSTM_SIZE = results.lstm_size # Load single frame feature vectors and attribute/entity/action vectors if TAG_TYPE == 'predicted': video_entity_vectors = pickle.load(open("../advanced_tag_models/entity_simple_predicted_tags.pickle", "rb")) video_ac...
random_line_split
generate.py
float, help='Threshold for tag binarization') parser.add_argument('-s', action='store', dest='lstm_size', type= int, help='Number of hidden units in LSTM model') parser.add_argument('-m', action='store', dest='model_file', help='Model File Name') # parser.add_argument('-d', action='store', dest='gpu', help='GPU to use...
(captioning_model, prev_words_input, other_inputs): for itr in range(NUM_PREV_WORDS-1): predictions = captioning_model.predict(other_inputs + [prev_words_input]) for idx,video in enumerate(test): prev_words_input[idx][itr+1] = np.argmax(predictions[idx]) return prev_words_input ...
greedy_search
identifier_name
generate.py
float, help='Threshold for tag binarization') parser.add_argument('-s', action='store', dest='lstm_size', type= int, help='Number of hidden units in LSTM model') parser.add_argument('-m', action='store', dest='model_file', help='Model File Name') # parser.add_argument('-d', action='store', dest='gpu', help='GPU to use...
results_folder = "./" # # Load All Captions fname = folder + "cleaned_descriptions.csv" with open(fname) as f: content = f.readlines() all_captions = [(x.strip().split(",")[0],x.strip().split(",")[1]) for x in content] # # Write correct caption file correct_captions = open(results_folder + "annotations/correct...
preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas)
identifier_body
jiayuan.py
,callback=self.get_main_info) def get_main_info(self,response):#解析搜索业面的url #info = response.body.decode("utf-8") #登录后可以查看一下登录响应信息json.loads( # for url in self.start_urls: time.sleep(1) print("当前的url",response.url) print('重新加载url') self.driver.get(response.ur...
item['nation_mate'] = mate_dict['民族'] item['education_mate'] = mate_dict['学历'] item['image_mate'] = mate_dict['相册'] item['marital_status'] = mate_dict['婚姻状况'] item['address_mate'] = mate_dict['居住地'] item['s
mate_dict = parse(i.text) item['person_id_mate'] = person_id item['age_mate'] = mate_dict['年龄'] item['height_mate'] = mate_dict['身高']
random_line_split
jiayuan.py
onnectionPool(host='127.0.0.1',port=6379,db=0,decode_responses=True) #427条记录 r = redis.StrictRedis(connection_pool=pool) name = "jiayuan_main" redis_key = 'jiayuan_main:start_urls' url_base = 'http://search.jiayuan.com/v2/index.php?key=&sex=f&stc=&sn=default&sv=1&p=%s&pt=163649&ft=off&f=select&mt...
pool=redis.C
identifier_name
jiayuan.py
driver.get(login_url) time.sleep(3) driver.find_element_by_id("login_btn").click() driver.find_element_by_id("login_email").clear() driver.find_element_by_id("login_email").send_keys(USER_NAME) #修改为自己的用户名 driver.find_element_by_id("login_password").clear() driver.find_element_by_id("lo...
127.0.0.1',port=6379,db=0,decode_responses=True) #427条记录 r = redis.StrictRedis(connection_pool=pool) name = "jiayuan_main" redis_key = 'jiayuan_main:start_urls' url_base = 'http://search.jiayuan.com/v2/index.php?key=&sex=f&stc=&sn=default&sv=1&p=%s&pt=163649&ft=off&f=select&mt=d' redis_key =...
identifier_body
jiayuan.py
,callback=self.get_main_info) def get_main_info(self,response):#解析搜索业面的url #info = response.body.decode("utf-8") #登录后可以查看一下登录响应信息json.loads( # for url in self.start_urls: time.sleep(1) print("当前的url",response.url) print('重新加载url') self.driver.get(response.ur...
<class 'str'> 年 龄: 26-29岁之间 身 高: 169-185厘米 民 族: 汉族 学 历: 不限 相 册: ...
=url,cookies=self.cookies,callback=self.get_details)#解析人员详细信息 # yield item def get_details(self,response): '''
conditional_block
wxkfmanager.go
码 Redircturl string //公众号授权完成后的回调URL用来接收授权码auth_code Compentauthurl string //当前第三方平台授权移动端连接 AppAuthinfos []APPAuthInfoResp //第三方公众号令牌数组,自动刷新 } //初始化开放平台管理器 func InitWXKFManager(token,appid,EncodingAESKey,appseceret,Redircturl string,refreshAppAuthHanlder func(appauth ...APPAuthInfoResp),AppAuthinfos...
Decrptmsg APPAuthMsg, safe bool) { if CheckSign { if len(responsehandler)>0 { responsehandler[0](Decrptmsg) } } }) context.String(http.StatusOK,"success") } //代公众号实现网页授权 /****************代公众号实现业务*******************/ //1.代公众号调用接口 //获取用户信息 func (wx *WXKFManager)GetUserInfo( authorizer...
l, Orignmsg ReqMsg,
identifier_name
wxkfmanager.go
码获取授权信息 func (wx *WXKFManager) HanleCompentAuth(context * gin.Context, responsehandler func(authinfo APPAuthInfoResp)(redicturl string)){ authcode := context.Query("auth_code") //查询公众号授权第三方平台的权限 wx.getCompentAuthAccesstoken(authcode, func(appAuthInfo APPAuthInfoResp) { wx.AppAuthinfos=append(wx.AppAuthinfos, ap...
AuthResp mapstructure.Dec
conditional_block
wxkfmanager.go
if len(responsehandler)>0 { responsehandler[0](Decrptmsg) } } }) context.String(http.StatusOK,"success") } //代公众号实现网页授权 /****************代公众号实现业务*******************/ //1.代公众号调用接口 //获取用户信息 func (wx *WXKFManager)GetUserInfo( authorizer_access_token,authorizer_appid string ,hanlder ...func...
identifier_body
wxkfmanager.go
授权码 Redircturl string //公众号授权完成后的回调URL用来接收授权码auth_code Compentauthurl string //当前第三方平台授权移动端连接 AppAuthinfos []APPAuthInfoResp //第三方公众号令牌数组,自动刷新 } //初始化开放平台管理器 func InitWXKFManager(token,appid,EncodingAESKey,appseceret,Redircturl string,refreshAppAuthHanlder func(appauth ...APPAuthInfoResp),AppAuthinf...
//获取授权方选项设置信息 func (wx *WXKFManager) GetCompentAuthOptionInfo(authorizer_appid,option_name string,responsehandler ...func(APPOptionResp)) { url :="https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" url =url +wx.Component_access_token POSTJson(url,gin.H{"component_appid": wx.Comp...
random_line_split
technique.rs
(json_file: &Path, rl_file: &Path) -> Result<()> { let config_data = fs::read_to_string("data/config.toml").expect("Cannot read config.toml file"); let config: toml::Value = toml::from_str(&config_data).expect("Invalig config.toml file"); // we use if let for error conversion // we don't use match for ...
translate_file
identifier_name
technique.rs
for better linear reading let json_data = fs::read_to_string(&json_file); if json_data.is_err() { return Err(Error::User(format!("Cannot read file {}", json_file.to_string_lossy()))) } let technique = serde_json::from_str::<Technique>(&json_data.unwrap()); if technique.is_err() { return Err(Error::User...
fn translate_arg(config: &toml::Value, arg: &str) -> Result<String> { let var = match parse_cfstring(arg) { Err(_) => return Err(Error::User(format!("Invalid variable syntax in '{}'", arg))), Ok((_,o)) => o }; map_strings_results(var.iter(), |x| Ok(format!("\"{}\"",x.to_string()?)), ",") }...
// empty string value(vec![CFStringElt::Static("".into())], not(anychar)), )) )(i) }
random_line_split
html5_player.js
}; //getting large screen button only for watch video page if (enlarge_small == 'true') { $('.btmControl').append('<div class="smallscr largescr hbtn" id="largescr" title="Enlarge/Small Size"></div>'); $('#largescr').insertBefore("#fs"); } //Large screen function $(".largescr").click(function() { $(this).t...
{ //before everything get started video.on('loadedmetadata', function() { video[0].currentTime = start_time; video[0].play(); //set video properties $('.loading').fadeOut(500); $('.init').hide(); }); }
identifier_body
html5_player.js
end * ================== */ //CONTROLS EVENTS //video screen and play button clicked video.on('click', function() { playpause(); } ); $('.btnPlay').on('click', function() { playpause(); } ); $('.caption').on('click', function() { playpause(); } ); $('.init').on('click', function() { playpause(); } ); ...
}; $( "#replay_v" ).click(function() { video[0].play(); $('#opacity').hide(); $('#related_1').hide(); $('.control').show(); $('.caption').show(); $('#web').show(); //showing pause icon by before video load $('.btnPlay').addClass('paused'); }); $( "#cancel_v" ).click(fu...
{ $('.init').show(); $('.btnPlay').removeClass('paused'); video[0].pause(); _pause = true; }
conditional_block
html5_player.js
} else { $('.init').show(); $('.btnPlay').removeClass('paused'); video[0].pause(); _pause = true; } }; $( "#replay_v" ).click(function() { video[0].play(); $('#opacity').hide(); $('#related_1').hide(); $('.control').show(); $('.caption').show(); $('#web').show(); ...
startFocusOut
identifier_name
html5_player.js
//VIDEO EVENTS //video canplay event video.on('canplay', function() { $('.loading').fadeOut(100); }); //video canplaythrough event //solve Chrome cache issue var completeloaded = false; video.on('canplaythrough', function() { completeloaded = true; }); //video ended event video.on('ended', function() ...
if(!jsonData["360"]) {
random_line_split
SignalDef.rs
pub const SYS_SECCOMP: i32 = 1; // TRAP_* codes are only meaningful for SIGTRAP. // TRAP_BRKPT indicates a breakpoint trap. pub const TRAP_BRKPT: i32 = 1; } pub const UC_FP_XSTATE: u64 = 1; pub const UC_SIGCONTEXT_SS: u64 = 2; pub const UC_STRICT_RESTORE_SS: u64 = 4; // https://elixir.bootlin.com/linux...
{ return idx }
conditional_block
SignalDef.rs
3; // CLD_TRAPPED indicates that a task was stopped by ptrace. pub const CLD_TRAPPED: i32 = 4; // CLD_STOPPED indicates that a thread group completed a group stop. pub const CLD_STOPPED: i32 = 5; // CLD_CONTINUED indicates that a group-stopped thread group was continued. pub const CLD_CONTIN...
New
identifier_name
SignalDef.rs
pub rsp: u64, pub ss: u64, /* top of stack page */ } impl PtRegs { pub fn Set(&mut self, ctx: &SigContext) { self.r15 = ctx.r15; self.r14 = ctx.r14; self.r13 = ctx.r13; self.r12 = ctx.r12; self.rbp = ctx.rbp; self.rbx = ctx.rbx; self.r11 = ctx.r11...
pub cs: u64, pub eflags: u64,
random_line_split
SignalDef.rs
pub fn ForEachSignal(&self, mut f: impl FnMut(Signal)) { for i in 0..64 { if self.0 & (1 << i) != 0 { f(Signal(i as i32 + 1)) } } } } #[derive(Debug, Clone, Default)] pub struct SignalQueue { signals: LinkedList<PendingSignal>, } impl SignalQueue { ...
{ let mask : SigMask = task.CopyInObj(addr)?; return Ok((mask.addr, mask.len)) }
identifier_body
api-put-object-multipart.go
Upload completeMultipartUpload // Calculate the optimal parts info for a given size. totalPartsCount, partSize, _, err := OptimalPartInfo(-1, opts.PartSize) if err != nil { return UploadInfo{}, err } // Choose hash algorithms to be calculated by hashCopyN, // avoid sha256 with non-v4 signature request or // ...
// Initiate a new multipart upload. uploadID, err := c.newUploadID(ctx, bucketName, objectName, opts) if err != nil { return UploadInfo{}, err } delete(opts.UserMetadata, "X-Amz-Checksum-Algorithm") defer func() { if err != nil { c.abortMultipartUpload(ctx, bucketName, objectName, uploadID) } }() /...
{ if opts.UserMetadata == nil { opts.UserMetadata = make(map[string]string, 1) } opts.UserMetadata["X-Amz-Checksum-Algorithm"] = "CRC32C" }
conditional_block
api-put-object-multipart.go
(ctx context.Context, bucketName, objectName string, reader io.Reader, opts PutObjectOptions) (info UploadInfo, err error) { // Input validation. if err = s3utils.CheckValidBucketName(bucketName); err != nil { return UploadInfo{}, err } if err = s3utils.CheckValidObjectName(objectName); err != nil { return Uplo...
putObjectMultipartNoStream
identifier_name
api-put-object-multipart.go
// Loop over total uploaded parts to save them in // Parts array before completing the multipart request. for i := 1; i < partNumber; i++ { part, ok := partsInfo[i] if !ok { return UploadInfo{}, errInvalidArgument(fmt.Sprintf("Missing part number %d", i)) } complMultipartUpload.Parts = append(complMultipar...
defer closeResponse(resp) if err != nil { return UploadInfo{}, err }
random_line_split
api-put-object-multipart.go
func (c *Client) putObjectMultipartNoStream(ctx context.Context, bucketName, objectName string, reader io.Reader, opts PutObjectOptions) (info UploadInfo, err error) { // Input validation. if err = s3utils.CheckValidBucketName(bucketName); err != nil { return UploadInfo{}, err } if err = s3utils.CheckValidObjec...
{ info, err = c.putObjectMultipartNoStream(ctx, bucketName, objectName, reader, opts) if err != nil { errResp := ToErrorResponse(err) // Verify if multipart functionality is not available, if not // fall back to single PutObject operation. if errResp.Code == "AccessDenied" && strings.Contains(errResp.Message,...
identifier_body
manager.go
(context.Context, ...UninstallOption) (*rpb.Release, error) CleanupRelease(context.Context, string) (bool, error) } type manager struct { actionConfig *action.Configuration storageBackend *storage.Storage kubeClient kube.Interface releaseName string namespace string values map[string]interface{} stat...
return nil }) } func createPatch(existing runtime.Object, expected *resource.Info) ([]byte, apitypes.PatchType, error) { existingJSON, err := json.Marshal(existing) if err != nil { return nil, apitypes.StrategicMergePatchType, err } expectedJSON, err := json.Marshal(expected.Object) if err != nil { return...
{ return fmt.Errorf("patch error: %w", err) }
conditional_block
manager.go
(context.Context, ...UninstallOption) (*rpb.Release, error) CleanupRelease(context.Context, string) (bool, error) } type manager struct { actionConfig *action.Configuration storageBackend *storage.Storage kubeClient kube.Interface releaseName string namespace string values map[string]interface{} stat...
func (m manager) getDeployedRelease() (*rpb.Release, error) { deployedRelease, err := m.storageBackend.Deployed(m.releaseName) if err != nil { if strings.Contains(err.Error(), "has no deployed releases") { return nil, driver.ErrReleaseNotFound } return nil, err } return deployedRelease, nil } func (m ma...
{ return err != nil && strings.Contains(err.Error(), "not found") }
identifier_body
manager.go
Release(context.Context, ...UninstallOption) (*rpb.Release, error) CleanupRelease(context.Context, string) (bool, error) } type manager struct { actionConfig *action.Configuration storageBackend *storage.Storage kubeClient kube.Interface releaseName string namespace string values map[string]interface{...
() string { return m.releaseName } func (m manager) IsInstalled() bool { return m.isInstalled } func (m manager) IsUpgradeRequired() bool { return m.isUpgradeRequired } // Sync ensures the Helm storage backend is in sync with the status of the // custom resource. func (m *manager) Sync(ctx context.Context) error ...
ReleaseName
identifier_name
manager.go
Release(context.Context, ...UninstallOption) (*rpb.Release, error) CleanupRelease(context.Context, string) (bool, error) } type manager struct { actionConfig *action.Configuration storageBackend *storage.Storage kubeClient kube.Interface releaseName string namespace string values map[string]interface{...
// the response even when it doesn't record the release in its release // store (e.g. when there is an error rendering the release manifest). // In that case the rollback will fail with a not found error because // there was nothing to rollback. // // Only log a message about a rollback failure if the...
uninstall := action.NewUninstall(m.actionConfig) _, uninstallErr := uninstall.Run(m.releaseName) // In certain cases, InstallRelease will return a partial release in
random_line_split
player.go
"go.minekube.com/gate/pkg/edition/java/proto/packet/title" "go.minekube.com/gate/pkg/edition/java/proto/util" "go.minekube.com/gate/pkg/edition/java/proto/version" "go.minekube.com/gate/pkg/edition/java/proxy/message" "go.minekube.com/gate/pkg/edition/java/proxy/player" "go.minekube.com/gate/pkg/gate/proto" "go....
"go.minekube.com/gate/pkg/edition/java/forge" "go.minekube.com/gate/pkg/edition/java/modinfo" "go.minekube.com/gate/pkg/edition/java/profile" "go.minekube.com/gate/pkg/edition/java/proto/packet" "go.minekube.com/gate/pkg/edition/java/proto/packet/plugin"
random_line_split
player.go
// SendResourcePack sends the specified resource pack from url to the user. If at all possible, // send the resource pack with a sha1 hash using SendResourcePackWithHash. To monitor the status // of the sent resource pack, subscribe to PlayerResourcePackStatusEvent. SendResourcePack(url string) error // SendResourc...
() bool { return p.onlineMode } func (p *connectedPlayer) GameProfile() profile.GameProfile { return *p.profile } var ( ErrNoBackendConnection = errors.New("player has no backend server connection yet") ErrTooLongChatMessage = errors.New("server bound chat message can not exceed 256 characters") ) func (p *conn...
OnlineMode
identifier_name
player.go
Known plugin channels *tabList // Player's tab list mu sync.RWMutex // Protects following fields connectedServer_ *serverConnection connInFlight *serverConnection settings player.Settings modInfo *modinfo.ModInfo connPhase clientConnectionPhase serversToTry []string...
nnectedServer(); cs != nil { return cs } // We must return an explicit nil, not a (*serverConnection)(nil). return nil } func (p *conne
identifier_body
player.go
to the user. If at all possible, // send the resource pack with a sha1 hash using SendResourcePackWithHash. To monitor the status // of the sent resource pack, subscribe to PlayerResourcePackStatusEvent. SendResourcePack(url string) error // SendResourcePackWithHash sends the specified resource pack from url to th...
} p.tryIndex =
conditional_block
dream.go
(t time.Time) time.Time { return t.Truncate(24 * time.Hour) } func now() string { return time.Now().Format(time.Kitchen) } // Dream is exported so it can be an api, haha what fun. Games perhaps? Stock trading? Some real time video effect? func Dream(c *gin.Context) { start := time.Now() defer func() { elapsed :...
Truncate
identifier_name
dream.go
le, }) Log.Info("base path is ", basePath) newJobLog(name) //let's save interesting job metadata for the user in a tidy format (err logs, srv logs kept with the binary or maybe put in bind dir? wip) jobLog.WithFields(logrus.Fields{ "fps": fps, "iterations": it, "oct...
} else { // if no youtube, then get file from form upload file, err := c.FormFile("file") if err != nil { Log.Error("failed to get file", err) //although this might not be an error as we support ytdl now return } name = strings.Split(file.Filename, ".")[0] fullName = file.Filename ext = strings.Spli...
} }
random_line_split
dream.go
func now() string { return time.Now().Format(time.Kitchen) } // Dream is exported so it can be an api, haha what fun. Games perhaps? Stock trading? Some real time video effect? func Dream(c *gin.Context) { start := time.Now() defer func() { elapsed := fmt.Sprintf("%s %s", now(), time.Since(start)) elapsed = s...
{ return t.Truncate(24 * time.Hour) }
identifier_body
dream.go
, }) Log.Info("base path is ", basePath) newJobLog(name) //let's save interesting job metadata for the user in a tidy format (err logs, srv logs kept with the binary or maybe put in bind dir? wip) jobLog.WithFields(logrus.Fields{ "fps": fps, "iterations": it, "octav...
break //we got our file, now we move on, we don't need to keep listening for URL } } } else { // if no youtube, then get file from form upload file, err := c.FormFile("file") if err != nil { Log.Error("failed to get file", err) //although this might not be an error as we support ytdl now return ...
{ if err = os.Mkdir(framesDirPath, 0777); err != nil { Log.Error("failed to make a new job dir w/ error: ", err) } Log.Info("frames folder for new job was created at ", framesDirPath) }
conditional_block
buffer.go
have to look in our trusy // shift mapping thing. if val, ok := shiftAlternative[r]; ok { r = val } } } // NOTE: we have to do this AFTER we map the // shift combo for the value! // this will not insert a ), }, or ] if there // is one to the right of us... basically // this escapes out of a clos...
urrLine := b.contents[b.curs.y] prevLine := b.contents[b.curs.y-1] b.contents[b.curs.y-1] = currLine b.contents[b.curs.y] = prevLine b.moveUp() } return true } func (b *Buffer) swapLineDown() bool { if b.curs.y < len(b.contents) { currLine := b.contents[b.curs.y] nextLine := b.contents[b.curs.y+1] b.c...
> 0 { c
identifier_name
buffer.go
we have to look in our trusy // shift mapping thing. if val, ok := shiftAlternative[r]; ok { r = val } } } // NOTE: we have to do this AFTER we map the // shift combo for the value! // this will not insert a ), }, or ] if there // is one to the right of us... basically // this escapes out of a c...
) swapLineDown() bool { if b.curs.y < len(b.contents) { currLine := b.contents[b.curs.y] nextLine := b.contents[b.curs.y+1] b.contents[b.curs.y+1] = currLine b.contents[b.curs.y] = nextLine b.moveDown() } return true } func (b *Buffer) scrollUp() { if b.cam.y > 0 { // TODO move the cursor down 45 lines...
s.y] prevLine := b.contents[b.curs.y-1] b.contents[b.curs.y-1] = currLine b.contents[b.curs.y] = prevLine b.moveUp() } return true } func (b *Buffer
conditional_block
buffer.go
// my UK macbook key layout. var shiftAlternative = map[rune]rune{ '1': '!', '2': '@', '3': '£', '4': '$', '5': '%', '6': '^', '7': '&', '8': '*', '9': '(', '0': ')', '-': '_', '=': '+', '`': '~', '/': '?', '.': '>', ',': '<', '[': '{', ']': '}', ';': ':', '\'': '"', '\\': '|', ...
} // TODO handle EVERYTHING but for now im handling
random_line_split
buffer.go
SHIFT_DOWN bool = false SUPER_DOWN = false // cmd on mac, ctrl on windows CONTROL_DOWN = false // what is this on windows? ALT_DOWN = false // option on mac CAPS_LOCK = false ) // TODO(Felix) this is really stupid func (b *Buffer) makeTab() string { blah := []rune{} for i := 0; i ...
identifier_body
lib.rs
. assert!(executor.run_until_stalled(&mut future.as_mut()).is_ready()); } None => warn!("Called stop on already stopped MLME"), } } pub fn delete(mut self) { if self.internal.is_some() { warn!("Called delete on MlmeHandle before calling stop."...
const MINSTREL_UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100); // Remedy for fxbug.dev/8165 (fxbug.dev/33151) // See |DATA_FRAME_INTERVAL_NANOS| // in //src/connectivity/wlan/testing/hw-sim/test/rate_selection/src/lib.rs // Ensure at least one probe frame (generated every 16 data frames)...
{ mac_sublayer.device.tx_status_report_supported && !mac_sublayer.rate_selection_offload.supported }
identifier_body
lib.rs
wlanmevicemonitor created to connect MLME and SME. let mlme_protocol_handle_via_iface_creation = match device.start(&ifc) { Ok(handle) => handle, Err(e) => { // Failure to unwrap indicates a critical failure in the driver init thread. startup_sender.send(...
handle_eth_frame_tx
identifier_name
lib.rs
before calling stop."); self.stop() } } pub fn queue_eth_frame_tx(&mut self, bytes: Vec<u8>) -> Result<(), Error> { self.driver_event_sink .unbounded_send(DriverEvent::EthFrameTx { bytes: bytes.into() }) .map_err(|e| e.into()) } // Fns used to inter...
{ // Failure to unwrap indicates a critical failure in the driver init thread. startup_sender.send(Err(anyhow!("device.start failed: {}", e))).unwrap(); return; }
conditional_block
lib.rs
now. assert!(executor.run_until_stalled(&mut future.as_mut()).is_ready()); } None => warn!("Called stop on already stopped MLME"), } } pub fn delete(mut self) { if self.internal.is_some() { warn!("Called delete on MlmeHandle before calling st...
startup_receiver .try_recv() .unwrap() .expect("Test MLME setup stalled.") .expect("Test MLME setup failed."); MlmeHandle { driver_event_sink, internal: Some(MlmeHandleInternal::Fake { executor, future }), } } asyn...
)); let _ = executor.run_until_stalled(&mut future.as_mut());
random_line_split
io_export_arm.py
pdata = np.array(pdata, dtype='<i2') ndata = np.array(ndata, dtype='<i2') if has_tex: t0data *= invscale_tex t0data = np.array(t0data, dtype='<i2') if has_tex1: t1data *= invscale_tex t1data = np.array(t1data, dtype='<i2') ...
_pack_map
identifier_name
io_export_arm.py
o['vertex_arrays'].append({ 'attrib': 'col', 'values': cdata }) if has_tang: o['vertex_arrays'].append({ 'attrib': 'tang', 'values': tangdata }) def export_mesh(self, bobject, scene): # This function exports a single mesh object print('Exporting mesh ' + bobject.data.name) ...
_pack_map(obj, fp)
conditional_block
io_export_arm.py
] = normal[0] ndata[i2 + 1] = normal[1] if has_tex: uv = lay0.data[loop.index].uv t0data[i2 ] = uv[0] t0data[i2 + 1] = 1.0 - uv[1] # Reverse Y if has_tex1: uv = lay1.data[loop.index].uv ...
fp.write(b"\xca" + struct.pack("<f", obj))
identifier_body