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
thread.go
next = newMessageHandlerCont(c) } next.Push(t.Runtime, ErrorValue(err)) } c = next } return } // This is to be able to close a suspended coroutine without completing it, but // still allow cleaning up the to-be-closed variables. If this is put on the // resume channel of a running thread, yield will c...
Parent
identifier_name
campaign_loader.rs
//pub fn load_all_campaign_metadata(asset_db: &mut AssetDatabase) {//-> Config { //} //loads all data for a given campaign pub fn load_campaign_data(path: &str, gpu: &mut Gpu, asset_db: &mut AssetDatabase) { //load all config files under the campain folder let mut campaign_config_paths = find_config_file...
else { error!("[Asset Loading] Failed to load asset relating to config file {}. {}", config_path.to_str().unwrap(), "Please review previous warnings." ); } } } //make sure file is one of the right formats for configuration files fn is_config_...
{ info!("[Asset Loading] Loaded asset relating to config file {}", config_path.to_str().unwrap()); }
conditional_block
campaign_loader.rs
(path: &str, gpu: &mut Gpu, asset_db: &mut AssetDatabase) { //load all config files under the campain folder let mut campaign_config_paths = find_config_files(path); //for each config file, load it then load the associated asset while let Some(config_path) = campaign_config_paths.pop() { ...
); return false; } };
random_line_split
campaign_loader.rs
pub fn load_all_campaign_metadata(asset_db: &mut AssetDatabase) {//-> Config { //} //loads all data for a given campaign pub fn load_campaign_data(path: &str, gpu: &mut Gpu, asset_db: &mut AssetDatabase) { //load all config files under the campain folder let mut campaign_config_paths = find_config_files(...
//creates a task for loading a config file and it's resources fn load_config_task(file_path: &PathBuf) -> Task<Config> { //needed so closure below can capture let path = file_path.clone(); Task::new(move || { //coerce into string value or return error let str_path = ...
{ coffee::Error::IO( std::io::Error::new( std::io::ErrorKind::Other, msg ) ) }
identifier_body
campaign_loader.rs
//pub fn load_all_campaign_metadata(asset_db: &mut AssetDatabase) {//-> Config { //} //loads all data for a given campaign pub fn
(path: &str, gpu: &mut Gpu, asset_db: &mut AssetDatabase) { //load all config files under the campain folder let mut campaign_config_paths = find_config_files(path); //for each config file, load it then load the associated asset while let Some(config_path) = campaign_config_paths.pop() { ...
load_campaign_data
identifier_name
encryption_properties.go
. type Algorithm struct { Algo Cipher Aad struct { AadPrefix []byte AadFileUnique []byte SupplyAadPrefix bool } } // ToThrift returns an instance to be used for serializing when writing a file. func (e Algorithm) ToThrift() *format.EncryptionAlgorithm { if e.Algo == AesGcm { return &format.Encrypt...
{ o(&cfg) }
conditional_block
encryption_properties.go
ryptionProperties{ Verifier: cfg.verifier, footerKey: cfg.footerKey, checkPlaintextFooterIntegrity: cfg.checkFooterIntegrity, KeyRetriever: cfg.retriever, aadPrefix: cfg.aadPrefix, columnDecryptProps: cfg.colDecrypt, ...
ret.Aad.SupplyAadPrefix = *enc.AES_GCM_V1.SupplyAadPrefix return
random_line_split
encryption_properties.go
) { if len(decrypt) == 0 { return } if len(cfg.colDecrypt) != 0 { panic("column properties already set") } for _, v := range decrypt { if v.IsUtilized() { panic("parquet: column properties utilized in another file") } v.SetUtilized() } cfg.colDecrypt = decrypt } } // WithKeyRetriever ...
WithFooterKeyMetadata
identifier_name
encryption_properties.go
type colEncryptConfig struct { key string keyMetadata string encrypted bool } // ColumnEncryptOption how to specify options to the the NewColumnEncryptionProperties function. type ColumnEncryptOption func(*colEncryptConfig) // WithKey sets a column specific key. // If key is not set on an encrypted col...
{ copy := ce.key return NewColumnEncryptionProperties(ce.columnPath, WithKey(copy), WithKeyMetadata(ce.keyMetadata)) }
identifier_body
bot.js
= 4; return permlvl; }; var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g; client.on('debug', e => { console.log(chalk.bgBlue.green(e.replace(regToken, 'that was redacted'))); }); client.on('warn', e => { console.log(chalk.bgYellow(e.replace(regToken, 'that was redacted'))); }); client.on('error', e => { ...
const request = require('node-superfetch'); const db = require('quick.db'); const ms = require('parse-ms') let timeout = 600000 let dakdest = await db.fetch(`goldzzz_${msg.author.id}`); let i = db.fetch(`gold_${msg.author.id}`) if (i == 'gold') { if (dakdest !== null && timeout - (Date.now() - dakdest) > ...
client.on("message", async msg => {
random_line_split
SI507_Final_Project.py
except: pass try: Uni.female_tot = soup.find_all('strong',{'class':'f-12'})[2].text except: pass try: Uni.female_intl = soup.find_all('strong',{'class':'f-12'})[5].text except: pass try: fullAddress = soup.find('ul',{'class':'fa-ul'})....
i = 1 restaurantInfo = "" for key in restaurantNameInfo.keys(): if i > 10: break name = key address = restaurantNameInfo[key]['address'] phone = restaurantNameInfo[key]['phone'] restaurantInfo = restaurantInfo + "[{}] {} : {}, {} \n".format(i, na...
identifier_body
SI507_Final_Project.py
dbName connection = sqlite3.connect(dbName) cursor = connection.cursor() insertUni = """ INSERT or IGNORE INTO Universities (NAME,STATE,ADDRESS,ZIPCODE,PHONE,URL,MALE,FEMALE,MALEINTL,FEMALEINTL) VALUES ("{}","{}","{}","{}","{}","{}","{}","{}","{}","{}");""".format(Uni.name,Uni.states,Uni.add...
break
conditional_block
SI507_Final_Project.py
) return unique_key def requestResponseText(url): ''' request response text of the url Parameters ---------- url: string Returns ------- response.text ''' if (url in CACHE_DICT.keys()): print("Using cache") else: print("Fetching") ...
extractRestaurantInfoOnly
identifier_name
SI507_Final_Project.py
string address of the restaurnat zipcode: string zip-code of the restaurnat ''' def __init__(self): #initialize empty attributes self.name = [] # address of the restaurant self.address = [] # address of the restaurant self.zipcode = [] # zip code of the resta...
pass try: Uni.male_tot = soup.find_all('strong',{'class':'f-12'})[1].text except: pass try: Uni.male_intl = soup.find_all('strong',{'class':'f-12'})[4].text except: pass try: Uni.female_tot = soup.find_all('strong',{'class':'f-12'})[2].text ...
try: Uni.state = soup.find_all('li',{'class':'breadcrumb-item'})[2].a.text except:
random_line_split
main.go
WHISPER_ENDPOINT", "WHISPER_URL"}, Value: "https://api.whisper.rotational.dev", }, } app.Commands = []*cli.Command{ { Name: "serve", Usage: "run the whisper server", Category: "server", Action: serve, Flags: []cli.Flag{ &cli.StringFlag{ Name: "addr", Aliases: []strin...
Aliases: []string{"G", "gs"}, Usage: "generate a random secret of the specified length", }, &cli.StringFlag{ Name: "in", Aliases: []string{"i", "u", "upload"}, Usage: "upload a file as the secret contents", }, &cli.StringFlag{ Name: "password", Aliases: []str...
}, &cli.IntFlag{ Name: "generate-secret",
random_line_split
main.go
ISPER_ENDPOINT", "WHISPER_URL"}, Value: "https://api.whisper.rotational.dev", }, } app.Commands = []*cli.Command{ { Name: "serve", Usage: "run the whisper server", Category: "server", Action: serve, Flags: []cli.Flag{ &cli.StringFlag{ Name: "addr", Aliases: []string{...
// Print the password so that it can be used to retrieve the secret later fmt.Printf("Password for retrieval: %s\n", req.Password) } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() var rep *v1.CreateSecretReply if rep, err = client.CreateSecret(ctx, req); err != nil {...
{ return cli.Exit(err, 1) }
conditional_block
main.go
", "expires", "expires-after"}, Usage: "specify the lifetime of the secret before it is deleted", }, &cli.BoolFlag{ Name: "b64encoded", Aliases: []string{"b", "b64"}, Usage: "specify if the secret is base64 encoded (true if uploading a file, false if generated)", }, }, }, {...
{ var fi fs.FileInfo if fi, err = os.Stat(path); err != nil { return false, err } return fi.IsDir(), nil }
identifier_body
main.go
ISPER_ENDPOINT", "WHISPER_URL"}, Value: "https://api.whisper.rotational.dev", }, } app.Commands = []*cli.Command{ { Name: "serve", Usage: "run the whisper server", Category: "server", Action: serve, Flags: []cli.Flag{ &cli.StringFlag{ Name: "addr", Aliases: []string{...
(c *cli.Context) (err error) { // Create the request req := &v1.CreateSecretRequest{ Password: c.String("password"), Accesses: c.Int("accesses"), Lifetime: v1.Duration(c.Duration("lifetime")), } // Add the secret to the request via one of the command line options switch { case c.String("secret") != "": i...
create
identifier_name
sound.js
}; // // luv.update = function() { // // This will throw an error; // // cry might need some time to load. // // Continue reading for a working version. // if(something) { cry.play(); } // }; // // A simple way to fix this is to check that all media has bee...
{ instance = instances[i]; if(instance.isReady()) { return instance; } }
conditional_block
sound.js
sfx/cry.mp3'); // }; // // luv.update = function() { // // This will throw an error; // // cry might need some time to load. // // Continue reading for a working version. // if(something) { cry.play(); } // }; // // A simple way to fix this is to che...
var getExistingReadyInstance = function(instances) { var instance; for(var i=0; i< instances.length; i++) { instance = instances[i]; if(instance.isReady()) {
random_line_split
LonghurstProvince.py
(target='Iodide'): """ Driver to add Longhurst Provinces fields to spatial NetCDF files """ Filenames = [ 's2s_predicted_{}_0.125x0.125_No_Skagerrak', 's2s_feature_variables_0.125x0.125', 's2s_predicted_{}_0.125x0.125', ] folder = '/work/home/ts551/data/iodide/' for n...
add_longhurst_raster_array_and_LWI_core_NetCDFs
identifier_name
LonghurstProvince.py
+= [lat] lons += [lon] # Make into a DataFrame df = pd.DataFrame() df[LatVar] = lats df[LonVar] = lons # Add a single variable for the coordinate def f(x): return (x[LonVar], x[LatVar]) df[CoordVar] = df.apply(f, axis=1) # map the calculation of provinces def G...
# What data sets contribute to this PrtStr = 'Datasets contributing to these numbers: {}' print(PrtStr.format(', '.join(set(tmp['Data_Key'])))) def ParseLonghurstProvinceFile(): """ Parse the Longhurst *.xml file into a dictionary object Notes ----- - This code is copied from elsewh...
MITp_ = tmp_.loc[tmp_.index == idx, :]['PName (MIT)'].values[0] print(PrtStr.format(MITp_, Get_LonghurstProvinceName4Num(MITp_), prov, Get_LonghurstProvinceName4Num(prov)))
conditional_block
LonghurstProvince.py
Print the differences to screen print("When assignment differs - The MIT method gives:") PrtStr = "MIT:'{}' ({}), but R gives '{}' ({})" for prov in list(set(tmp['PName (R)'])): tmp_ = tmp.loc[tmp['PName (R)'] == prov, :] for idx in tmp_.index: MITp_ = tmp_.loc[tmp_.index == idx...
""" Get the longhurst province Parameters ------- input (str): input string to use as key to return dictionary value invert (float): reverse the key/pair of the dictionary rtn_dict (bool): return the entire dictionary. Returns ------- (str) Notes ----- - these **are**...
identifier_body
LonghurstProvince.py
pd.DataFrame(vals, index=[lat, lon]).unstack() df.to_csv('Intial_test_{}_processed_{}.csv'.format(res, ExStr)) # Convert to Dataset ds = xr.Dataset(data_vars={CoordVar: (['lat', 'lon', ], df.values)}, coords={'lat': DSlats, 'lon': DSlons, }) # Save as NetCDF file ds.to_netcdf('...
random_line_split
helpers.js
return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resol...
{ return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
identifier_body
helpers.js
step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": ver...
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) ...
{ _.label = t[1]; t = op; break; }
conditional_block
helpers.js
step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": ver...
return __awaiter(this, void 0, void 0, function () { var DotCoverPath, outputLocation, downloadFileName, url, zipLocation; var _this = this; return __generator(this, function (_a) { DotCoverPath = "CommandLineTools-2020-1-3"; outputLocation = _...
random_line_split
helpers.js
step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": ver...
() { } /// Check value contains content befor returning string value ExtensionHelpers.prototype.NamePairCheck = function (name, value, addQuotes) { if (value != undefined && value != '') { var argument = ' /' + name; if (addQuotes == true) { argument += '="' +...
ExtensionHelpers
identifier_name
utils.py
, ManyToManyRel) and not related.symmetrical: yield (name, related) def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have ...
klass__name = klass.__class__.__name__ raise ValueError( "Object is of type '{}', but must be a Django Model, " "Manager, or QuerySet".format(klass__name) ) return manager.all() def _get_custom_resolver(info): """ Get custom user defined resolver for que...
else:
random_line_split
utils.py
, ManyToManyRel) and not related.symmetrical: yield (name, related) def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have ...
return manager.all() def _get_custom_resolver(info): """ Get custom user defined resolver for query. This resolver must return QuerySet instance to be successfully resolved. """ parent = info.parent_type custom_resolver_name = f"resolve_{to_snake_case(info.field_name)}" if hasattr(pa...
if isinstance(klass, type): klass__name = klass.__name__ else: klass__name = klass.__class__.__name__ raise ValueError( "Object is of type '{}', but must be a Django Model, " "Manager, or QuerySet".format(klass__name) )
conditional_block
utils.py
, ManyToManyRel) and not related.symmetrical: yield (name, related) def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have ...
except ValidationError as e: raise ValidationError(e.__str__()) except TypeError as e: raise TypeError(e.__str__()) except Exception as e: raise Exception(e.__str__()) def create_obj(django_model, new_obj_key=None, *args, **kwargs): """ Function used by my on traditional M...
""" Function used to get a object :param app_label: A valid Django Model or a string with format: <app_label>.<model_name> :param model_name: Key into kwargs that contains de data: new_person :param object_id: :return: instance """ try: model = apps.get_model("{}.{}".format(app_label...
identifier_body
utils.py
, ManyToManyRel) and not related.symmetrical: yield (name, related) def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have ...
(d): """ Remove all empty fields in a nested dict """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (clean_dict(v) for v in d) if v] return OrderedDict([(k, v) for k, v in ((k, clean_dict(v)) for k, v in list(d.items())) if v]) def get...
clean_dict
identifier_name
mod.rs
let start = Instant::now(); // Postgres only supports a maximum of 2^15 params let (remain, posts) = if item.len() > 1280 { let remain = item.split_off(1280); (remain, item) } else { (vec![], item) }; item = rem...
false => Poll::Pending, } } }
random_line_split
mod.rs
::Acquire) as f64; let tt = self.inner.metrics.query_time_ns.load(Ordering::Acquire) as f64; let m = Metrics { posts: self.inner.metrics.posts.load(Ordering::Acquire), avg_insert_time_ms: queries / tt * 1_000_000., save_errors: self.inner.metrics.save_errors.load(Orde...
start_send
identifier_name
mod.rs
} #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Search { inner: Arc<SearchInner>, } impl Search { #[allow(dead_code)] pub fn builder() -> SearchBuilder { SearchBuilder::default() } pub fn metrics_provider(&self) -> impl super::MetricsProvider { Sea...
{ return Poll::Ready(Err(Error::ArchiveError)); }
conditional_block
mod.rs
) { self.queries.fetch_add(1, Ordering::Relaxed); self.query_time_ns .fetch_add(dur.as_nanos() as u64, Ordering::Relaxed); } pub fn incr_save_error(&self, count: u64) { self.save_errors.fetch_add(count, Ordering::Relaxed); } } #[derive(Clone)] pub struct SearchMetricsPr...
{ let posts = self.inflight_posts.load(Ordering::Acquire); posts < self.max_inflight_posts }
identifier_body
file_system_persistence.go
protocol.BlockPairContainer) primitives.BlockHeight { if block == nil { return 0 } return block.TransactionsBlock.Header.BlockHeight() } func (f *BlockPersistence) GracefulShutdown(shutdownContext context.Context) { logger := f.logger.WithTags(log.String("filename", blocksFileName(f.config))) if err := f.blockW...
newTip, err := newFileBlockWriter(file, codec, bhIndex.fetchNextOffset()) if err != nil { closeSilently(file, logger) return nil, err } adapter := &BlockPersistence{ bhIndex: bhIndex, config: conf, blockTracker: synchronization.NewBlockTracker(logger, uint64(bhIndex.getLastBlockHeight()), 5)...
{ closeSilently(file, logger) return nil, err }
conditional_block
file_system_persistence.go
protocol.BlockPairContainer) primitives.BlockHeight { if block == nil { return 0 } return block.TransactionsBlock.Header.BlockHeight() } func (f *BlockPersistence) GracefulShutdown(shutdownContext context.Context) { logger := f.logger.WithTags(log.String("filename", blocksFileName(f.config))) if err := f.blockW...
(file *os.File, conf config.FilesystemBlockPersistenceConfig, logger log.Logger) error { header := newBlocksFileHeader(uint32(conf.NetworkType()), uint32(conf.VirtualChainId())) logger.Info("creating new blocks file", log.String("filename", file.Name())) err := header.write(file) if err != nil { return errors.Wra...
writeNewFileHeader
identifier_name
file_system_persistence.go
Id, conf.VirtualChainId()) } offset, err = file.Seek(0, io.SeekCurrent) // read current offset if err != nil { return 0, errors.Wrapf(err, "error reading blocks file header") } return offset, nil } func writeNewFileHeader(file *os.File, conf config.FilesystemBlockPersistenceConfig, logger log.Logger) error { ...
{ return blocksFileName(f.config) }
identifier_body
file_system_persistence.go
protocol.BlockPairContainer) primitives.BlockHeight { if block == nil { return 0 } return block.TransactionsBlock.Header.BlockHeight() } func (f *BlockPersistence) GracefulShutdown(shutdownContext context.Context) { logger := f.logger.WithTags(log.String("filename", blocksFileName(f.config))) if err := f.blockW...
return 0, errors.Wrapf(err, "error reading blocks file header") } if header.NetworkType != uint32(conf.NetworkType()) { return 0, fmt.Errorf("blocks file network type mismatch. found netowrk type %d expected %d", header.NetworkType, conf.NetworkType()) } if header.ChainId != uint32(conf.VirtualChainId()) { ...
header := newBlocksFileHeader(0, 0) err = header.read(file) if err != nil {
random_line_split
app.js
; element = document.links[2]; element = document.links[2].id; element = document.links[2].className; element = document.links[2].classList; //forms element = document.forms[0]; element = document.forms[0].method; element = document.forms[0].action; element = document.forms[0].className; element = document.forms[0].c...
} console.log(courseList); //local storage //add to local storage localStorage .setItem('name', "Kasia"); // add to session storage //sessionStorage.setItem('name', 'Kasia'); //remove from
console.log("courses added"); }
random_line_split
app.js
document.scripts[0].getAttribute('src'); //looping all the images let images = document.images; let imagesArray = Array.from(images); imagesArray.forEach(function(image){ return image.src; }); console.log(imagesArray); //selecting DOM element let heading = document.getElementById('heading'); console.log(heading...
{ names = JSON.parse(localStorageContent) }
conditional_block
app.js
; element = document.links[2]; element = document.links[2].id; element = document.links[2].className; element = document.links[2].classList; //forms element = document.forms[0]; element = document.forms[0].method; element = document.forms[0].action; element = document.forms[0].className; element = document.forms[0].c...
console.log(courseList); //local storage //add to local storage localStorage .setItem('name', "Kasia"); // add to session storage //sessionStorage.setItem('name', 'Kasia'); //remove
{ if (event.target.classList.contains('add-to-cart')){ console.log("courses added"); } }
identifier_body
app.js
; element = document.links[2]; element = document.links[2].id; element = document.links[2].className; element = document.links[2].classList; //forms element = document.forms[0]; element = document.forms[0].method; element = document.forms[0].action; element = document.forms[0].className; element = document.forms[0].c...
(event){ if (event.target.classList.contains('add-to-cart')){ console.log("courses added"); } } console.log(courseList); //local storage //add to local storage localStorage .setItem('name', "Kasia"); // add to session storage //sessionStorage.setItem('name', 'Kasia'); //remove from
addToCart
identifier_name
metadata.rs
_or_else(|| { anyhow!("All workspace members are expected to be under the workspace root") })?; let diff = Utf8PathBuf::from_path_buf(path_diff) .map_err(|_e| anyhow!("Invalid UTF-8 in source directory path diff."))?; // Create a matching directory tree for the cur...
{ checksums.insert( package_ident(package.name.as_ref(), &package.version.to_string()), checksum.to_string(), ); }
conditional_block
metadata.rs
} impl MetadataFetcher for CargoMetadataFetcher { fn fetch_metadata(&self, working_dir: &Utf8Path, include_deps: bool) -> Result<Metadata> { let mut command = MetadataCommand::new(); if !include_deps { command.no_deps(); } command .cargo_path(&self.cargo_bin_path) .current_dir(wo...
{ CargoMetadataFetcher { cargo_bin_path: cargo_bin_path(), } }
identifier_body
metadata.rs
(), fs::read_to_string(working_dir.join("Cargo.toml")).unwrap() ) }) } } pub struct DummyLockfileGenerator { // Optional lockfile to use for generation pub lockfile_contents: Option<String>, } impl LockfileGenerator for DummyLockfileGenerator { fn generate_lockfil...
random_line_split
metadata.rs
{ cargo_bin_path: Utf8PathBuf, } impl LockfileGenerator for CargoLockfileGenerator { /// Generate lockfile information from a cargo workspace root fn generate_lockfile(&self, crate_root_dir: &Utf8Path) -> Result<Lockfile> { let lockfile_path = crate_root_dir.join("Cargo.lock"); // Generate lockfile ...
CargoLockfileGenerator
identifier_name
EventModal.js
Icon, Table } from 'antd'; import React, {Component} from 'react'; import videojs from 'video.js'; import Flash from 'videojs-flash'; import 'video.js/dist/video-js.css'; import moment from 'moment'; import styles from './EventModal.less'; import { getLocalTimeF } from '../../../utils/time'; import {imageUrl, stringTra...
(){ const {form} = this.props; this.props.dispatch({ type:'device/updateState', payload:{ eventModal:false } }) } handleCancel(){ this.props.dispatch({ type:'device/updateState', payload:{ ...
onOk
identifier_name
EventModal.js
Icon, Table } from 'antd'; import React, {Component} from 'react'; import videojs from 'video.js'; import Flash from 'videojs-flash'; import 'video.js/dist/video-js.css'; import moment from 'moment'; import styles from './EventModal.less'; import { getLocalTimeF } from '../../../utils/time'; import {imageUrl, stringTra...
} ] } else if(videoUrl[index].indexOf('m3u8')>(-1)) { videotype = [ { src: videoUrl[index], type: 'application/x-mpegURL' ...
type: 'rtmp/mp4'
random_line_split
EventModal.js
, Table } from 'antd'; import React, {Component} from 'react'; import videojs from 'video.js'; import Flash from 'videojs-flash'; import 'video.js/dist/video-js.css'; import moment from 'moment'; import styles from './EventModal.less'; import { getLocalTimeF } from '../../../utils/time'; import {imageUrl, stringTransfo...
handleImgCancel = () => this.setState({ previewVisible: false }) handlePreview = (file) => { this.setState({ previewImage: file.url || file.thumbUrl, previewVisible: true, }); } render() { const { form: { getFieldDecorator...
{ this.props.dispatch({ type:'device/updateState', payload:{ eventModal:false } }) }
identifier_body
kieapp_types.go
// Important: Run "operator-sdk generate k8s" to regenerate code after modifying this file // KIE environment type to deploy (prod, authoring, trial, etc) Environment string `json:"environment,omitempty"` KieDeployments int `json:"kieDeployments"` // Number of KieServer DeploymentConfigs ...
init
identifier_name
kieapp_types.go
modifying this file // KIE environment type to deploy (prod, authoring, trial, etc) Environment string `json:"environment,omitempty"` KieDeployments int `json:"kieDeployments"` // Number of KieServer DeploymentConfigs (defaults to 1) RhpamRegistry KieAppRegistry `json:"rhpamRegistry,om...
{ SchemeBuilder.Register(&KieApp{}, &KieAppList{}) }
identifier_body
kieapp_types.go
openshift/client-go/image/clientset/versioned/typed/image/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json ...
DeploymentConfigs []appsv1.DeploymentConfig `json:"deploymentConfigs,omitempty"` BuildConfigs []buildv1.BuildConfig `json:"buildConfigs,omitempty"` ImageStreams []oimagev1.ImageStream `json:"imageStreams,omitempty"` Services []corev1.Service ...
PersistentVolumeClaims []corev1.PersistentVolumeClaim `json:"persistentVolumeClaims,omitempty"` ServiceAccounts []corev1.ServiceAccount `json:"serviceAccounts,omitempty"` Secrets []corev1.Secret `json:"secrets,omitempty"` Roles []rbacv1.Role ...
random_line_split
main.go
* 500) defer t.Stop() go func() { for { select { case <-t.C: writer.Flush() } } }() // main logic - now multi-threaded for a tonne of traffic, quickly. Hopefully it's still functional :D for u := range urls { wg.Add(1) go func(site string) { defer wg.Done() finalUrls := []string{} ...
func attemptToIdentifyEngine(url string, vulnParamElement int, quietMode bool) []string { // this might be meh, but make a request to the same URL per template based on the payloads we have // for this, we don't care about the number of parameters - we just want to try identify the template engine
random_line_split
main.go
) ch := readStdin() go func() { for u := range ch { urls <- u } close(urls) }() var outputFileFlag string flag.StringVar(&outputFileFlag, "o", "", "Output file for possible SSTI vulnerable URLs") quietModeFlag := flag.Bool("q", false, "Only output the URLs with possible SSTI vulnerabilities") flag.Par...
() <-chan string { lines := make(chan string) go func() { defer close(lines) sc := bufio.NewScanner(os.Stdin) for sc.Scan() { url := strings.ToLower(sc.Text()) if url != "" { lines <- url } } }() return lines } // TODO: Should we randomise this? Do we care? probably not. // We should extend th...
readStdin
identifier_name
main.go
) ch := readStdin() go func() { for u := range ch { urls <- u } close(urls) }() var outputFileFlag string flag.StringVar(&outputFileFlag, "o", "", "Output file for possible SSTI vulnerable URLs") quietModeFlag := flag.Bool("q", false, "Only output the URLs with possible SSTI vulnerabilities") flag.Par...
parameterSplit := strings.Split(urlParamSplit[1], "&") if len(parameterSplit) == 0 { return "", nil, nil // Although we had a ? in the URL, no parameters were actually identified } generatedPayloadCount := 1 // start from 1 because we aren't CS students generatedPayloads := []string{} // coll...
{ return "", nil, nil // Although we had a ? in the URL, no parameters were actually identified as the amount of chars after the ? appeared to be 0 }
conditional_block
main.go
I vulnerabilities") flag.Parse() quietMode := *quietModeFlag saveOutput := outputFileFlag != "" outputToSave := []string{} if !quietMode { banner() fmt.Println("") } writer := bufio.NewWriter(out) var wg sync.WaitGroup // flush to writer periodically t := time.NewTicker(time.Millisecond * 500) defer ...
{ r, _ := regexp.Compile(criteria) return r.MatchString(body) }
identifier_body
Generator.py
(0, num_elems), 2)] def calculate_action_list(num_agents): all_actions = [] for agent_idx in range(num_agents): all_actions.append(CorridorConstants.move_action(agent_idx)) for agent_idx_pair in calculate_pairs(num_agents): all_actions.append(CorridorConstants.click_action(*agent_idx_pair...
else: res[src_tile_idx, src_tile_idx] = 1.0 - succ_prob res[src_tile_idx, dst_tile_idx] = succ_prob return res def calculate_euclidian_distance_in_grid(p1, p2): return np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def calculate_good_sense_matrices(w, h, rock_positions...
res[src_tile_idx, dst_tile_idx] = 1.0
conditional_block
Generator.py
(0, num_elems), 2)] def calculate_action_list(num_agents): all_actions = [] for agent_idx in range(num_agents): all_actions.append(CorridorConstants.move_action(agent_idx)) for agent_idx_pair in calculate_pairs(num_agents): all_actions.append(CorridorConstants.click_action(*agent_idx_pair...
res = np.zeros(shape=(2, 2)) good, bad = RockSamplingConstants.good_idx, RockSamplingConstants.bad_idx res[bad][bad] = -bad_sample_penalty res[bad][good] = 0 # can't happen res[good][bad] = good_sample_reward res[good][good] = 0 # no effect return res def generate_random_tile(w, h): ...
random_line_split
Generator.py
(0, num_elems), 2)] def calculate_action_list(num_agents): all_actions = [] for agent_idx in range(num_agents): all_actions.append(CorridorConstants.move_action(agent_idx)) for agent_idx_pair in calculate_pairs(num_agents): all_actions.append(CorridorConstants.click_action(*agent_idx_pair...
def get_rock_sample_reward_matrix(good_sample_reward, bad_sample_penalty): res = np.zeros(shape=(2, 2)) good, bad = RockSamplingConstants.good_idx, RockSamplingConstants.bad_idx res[bad][bad] = -bad_sample_penalty res[bad][good] = 0 # can't happen res[good][bad] = good_sample_reward res[goo...
res = {} good_matrices = calculate_good_sense_matrices(w, h, rock_positions, sense_decay_const) bad_matrices = calculate_bad_sense_matrices(w, h, rock_positions, sense_decay_const) for rock_idx in range(len(rock_positions)): rock_symbol = RockSamplingConstants.rock_symbol(rock_idx) res[rock_...
identifier_body
Generator.py
(0, num_elems), 2)] def calculate_action_list(num_agents): all_actions = [] for agent_idx in range(num_agents): all_actions.append(CorridorConstants.move_action(agent_idx)) for agent_idx_pair in calculate_pairs(num_agents): all_actions.append(CorridorConstants.click_action(*agent_idx_pair...
(length, *args): res = [RockSamplingConstants.WILDCARD for _ in range(length)] for i in args: res[i] = PLACE_HOLDER_SYMBOL return ' '.join(res) def calculate_direction(src_tile, dst_tile): x1, y1 = src_tile[0], src_tile[1] x2, y2 = dst_tile[0], dst_tile[1] if y2 - y1 > 0: retur...
create_combination_template
identifier_name
main.rs
let world_height = world_width * height / width; let world_left = center.x - world_width / 2.0; let world_top = center.y + world_height / 2.0; let world_bottom = center.y - world_height / 2.0; (world_width, world_height, world_left, world_top, world_bottom) } fn pixel_to_world(pixel_coord: ...
unsafe { gl::ClearColor(0.2, 0.1, 0.05, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); } unsafe { set_viewport(program, zoom, &pixels, &center) }; match current_tile { Some(ref tile) => { draw_fractal(&tile.po...
conditional_block
main.rs
>, center: &Point<f64>) -> (f64, f64, f64, f64, f64) { let width = pixels.x as f64; let height = pixels.y as f64; let world_width = world_width_from_zoom(zoom); let world_height = world_width * height / width; let world_left = center.x - world_width / 2.0; let world_top = center.y + ...
gl::Clear(gl::COLOR_BUFFER_BIT); }
random_line_split
main.rs
let ns = self.nanoseconds; match ns { 0 ... 1_000 => fmt.write_fmt(format_args!("{} ns", ns)), 1_000 ... 1_000_000 => fmt.write_fmt(format_args!("{:.*} µs", 2, (ns as f64) / 1_000f64)), 1_000_000 ... 1_000_000_000 => fmt.write_fmt(...
fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(WindowHint::ContextVersion(3, 2)); glfw.window_hint(WindowHint::OpenGlForwardCompat(true)); glfw.window_hint(WindowHint::OpenGlProfile(OpenGlProfileHint::Core)); let x_initial_points = 500; let y_initial_po...
let points = colors.len() / 3; unsafe { load_vector_in_buffer(vertex_buffer, &positions); load_vector_in_buffer(color_buffer, &colors); gl::DrawArrays(gl::POINTS, 0, points as i32); window.swap_buffers(); } }
identifier_body
main.rs
let ns = self.nanoseconds; match ns { 0 ... 1_000 => fmt.write_fmt(format_args!("{} ns", ns)), 1_000 ... 1_000_000 => fmt.write_fmt(format_args!("{:.*} µs", 2, (ns as f64) / 1_000f64)), 1_000_000 ... 1_000_000_000 => fmt.write_fmt(...
buffer: u32, values: &Vec<GLfloat>) { gl::BindBuffer(gl::ARRAY_BUFFER, buffer); gl::BufferData(gl::ARRAY_BUFFER, (values.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, mem::transmute(&values[0]), gl::STATIC_DRAW); } unsafe fn bind_attribute_to_buffer(...
oad_vector_in_buffer(
identifier_name
model.rs
Task(_) = self { writeln!(out, "Deleted task {}", self.task_id())?; } else { let task = model.get_task(self.task_id()).unwrap(); // TODO match self { DeleteTask(_) => unreachable!(), AddTask(_) => writeln!(out, "Added Task {}", task.short_id())...
fn test_short_uuid_ref() {
#[test]
random_line_split
model.rs
(_) = self { writeln!(out, "Deleted task {}", self.task_id())?; } else { let task = model.get_task(self.task_id()).unwrap(); // TODO match self { DeleteTask(_) => unreachable!(), AddTask(_) => writeln!(out, "Added Task {}", task.short_id())?, ...
pub fn apply_effect(&mut self, effect: &Effect) -> () { use Effect::*; match effect.clone() { AddTask(task) => { self.add_task(task); } ChangeTaskTags { uuid, added, removed, } => { ...
{ let mut model = Self::new(); for effect in effects { model.apply_effect(&effect) } model.is_dirty = false; model }
identifier_body
model.rs
(_) = self { writeln!(out, "Deleted task {}", self.task_id())?; } else { let task = model.get_task(self.task_id()).unwrap(); // TODO match self { DeleteTask(_) => unreachable!(), AddTask(_) => writeln!(out, "Added Task {}", task.short_id())?, ...
ChangeTaskTags { uuid, added, removed, } => { self.change_task_tags(&uuid, added, removed); } ChangeTaskState(uuid, state) => { self.change_task_state(&uuid, state); } ...
{ self.add_task(task); }
conditional_block
model.rs
(_) = self { writeln!(out, "Deleted task {}", self.task_id())?; } else { let task = model.get_task(self.task_id()).unwrap(); // TODO match self { DeleteTask(_) => unreachable!(), AddTask(_) => writeln!(out, "Added Task {}", task.short_id())?, ...
(&self) -> bool { self.is_dirty } } #[cfg(test)] mod tests { use super::*; use chrono; use std::str::FromStr; use uuid::Uuid; use {Priority, Task, TaskState}; #[test] fn test_add_delete_task() { let mut m = Model::new(); let t = Task::new("foo"); m.add_t...
is_dirty
identifier_name
lib.rs
use quest_hook::inline_hook::hook; /// use quest_hook::libil2cpp::Il2CppObject; /// use log::info; /// /// #[hook("", "MainSettingsModelSO", "OnEnable")] /// fn on_enable(this: &Il2CppObject) { /// info!("MainSettingsModelSO.OnEnable was called!"); /// /// on_enable.original(this); // Call the original C# meth...
(attr: TokenStream, item: TokenStream) -> TokenStream { let punctuated_args = parse_macro_input!(attr with Punctuated<LitStr, Token![,]>::parse_separated_nonempty); let input = parse_macro_input!(item as ItemFn); match create_hook(punctuated_args, input) { Ok(ts) => ts, Err(err) => ...
hook
identifier_name
lib.rs
use quest_hook::inline_hook::hook; /// use quest_hook::libil2cpp::Il2CppObject; /// use log::info; /// /// #[hook("", "MainSettingsModelSO", "OnEnable")] /// fn on_enable(this: &Il2CppObject) { /// info!("MainSettingsModelSO.OnEnable was called!"); /// /// on_enable.original(this); // Call the original C# meth...
fn create_impl_arguments_parameters(range: ExprRange) -> Result<TokenStream, Error> { let span = range.span(); let start = range .from .ok_or_else(|| Error::new(span, "Tuple length range must have a lower bound"))?; let start = parse_range_bound(*start)?; let end = range .to ...
{ let range = parse_macro_input!(input as ExprRange); match create_impl_arguments_parameters(range) { Ok(ts) => ts, Err(err) => err.to_compile_error().into(), } }
identifier_body
lib.rs
use quest_hook::inline_hook::hook; /// use quest_hook::libil2cpp::Il2CppObject; /// use log::info; /// /// #[hook("", "MainSettingsModelSO", "OnEnable")] /// fn on_enable(this: &Il2CppObject) { /// info!("MainSettingsModelSO.OnEnable was called!"); /// /// on_enable.original(this); // Call the original C# meth...
let name = sig.ident; let return_type = sig.output; let typecheck_return_type = match &return_type { ReturnType::Default => quote! { () }, ReturnType::Type(_, ty) => quote! { #ty }, }; let hook_name = format_ident!("{}_hook", name); let hook_args = sig.inputs; let mut this_...
random_line_split
train_arch9.py
parser.add_argument('--use_cropped_img', action='store_true') parser.add_argument('--experiment_name', default=datetime.datetime.now().strftime("%Y.%m.%d-%H%M%S")) parser.add_argument('--num_ckpt', type=int, default=10) parser.add_argument('--clear', default=False, action='store_true') args = parser.parse_args() num_...
d_opt = tf.train.AdamOptimizer(lr, beta1=0.5) g_opt = tf.train.AdamOptimizer(lr, beta1=0.5) tower_d_grads = [] tower_g_grads = [] tower_d_loss_gan = [] tower_gp = [] tower_d_loss_cls = [] tower_g_loss_sim = [] tower_g_loss_r = [] tower_g_loss_r0 = [] tower_g_loss_gan = [] tower_g_loss_cls = [] tower_g_loss_cyc =...
pass
conditional_block
train_arch9.py
(x1, x2, y1, y2, margin): return tf.reduce_mean(tf.nn.relu(models.inner_product(x1, x2) - models.inner_product(y1, y2) + margin)) parser = argparse.ArgumentParser() # settings dataroot_default = './data/CelebA' parser.add_argument('--dataroot', type=str, default=dataroot_default) parser.add_argument('--dataset', t...
matching_loss
identifier_name
train_arch9.py
parser = argparse.ArgumentParser() # settings dataroot_default = './data/CelebA' parser.add_argument('--dataroot', type=str, default=dataroot_default) parser.add_argument('--dataset', type=str, default='celeba') parser.add_argument('--gpu', type=str, default='0,1', help='Specify which gpu to use b...
return tf.reduce_mean(tf.nn.relu(models.inner_product(x1, x2) - models.inner_product(y1, y2) + margin))
identifier_body
train_arch9.py
parser.add_argument('--use_cropped_img', action='store_true') parser.add_argument('--experiment_name', default=datetime.datetime.now().strftime("%Y.%m.%d-%H%M%S")) parser.add_argument('--num_ckpt', type=int, default=10) parser.add_argument('--clear', default=False, action='store_true') args = parser.parse_args() num_...
else: pass d_opt = tf.train.AdamOptimizer(lr, beta1=0.5) g_opt = tf.train.AdamOptimizer(lr, beta1=0.5) tower_d_grads = [] tower_g_grads = [] tower_d_loss_gan = [] tower_gp = [] tower_d_loss_cls = [] tower_g_loss_sim = [] tower_g_loss_r = [] tower_g_loss_r0 = [] tower_g_loss_gan = [] tower_g_loss_cls = [] towe...
xt_s = tf.gather(xs_s, permuted_index) lt_s = tf.gather(ls_s, permuted_index) rt_i = tf.gather(rs_s, permuted_index) rt_s = tf.reshape(tf.gather(r_M, rt_i), [rt_i.shape[0], args.dim_noise])
random_line_split
teslatar.py
( aPrices ): found=False i=0 dt=datetime.now() #dt=datetime(2019,4,3,11,59,59) oneHour=timedelta(hours=1) while i<len(aPrices): #print( aPrices[i][0], aPrices[i][1] ) if( aPrices[i][0]<=dt and dt<aPrices[i][0]+oneHour ): found=True break i+=1 r...
isInsidePriceHour
identifier_name
teslatar.py
=datetime.now() #dt=datetime(2019,4,3,11,59,59) oneHour=timedelta(hours=1) while i<len(aPrices): #print( aPrices[i][0], aPrices[i][1] ) if( aPrices[i][0]<=dt and dt<aPrices[i][0]+oneHour ): found=True break i+=1 return found # basic vars aChargeMode = [] ...
# update vehicle structure vehicles=tesla.vehicle_list() # this command does not effect sleep mode of car #print( vehicles ) # check every car nCar=0 info=["state","position","charge mode","idle","charge state"] while nCar<nNumCars: # ...
aPrices=getHourlyPrices() oldPriceHour = datetime.now().hour
conditional_block
teslatar.py
#gets an Array of datetime and prices (here for testing only random) def getHourlyPrices(): aPrices=[] logging.info("Query aWATTar for new pricing...") r = requests.get('https://api.awattar.de/v1/marketdata') j = r.json()["data"] #print( j ) for i in j: #print( i["start_timestamp"...
now=float(datetime.now().strftime("%H"))+float(datetime.now().strftime("%M"))/60 hoursLeft=0 if( now>then ): hoursLeft=24-now+then else: hoursLeft=then-now return( hoursLeft )
identifier_body
teslatar.py
=datetime.now() #dt=datetime(2019,4,3,11,59,59) oneHour=timedelta(hours=1) while i<len(aPrices): #print( aPrices[i][0], aPrices[i][1] ) if( aPrices[i][0]<=dt and dt<aPrices[i][0]+oneHour ): found=True break i+=1 return found # basic vars aChargeMode = [] ...
startHour = datetime.now().hour aPrices=[] oldPriceHour=-1 oldLenPrices=-1 timeToFull=[] mode=[] oldMode=[] lastModeChange=[] oldChargeLimitSoc=[] i=0 while i<nNumCars: aChargeMode+=[finishHour] aPricesChosen+=[0] mode+=[0] oldMode+=[-1] lastModeChange+=[0] oldChargeLimitSoc+=[0] timeToFull+...
random_line_split
my_agent.py
4), (8, 5), (10, 5)], (9,6): [(9, 7), (9, 5), (8, 6), (10, 6)], (9,7): [(9, 8), (9, 6), (8, 7), (10, 7)], (9,8): [(9, 9), (9, 7), (8, 8), (10, 8)], (9,9): [(9, 8), (8, 9), (10, 9)], (10,0): [(10, 1), (9, 0), (11, 0)], (10,1): [(10, 2), (10, 0), (9, 1), (11, 1)], (...
blocks = random_blocks() graph = convert_to_graph(blocks) traps = locate_traps(graph) print_graph(graph, traps) # x = solid block, O = trap. set traps=None to see a clear game state. # function to time decision making # times = [] # for i in range(500): # blocks = random_blocks() ...
conditional_block
my_agent.py
(self): ''' Place any initialisation code for your agent here (if any) ''' pass def next_move(self, game_state, player_state): ''' This method is called each time your Agent is required to choose an action If you're just starting out or are new to Python, you...
__init__
identifier_name
my_agent.py
9), (8, 9)], (8,0): [(8, 1), (7, 0), (9, 0)], (8,1): [(8, 2), (8, 0), (7, 1), (9, 1)], (8,2): [(8, 3), (8, 1), (7, 2), (9, 2)], (8,3): [(8, 4), (8, 2), (7, 3), (9, 3)], (8,4): [(8, 5), (8, 3), (7, 4), (9, 4)], (8,5): [(8, 6), (8, 4), (7, 5), (9, 5)], (8,6): [(8, 7...
def locate_traps(graph):
random_line_split
my_agent.py
, 8), (6, 9), (8, 9)], (8,0): [(8, 1), (7, 0), (9, 0)], (8,1): [(8, 2), (8, 0), (7, 1), (9, 1)], (8,2): [(8, 3), (8, 1), (7, 2), (9, 2)], (8,3): [(8, 4), (8, 2), (7, 3), (9, 3)], (8,4): [(8, 5), (8, 3), (7, 4), (9, 4)], (8,5): [(8, 6), (8, 4), (7, 5), (9, 5)], (8,...
""" Generate 43 random blocks (board always starts with 43) Can set seed for consistent testing graph """ cells = [] while len(cells) != 43: cell_to_add = (random.randint(0, 11), random.randint(0, 9)) if cell_to_add not in cells: cells.append(cell_to_add) return cells
identifier_body
calculations.js
Masa : true, // HP mlMalayalaMasa : true, // HP malayalaMasaNum : true, // HP adhimasa : true, paksa : true, tithiDay : true, ftithi : true, naksatra : true, malayalaNaksatra : true, // HP mlMalayalaNaksatra : true...
else { this.calendarData.paksa = 'Suklapaksa'; } }, fromGregorian : function (settings, gregorianDate) { // TODO: Add Tests if/when feasible _setConstants(settings); var julianDay = calendar.gregorianDateToJulianDay(gregorianDate); var ahargana = calendar.julianDayToAhargana(julianD...
{ this.calendarData.tithiDay -= 15; this.calendarData.paksa = 'Krsnapaksa'; }
conditional_block
calculations.js
Masa : true, // HP mlMalayalaMasa : true, // HP malayalaMasaNum : true, // HP adhimasa : true, paksa : true, tithiDay : true,
malayalaNaksatra : true, // HP mlMalayalaNaksatra : true, // HP sunriseTime : { hour : true, minute : true } }, setPaksa : function () { // TODO: Add Tests if/when feasible if (15 < this.calendarData.tithiDay) { this.calendarData.tithiDay -= 15; ...
ftithi : true, naksatra : true,
random_line_split
global.go
fmt.Sprintf("'%s' must be 'text' or 'json'", format)) } } } if rawURL := c.GetV1().GetExternal().GetAutomate().GetNode().GetValue(); rawURL != "" { externalAutomateURL, err := url.Parse(rawURL) if err != nil { cfgErr.AddInvalidValue("global.v1.external.automate.node", "must be url") } else { sc...
{ return w.String(strings.Join(proxy.DefaultNoProxyEntries, ",")) }
conditional_block
global.go
() error { // nolint gocyclo cfgErr := NewInvalidConfigError() if c.GetV1() == nil { cfgErr.AddMissingKey("global.v1") return cfgErr } if c.GetV1().GetFqdn() == nil { cfgErr.AddMissingKey("global.v1.fqdn") } if len(c.GetV1().GetFrontendTls()) < 1 { // It's not currently mandatory to configure frontend_...
Validate
identifier_name
global.go
", "path": p, }).Debug("failed checking for read/write/exec on path") } if err == nil && !ok { cfgErr.AddInvalidValue( "global.v1.backups.filesystem.path", fmt.Sprintf("the 'hab' user must have read/write/exec permissions to path: %s", p), ) } case "s3": if bu.GetS3().GetBucket().GetEndpoi...
if p == "" { cfgErr.AddMissingKey("global.v1.external.opensearch.auth.aws_os.password") } case "":
random_line_split
global.go
", "warning", "error", "fatal", "panic": default: cfgErr.AddInvalidValue("global.v1.log.level", fmt.Sprintf("'%s' must be one of 'debug, 'info', 'warning', 'error', 'fatal', 'panic'", level)) } } if format := log.GetFormat().GetValue(); format != "" { // logrus does support custom formatters. For ...
{ if c.V1.Proxy == nil { return nil } proxy := c.V1.Proxy if proxy.Host == nil { return nil } b := strings.Builder{} // NOTE: from testing, it appears that Rust (hab) requires "http://" to be // at the head of the proxy URLs b.WriteString("http://") // nolint: errcheck if proxy.User != nil { authPart...
identifier_body
binocular_input_topographic_map.py
'sigma_form_lateral': sigma_form_lateral, 'p_form_lateral': p_form_lateral, 'p_form_forward': p_form_forward, 'p_elim_dep': p_elim_dep, 'p_elim_pot': p_elim_pot, 'f_rew': f_rew, 'lateral_inhibition': args.lateral_inhibition, ...
plot_spikes
identifier_name
binocular_input_topographic_map.py
rac, 'a_minus': a_minus, 'a_plus': a_plus } if args.gaussian_input: gen_rate = generate_gaussian_input_rates else: gen_rate = generate_rates # +-------------------------------------------------------------------+ # | Initial network setup ...
if spikes is not None and len(spikes) > 0: f, ax1 = plt.subplots(1, 1, figsize=(16, 8)) ax1.set_xlim((0, simtime)) ax1.scatter([i[1] for i in spikes], [i[0] for i in spikes], s=.2) ax1.set_xlabel('Time/ms') ax1.set_ylabel('spikes') ax1.set_title(ti...
identifier_body
binocular_input_topographic_map.py
args.delay, 'b': b, 't_minus': tau_minus, 't_plus': tau_plus, 'tau_refrac': args.tau_refrac, 'a_minus': a_minus, 'a_plus': a_plus } if args.gaussian_input: gen_rate = generate_gaussian_input_rates else: gen_rate ...
f, ax1 = plt.subplots(1, 1, figsize=(16, 8)) ax1.set_xlim((0, simtime)) ax1.scatter([i[1] for i in spikes], [i[0] for i in spikes], s=.2)
random_line_split
binocular_input_topographic_map.py
_positions==1) positions = [left_positions, right_positions] if case == CASE_REW_NO_CORR: raise NotImplementedError elif case == CASE_CORR_AND_REW or case == CASE_CORR_NO_REW: rates = np.empty((simtime // t_stim, grid[0], grid[1])) for rate_id in range(simtime // t_stim): rand_offset = np.random...
final_ff_conn_network[int(source), int(target)] += weight
conditional_block
imaginate.rs
fn initiate_server_check_maybe_fail(&mut self) -> Result<Option<ImaginateFuture>, Error> { use futures::future::FutureExt; let Some(client) = &self.client else { return Ok(None); }; if self.pending_server_check.is_some() { return Ok(None); } self.server_status = ImaginateServerStatus::Checking; l...
{ match parse_url(name) { Ok(url) => self.host_name = url, Err(err) => self.server_status = ImaginateServerStatus::Failed(err.to_string()), } }
identifier_body
imaginate.rs
})"), Self::ImageEncode(err) => write!(f, "failed to encode png image ({err})"), Self::UnsupportedPixelType(ty) => write!(f, "pixel type `{ty}` not supported for imaginate images"), Self::InconsistentImageSize => write!(f, "image width and height do not match the image byte size"), Self::Terminated => write...
{ if let Ok(ProgressResponse { progress }) = progress { set_progress(ImaginateStatus::Generating(progress * 100.)); } response_future }
conditional_block
imaginate.rs
let url = join_url(&self.host_name, SDAPI_PROGRESS)?; let request = new_get_request(client, url)?; let (send, recv) = futures::channel::oneshot::channel(); let response_future = client.execute(request).map(move |r| { let _ = send.send(r); }); self.pending_server_check = Some(recv); Ok(Some(Box::pin(res...
(futures::future::AbortHandle); impl ImaginateTerminationHandle for ImaginateFutureAbortHandle { fn terminate(&self) { self.0.abort() } } #[derive(Debug)] enum Error { UrlParse { text: String, err: <&'static str as TryInto<Url>>::Error }, ClientBuild(reqwest::Error), RequestBuild(reqwest::Error), Request(reqw...
ImaginateFutureAbortHandle
identifier_name
imaginate.rs
} } } } pub fn server_status(&self) -> &ImaginateServerStatus { &self.server_status } pub fn is_checking(&self) -> bool { matches!(self.server_status, ImaginateServerStatus::Checking) } } #[derive(Debug)] struct ImaginateFutureAbortHandle(futures::future::AbortHandle); impl ImaginateTerminationHa...
seed: seed.await, steps: samples.await, cfg_scale: prompt_guidance.await as f64,
random_line_split
tax_task.py
_true', help='use position embed or not') parser.add_argument('--position_embed_size', type=int, default=100, help='position embed size') parser.add_argument('--position_embed_mode', type=str, default='sum', choices=['sum','concat'], help='position embed mode[sum,concat]') parser.add_argument('--self_attention_units',...
(config): # model save path model_save_dir = os.path.join("../model/tax-task", model_name, time_str) if not os.path.exists(model_save_dir): os.makedirs(model_save_dir) # log save path log_save_dir = os.path.join("../logs/tax-task", model_name, time_str) if not os.path.exists(log_save_di...
train
identifier_name