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
made.py
.qgisUserDbFilePath()).path() + "/python/plugins/dalacalc" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/dalacalc_" + locale + ".qm" i...
# run method that performs all the real work def run(self): # create and show the dialog flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMaximizeButtonHint self.dlg = DalaCalcDialog(self.iface.mainWindow(), flags) # show the dialog self.dlg.show() ...
self.iface.removePluginMenu(u"&Hitungan Kerusakan Kerugian", self.action) self.iface.removeToolBarIcon(self.action)
identifier_body
__init__.py
PUT|DELETE|TRACE|PATCH) ') _accept_html = re.compile(rb'^Accept:[^\r]*text/html', re.IGNORECASE) _keep_alive = re.compile(rb'^Connection:[^\r]*keep-alive$', re.IGNORECASE) _error_page = '''<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>wstan error</title> <style type="text/css"> body {{...
sha1 = hashlib.sha1() sha1.update(dat) return sha1.digest()
random_line_split
__init__.py
, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import logging import socket import struct import hashlib import asyncio import base64 import sys import os import re from binascii import Error as Base64Error...
(): import argparse from wstan.autobahn.websocket.protocol import parseWsUrl parser = argparse.ArgumentParser( description='Ver %s | Tunneling TCP in WebSocket' % __version__) # common config parser.add_argument('-g', '--gen-key', help='generate a key and exit', action='store_true') par...
load_config
identifier_name
__init__.py
PUT|DELETE|TRACE|PATCH) ') _accept_html = re.compile(rb'^Accept:[^\r]*text/html', re.IGNORECASE) _keep_alive = re.compile(rb'^Connection:[^\r]*keep-alive$', re.IGNORECASE) _error_page = '''<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>wstan error</title> <style type="text/css"> body {{...
sha1 = hashlib.sha1() sha1.update(dat) return sha1.digest()
identifier_body
__init__.py
, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import logging import socket import struct import hashlib import asyncio import base64 import sys import os import re from binascii import Error as Base64Error...
exceptions = [] sock = None for family, type_, proto, cname, address in infos: try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) await loop.sock_connect(sock, address) except OSError as exc: if sock is ...
raise OSError('getaddrinfo() returned empty list')
conditional_block
fs.rs
VirtioFeatures}; use crate::virtio; use crate::virtio::copy_config; use crate::virtio::fs::passthrough::PassthroughFs; use crate::virtio::fs::{process_fs_queue, virtio_fs_config, FS_MAX_TAG_LEN}; use crate::virtio::vhost::user::device::handler::{ CallEvent, DeviceRequestHandler, VhostUserBackend, }; static FS_EXE...
fn jail_and_fork( mut keep_rds: Vec<RawDescriptor>, dir_path: PathBuf, uid_map: Option<String>, gid_map: Option<String>, ) -> anyhow::Result<i32> { // Create new minijail sandbox let mut j = Minijail::new()?; j.namespace_pids(); j.namespace_user(); j.namespace_user_disable_setgrou...
{ let egid = unsafe { libc::getegid() }; format!("{} {} 1", egid, egid) }
identifier_body
fs.rs
VirtioFeatures}; use crate::virtio; use crate::virtio::copy_config; use crate::virtio::fs::passthrough::PassthroughFs; use crate::virtio::fs::{process_fs_queue, virtio_fs_config, FS_MAX_TAG_LEN}; use crate::virtio::vhost::user::device::handler::{ CallEvent, DeviceRequestHandler, VhostUserBackend, }; static FS_EXE...
{ #[argh(option, description = "path to a socket", arg_name = "PATH")] socket: String, #[argh(option, description = "the virtio-fs tag", arg_name = "TAG")] tag: String, #[argh(option, description = "path to a directory to share", arg_name = "DIR")] shared_dir: PathBuf, #[argh(option, descri...
Options
identifier_name
fs.rs
VirtioFeatures}; use crate::virtio; use crate::virtio::copy_config; use crate::virtio::fs::passthrough::PassthroughFs; use crate::virtio::fs::{process_fs_queue, virtio_fs_config, FS_MAX_TAG_LEN}; use crate::virtio::vhost::user::device::handler::{ CallEvent, DeviceRequestHandler, VhostUserBackend, }; static FS_EXE...
if pid < 0 { bail!("Fork error! {}", std::io::Error::last_os_error()); } Ok(pid) } struct FsBackend { server: Arc<fuse::Server<PassthroughFs>>, tag: [u8; FS_MAX_TAG_LEN], avail_features: u64, acked_features: u64, acked_protocol_features: VhostUserProtocolFeatures, workers...
{ unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) }; }
conditional_block
fs.rs
VirtioFeatures}; use crate::virtio; use crate::virtio::copy_config; use crate::virtio::fs::passthrough::PassthroughFs; use crate::virtio::fs::{process_fs_queue, virtio_fs_config, FS_MAX_TAG_LEN}; use crate::virtio::vhost::user::device::handler::{ CallEvent, DeviceRequestHandler, VhostUserBackend, }; static FS_EXE...
/// Starts a vhost-user fs device. /// Returns an error if the given `args` is invalid or the device fails to run. pub fn run_fs_device(program_name: &str, args: &[&str]) -> anyhow::Result<()> { let opts = match Options::from_args(&[program_name], args) { Ok(opts) => opts, Err(e) => { i...
#[argh(option, description = "uid map to use", arg_name = "UIDMAP")] uid_map: Option<String>, #[argh(option, description = "gid map to use", arg_name = "GIDMAP")] gid_map: Option<String>, }
random_line_split
analysis.py
# put the files to analyze in a folder of your choosing in the same # directory as this python file. This folder will also # need to contain a "metadata.txt" file. The metadata file # needs to be a .tsv with the filename, genre, author, title, era columns directories = ["corpus"] # Size of resultant PDF figsize = (1...
umerate(infolist[1]): if title in yeshititles: infolist[2][i] = "野史" ''' if "外史" in title or "逸史" in title or "密史" in title or "野史" in title: priorgenre = infolist[2][i] if priorgenre == "小说": infolist[2][i] = "ny" elif priorgenre == "演义": infolist[2][i] = "yy" elif priorgenre == "志存记录": ...
hoice") # Kill the program exit() for i,title in en
conditional_block
analysis.py
# put the files to analyze in a folder of your choosing in the same # directory as this python file. This folder will also # need to contain a "metadata.txt" file. The metadata file # needs to be a .tsv with the filename, genre, author, title, era columns directories = ["corpus"] # Size of resultant PDF figsize = (...
infolist = altinfo print("Making vectorizer") # create a vectorizer object to vectorize the documents into matrices. These # vectorizers return sparse matrices. # Calculate using plain term frequency if cnchoice == "tf": vectorizer = TfidfVectorizer(use_idf=False, analyzer='word', token_pattern='\S+', ngram...
nl.append(infolist[i][it]) altinfo.append(nl)
random_line_split
tools.py
data = yaml.safe_load(descriptor) except Exception as ex: raise CekitError('Cannot load descriptor', ex) if isinstance(data, basestring): LOGGER.debug("Reading descriptor from '{}' file...".format(descriptor)) if os.path.exists(descriptor): with open(descriptor, 'r') as fh...
self.os_release = {} self.platform = None os_release_path = "/etc/os-release" if os.path.exists(os_release_path): # Read the file containing operating system information with open(os_release_path, 'r') as f: content = f.readlines() s...
""" External dependency manager. Understands on what platform are we currently running and what dependencies are required to be installed to satisfy the requirements. """ # List of operating system families on which CEKit is known to work. # It may work on other operating systems too, but it wa...
identifier_body
tools.py
as ex: if ex.output is not None and 'AuthError' in ex.output: LOGGER.warning( "Brew authentication failed, please make sure you have a valid Kerberos ticket") raise CekitError("Could not fetch archives for checksum {}".format(md5), ex) archives = yam...
handle_core_dependencies
identifier_name
tools.py
data = yaml.safe_load(descriptor) except Exception as ex: raise CekitError('Cannot load descriptor', ex) if isinstance(data, basestring): LOGGER.debug("Reading descriptor from '{}' file...".format(descriptor)) if os.path.exists(descriptor): with open(descriptor, 'r') as fh...
LOGGER.debug("All dependencies provided!") # pylint: disable=R0201 def _check_for_library(self, library): library_found = False if sys.version_info[0] < 3: import imp try: imp.find_module(library) library_found = True ...
self._check_for_executable(dependency, executable)
conditional_block
tools.py
data = yaml.safe_load(descriptor) except Exception as ex: raise CekitError('Cannot load descriptor', ex) if isinstance(data, basestring): LOGGER.debug("Reading descriptor from '{}' file...".format(descriptor)) if os.path.exists(descriptor): with open(descriptor, 'r') as fh...
# 'BUILDING': 0 # 'COMPLETE': 1 # 'DELETED': 2 # 'FAILED': 3 # 'CANCELED': 4 if build['state'] != 1: raise CekitError( "Artifact with checksum {} was found in Koji metadata but the build is in incorrect state ({}) making " "the ...
#
random_line_split
deploy.go
[]string) { defer log.Flush() stx.EnsureVaultSession(config) if flags.DeployDeps { flags.DeploySave = true } availableStacks := make(map[string]deployArgs) workingGraph := graph.NewGraph() buildInstances := stx.GetBuildInstances(args, config.PackageName) stx.Process(buildInstances, flags, log, f...
changeSetName := "stx-dpl-" + usr.Username + "-" + fmt.Sprintf("%x", sha1.Sum(templateFileBytes)) // validate template validateTemplateInput := cloudformation.ValidateTemplateInput{ TemplateBody: &templateBody, } validateTemplateOutput, validateTemplateErr := cfn.ValidateTemplate(&validateTemplateInput) // te...
{ fileName, saveErr := saveStackAsYml(stack, buildInstance, stackValue) if saveErr != nil { log.Error(saveErr) } log.Infof("%s %s %s %s:%s\n", au.White("Deploying"), au.Magenta(stack.Name), au.White("⤏"), au.Green(stack.Profile), au.Cyan(stack.Region)) log.Infof("%s", au.Gray(11, " Validating template...")) ...
identifier_body
deploy.go
() { rootCmd.AddCommand(deployCmd) deployCmd.Flags().BoolVarP(&flags.DeployWait, "wait", "w", false, "Wait for stack updates to complete before continuing.") deployCmd.Flags().BoolVarP(&flags.DeploySave, "save", "s", false, "Save stack outputs upon successful completion. Implies --wait.") deployCmd.Flags().BoolVarP...
init
identifier_name
deploy.go
} // TODO #47 parameters need to support the type as declared in Parameter.Type (in the least string and number). // this should be map[string]interface{} with type casting done when adding parameters to the changeset var override map[string]string yamlUnmarshalErr := yaml.Unmarshal(yamlBytes, &overri...
ecuteChangeSetErr) } if flags.Depl
conditional_block
deploy.go
behavior.Map) > 0 { // map the yaml key:value to parameter key:value for k, v := range behavior.Map { fromKey := k toKey := v parametersMap[toKey] = override[fromKey] } } else { // just do a straight copy, keys should align 1:1 for k, v := range override { overrideKe...
if flags.DeploySave { saveErr := saveStackOutputs(buildInstance, stack) if saveErr != nil { log.Fatal(saveErr)
random_line_split
http.go
.InterfacesTotal[i].In, prevtotals[i].In), DeltaOut: bps(s.InterfacesTotal[i].Out, prevtotals[i].Out), } } sort.Sort(interfaceOrder(ifs)) return ifs } func(s state) cpudelta() sigar.CpuList { prev := s.PREVCPU if len(prev.List) == 0 { return s.RAWCPU } // cls := s.RAWCPU cls := sigar.CpuList{List: make...
(disks []diskInfo, seq types.SEQ) []types.DiskData { sort.Stable(diskOrder{ disks: disks, seq: seq, reverse: _DFBIMAP.SEQ2REVERSE[seq], }) var dd []types.DiskData for _, disk := range disks { total, approxtotal := humanBandback(disk.Total) used, approxused := humanBandback(disk.Used) itotal, appr...
orderDisk
identifier_name
http.go
(s.InterfacesTotal[i].In, prevtotals[i].In), DeltaOut: bps(s.InterfacesTotal[i].Out, prevtotals[i].Out), } } sort.Sort(interfaceOrder(ifs)) return ifs } func(s state) cpudelta() sigar.CpuList { prev := s.PREVCPU if len(prev.List) == 0 { return s.RAWCPU } // cls := s.RAWCPU cls := sigar.CpuList{List: ma...
stateLock.Lock() defer stateLock.Unlock() lastState.PrevInterfacesTotal = []InterfaceTotal{} lastState.PREVCPU.List = []sigar.Cpu{} } func collect() { // state stateLock.Lock() defer stateLock.Unlock() prev_ifstotal := lastState.InterfacesTotal prev_cpu := lastState.RAWCPU ifs, ip := NewInterface...
var stateLock sync.Mutex var lastState state func reset_prev() {
random_line_split
http.go
.InterfacesTotal[i].In, prevtotals[i].In), DeltaOut: bps(s.InterfacesTotal[i].Out, prevtotals[i].Out), } } sort.Sort(interfaceOrder(ifs)) return ifs } func(s state) cpudelta() sigar.CpuList { prev := s.PREVCPU if len(prev.List) == 0 { return s.RAWCPU } // cls := s.RAWCPU cls := sigar.CpuList{List: make...
sum.User += cp.User + cp.Nice sum.Sys += cp.Sys sum.Idle += cp.Idle } total := sum.User + sum.Sys + sum.Idle // + sum.Nice user := percent(sum.User, total) sys := percent(sum.Sys, total) idle := uint(0) if user + sys < 100 { idle = 100 - user - sys } c.N = len(cls.List) c.User, c.AttrUser = u...
{ sum := sigar.Cpu{} cls := s.cpudelta() c := types.CPU{List: make([]types.CPU, len(cls.List))} for i, cp := range cls.List { total := cp.User + cp.Nice + cp.Sys + cp.Idle user := percent(cp.User, total) sys := percent(cp.Sys, total) idle := uint(0) if user + sys < 100 { idle = 100 - user - sys ...
identifier_body
http.go
.InterfacesTotal[i].In, prevtotals[i].In), DeltaOut: bps(s.InterfacesTotal[i].Out, prevtotals[i].Out), } } sort.Sort(interfaceOrder(ifs)) return ifs } func(s state) cpudelta() sigar.CpuList { prev := s.PREVCPU if len(prev.List) == 0 { return s.RAWCPU } // cls := s.RAWCPU cls := sigar.CpuList{List: make...
Iused: iused, Ifree: humanB(disk.Ifree), IusePercent: formatPercent(approxiused, approxitotal), DirName: disk.DirName, AttrUsePercent: labelAttr_colorPercent(percent(approxused, approxtotal)), AttrIusePercent: labelAttr_colorPercent(percent(approxiused, approxitotal)), }) } re...
{ total, approxtotal := humanBandback(disk.Total) used, approxused := humanBandback(disk.Used) itotal, approxitotal := humanBandback(disk.Inodes) iused, approxiused := humanBandback(disk.Iused) short := "" if len(disk.DevName) > 10 { short = disk.DevName[:10] } dd = append(dd, types.DiskData...
conditional_block
prohack-github.py
df[3865:] test=test.drop("y", axis = 1) test_res= test.copy() # %% [markdown] # ### Checking how many galaxies are there and how many of them are distinct. # # - There are **181** distinct galaxies on the training set and **172** on the test set. # # - On overall they each galaxy has **20** samples on the training ...
%% print(errors) # [-0.005510409192904806, -0.005474700678841418, -0.005478204236398942, -0.005493891458843025, -0.005485265856592613, -0.005493237060981963, -0.005493713846323645, -0.0055068515842603225] # %% [markdown] # ## Making predictions on the test data # # - Similar methodology is used to fill the missing v...
("cor: ",x) errors.append(loop_train(x)) #
conditional_block
prohack-github.py
[train['galaxy'] == x]) print("Total distinct galaxies: {}".format(len(train_gal))) print("Average samples per galaxy: {}".format(s/len(train_gal))) # %% test_gal=set(test["galaxy"]) s=0 for x in test_gal: s=s+len(test.loc[test['galaxy'] == x]) print("Total distinct galaxies: {}".format(len(test_gal))) print("Ave...
# # E.g: If the original p^2 value is higher than the predicted p^2, it will increase the error as we are directly giving it 0. #
random_line_split
prohack-github.py
[3865:] test=test.drop("y", axis = 1) test_res= test.copy() # %% [markdown] # ### Checking how many galaxies are there and how many of them are distinct. # # - There are **181** distinct galaxies on the training set and **172** on the test set. # # - On overall they each galaxy has **20** samples on the training set...
: errors=[] for gal in tqdm(train_gal): index = train.index[train['galaxy'] == gal] data = train.loc[index] errors.append(cross_validation_loop(data,cor)) return np.mean(errors) # %% [markdown] # #### Checking which correlation threshold gives better value # # The model performs be...
train(cor)
identifier_name
prohack-github.py
[3865:] test=test.drop("y", axis = 1) test_res= test.copy() # %% [markdown] # ### Checking how many galaxies are there and how many of them are distinct. # # - There are **181** distinct galaxies on the training set and **172** on the test set. # # - On overall they each galaxy has **20** samples on the training set...
% [markdown] # #### Checking which correlation threshold gives better value # # The model performs best when the threshold is 20 with RMSE of 0.0063 # %% cor=[20,25,30,40,50,60,70,80] errors=[] for x in cor: print("cor: ",x) errors.append(loop_train(x)) # %% print(errors) # [-0.005510409192904806, -0.0054...
s=[] for gal in tqdm(train_gal): index = train.index[train['galaxy'] == gal] data = train.loc[index] errors.append(cross_validation_loop(data,cor)) return np.mean(errors) # %
identifier_body
myRansac.py
] ) is None: continue new_d = time.strptime( lstr[0], '%Y/%m/%d' ) if new_d < BS_DATE: continue b = float( lstr[idx] ) data.append( [lstr[0], b] ) return data, csv_name def GetCleanData( data_x, data_y ): i = 0 j = 0 data_out = [] while i...
str = 'FYI: This mail is sent from a Ransac dev\r\n' str += 'Which IP addr is %s'%my_ip[0] txt = MIMEText(str) message.attach(txt) if self.tag is not None: message['Subject'] = Header(self.tag,'utf-8') if self.user is not None: message['Fr...
self.to_list = ['sunber.chou@qq.com'] self.cc_list = ['zhousongbo@hanmingtech.com'] self.tag = 'Finally, Ransac get result!' self.doc = None return def send(self): ret = True try: mail_host = smtplib.SMTP_SSL('smtp.exmail.qq.com', port=46...
identifier_body
myRansac.py
fits well to data #Return: # bestfit - model parameters which best fit the data (or nil if no good model is found) def ransac(data,model,n,k,t,d): iterations = 0 bestfit = None besterr = numpy.inf best_inlier_idxs = None best_d = d while iterations < k: maybe_idxs, test_idx...
fnList = LOCAL_PATH + 'A_result.txt' with open( fnList, 'w', encoding='utf-8') as fw_p:
random_line_split
myRansac.py
[idx] ) is None: continue new_d = time.strptime( lstr[0], '%Y/%m/%d' ) if new_d < BS_DATE: continue b = float( lstr[idx] ) data.append( [lstr[0], b] ) return data, csv_name def GetC
ta_x, data_y ): i = 0 j = 0 data_out = [] while i < len( data_x ) and j < len( data_y ): item_x = data_x[i] item_y = data_y[j] tx = time.strptime( item_x[0], '%Y/%m/%d' ) ty = time.strptime( item_y[0], '%Y/%m/%d' ) if tx < ty: i += 1 ...
leanData( da
identifier_name
myRansac.py
[idx] ) is None: continue new_d = time.strptime( lstr[0], '%Y/%m/%d' ) if new_d < BS_DATE: continue b = float( lstr[idx] ) data.append( [lstr[0], b] ) return data, csv_name def GetCleanData( data_x, data_y ): i = 0 j = 0 data_out = [] whi...
), 'utf-8') if self.doc: fn = os.path.basename( self.doc ) with open(self.doc,'rb') as f: doc = MIMEText(f.read(), 'base64', 'utf-8') doc["Content-Type"] = 'application/octet-stream' doc["Content-Disposition"] = 'attachment; filename...
message['Cc'] = Header(';'.join(self.cc_list
conditional_block
3DMain.js
*/ function setScreen(n, data, projManager, projectId, currentLayerObjList) { planArr = data; if (n == 1) { $("#earthDiv0,#earthDiv1,#earthDiv2").removeClass("s1 s2 s3 s4").addClass("hide"); $("#earthDiv0").removeClass("hide").addClass("s1"); for (var i = parent.earthArray.length - 1; i...
* @param n 屏幕数
random_line_split
3DMain.js
, firstId, true, true, false, false,true); },100); //第二个是现状 secordId 需要把现状数据库图层的都加上即可 parent.loadXZLayers(true, earth1); }else{ //两个都是方案 setTimeout(function(){ projManager.showAll...
se{ if(dataValue < minValue){
conditional_block
3DMain.js
if(htmlBalloons){ htmlBalloons.DestroyObject(); htmlBalloons=null; } var geoPoint = seearth.GlobeObserver.Pick(posX,posY); var guid = seearth.Factory.CreateGuid(); htmlBalloons = seearth.Factory.CreateHtmlBalloon(guid, "balloon"); htmlBalloons.SetSphericalLocation(geoPoint.Longit...
parent.htmlBalloon; var posX = parseInt(pVal.substring(pVal.indexOf("<posX>")+6, pVal.indexOf("</posX>"))); var posY = parseInt(pVal.substring(pVal.indexOf("<posY>")+6, pVal.indexOf("</posY>"))); var loaclUrl = window.location.href.substring(0, window.location.href.lastIndexOf("/")); var url = loaclUrl + "/res/c...
identifier_body
3DMain.js
缩小 因此采用下面两行代码强行设置宽高比例! document.getElementById("earthDiv0").style.width="50%"; document.getElementById("earthDiv0").style.height="100%"; document.getElementById("earthDiv1").style.width="50%"; document.getElementById("earthDiv1").style.height="100%"; //第二个球加载在右边 $("#ear...
; earth.classid = "CLSID:EA3EA17C-5724-4104-94D8-4EECBD352964"; earth.style.width = "100%"; earth.style.height = "100%"; div.appendChild(earth); earth.Event.OnCreateEarth = function (searth) { earth.Event.OnCreateEarth = function () {}; parent.earthArray.push(searth); searth....
th.name = id
identifier_name
pygit.py
list of repositories by running master_directory : str The absolute path to the directory git_exec : str The path to the git executable on the system message : str Commit message Returns -------- : Commands object """ def __str__(self): return "Commands: {...
"""Write status of all repositories to file in markdown format""" print("Getting repo status.\n\nYou may be prompted for credentials...") os.chdir(STATUS_DIR) attention = "" messages = [] TIME_STAMP = datetime.now().strftime("%a_%d_%b_%Y_%H_%M_%S_%p") fname = "REPO_STATUS_@_{}.md".format(TIME_...
identifier_body
pygit.py
(str(PurePath(SHELF_DIR / "MASTER_SHELF"))) MASTER_SHELF["master"] = master_directory MASTER_SHELF.close() def shelve_master_directory(master_directory, verbosity, rules): """Find and store the locations of git repos""" if master_directory: save_master(master_directory) show_verbose_o...
process = Popen([self.git_exec, ' git push'], stdin=PIPE, stdout=PIPE, stderr=STDOUT,)
conditional_block
pygit.py
_DIR / "NAME_SHELF"))) master = MASTER_SHELF["master"] print("Master ", master) # shelve_master_directory(master, 0, "") save_master(master) i = len(list(INDEX_SHELF.keys())) + 1 folder_paths = [x for x in Path(master).iterdir() if x.is_dir()] for folder_name in folder_paths: path...
push
identifier_name
pygit.py
', '--masterDirectory', help="Full pathname to directory holding any number of git repos.") parser.add_argument('-s', '--simpleDirectory', help="A list of full pathnames to any number of individual git repos.", nargs='+') return parser.parse_args() def shelve_git_path(git_path, verbosity): """Find and sto...
i = len(list(INDEX_SHELF.keys())) + 1 folder_paths = [x for x in Path(master).iterdir() if x.is_dir()] for folder_name in folder_paths: path = Path(master) / folder_name directory_absolute_path = Path(path).resolve() if is_git_repo(directory_absolute_path): if sys.platf...
random_line_split
merge.go
ux.Unlock() if ETLMergeTaskPool == nil { mp, err := mpool.NewMPool("etl_merge_task", 0, mpool.NoFixed) if err != nil { return nil, err } ETLMergeTaskPool = mp } return ETLMergeTaskPool, nil } func NewMerge(ctx context.Context, opts ...MergeOption) (*Merge, error) { var err error m := &Merge{ pathBuil...
w) } if err != nil { m.logger.Warn("failed to read file", logutil.PathField(fp.FilePath), zap.Error(err)) return err } // sql insert if cacheFileData.Size() > 0 { if err = cacheFileData.Flush(m.table); err != nil { return err } cacheFileData.Reset() } // delete empty file or file a...
rse ETL rows failed", logutil.TableField(m.table.GetIdentify()), logutil.PathField(fp.FilePath), logutil.VarsField(SubStringPrefixLimit(fmt.Sprintf("%v", line), 102400)), ) return err } cacheFileData.Put(ro
conditional_block
merge.go
for idx := 0; idx < length; idx++ { fileList = append(fileList, l.Remove(l.Front()).(string)) } return fileList, nil } // doMergeFiles handle merge (read->write->delete) ops for all files in the target directory. // Handle the files one by one, act uploadFile and do the deletion if upload is success. // Upload th...
ext.Context, ta
identifier_name
merge.go
} } length := l.Len() fileList := make([]string, 0, length) for idx := 0; idx < length; idx++ { fileList = append(fileList, l.Remove(l.Front()).(string)) } return fileList, nil } // doMergeFiles handle merge (read->write->delete) ops for all files in the target directory. // Handle the files one by one, act u...
etCsvStrings()) c.size += r.Size() } func (c *SliceCache) S
identifier_body
merge.go
const LoggerNameContentReader = "ETLContentReader" const MAX_MERGE_INSERT_TIME = 10 * time.Second const defaultMaxFileSize = 32 * mpool.MB // ======================== // handle merge // ======================== // Merge like a compaction, merge input files into one/two/... files. // - NewMergeService init merge as ...
) const LoggerNameETLMerge = "ETLMerge"
random_line_split
pg_v6.x.x.js
// `Function` types exised in this file, cause of they come from another // untyped npm lib. /* Cause of <flow 0.36 did not support export type very well, // so copy the types from pg-pool // https://github.com/flowtype/flow-typed/issues/16 // https://github.com/facebook/flow/commit/843389f89c69516506213e2...
random_line_split
domaintools.py
- mesh using marching cubes - calculate volume and area of domains using mesh ''' def __init__(self,coords,fields, density_field_index=0, density_threshold = 0.5): ''' Define and calculate useful variables for DomainAnalysis routines ''' self.__coords = coords ...
random_line_split
domaintools.py
entire domain is continuous (ie not split across boundaries) 2) Grab a little margin around each domain (the domain's "border") so that marching cubes can interpolate. The border is computed in identifyAndIndexDomains(). 3) Mesh the domain using marching cubes ''' isdomain = (s...
plt.show() plt.savefig(filename)
conditional_block
domaintools.py
volume = np.zeros(self.__ndomains) IQ = np.zeros(self.__ndomains) #for each domain for idomain in range(0,self.__ndomains): # calc center of domain com[idomain,:] = self.calcDomainCOM(idomain+1,units='coord') if useMesh: if self...
(self, area, vol): '''returns isoperimetric coefficient. 1 for perfect circle or sphere, less for other shapes note that in 2d "area" is actually perimeter, and "vol" is actually area This difference didn't seem to warrant a completely different method though ''' if self.__...
calcIQ
identifier_name
domaintools.py
ax = fig.add_subplot(111, projection='3d') # Fancy indexing: `verts[faces]` to generate a collection of triangles mesh = Poly3DCollection(verts[faces]) mesh.set_edgecolor('k') ax.add_collection3d(mesh) ax.set_xlim(0, self.__boxl[0]) ax.set_ylim(0, self.__boxl[1]) ...
''' Returns mean squared displacement (averaged over all micelles) ''' assert(self.__is_init_pos) return np.average(self.__sqdisp)
identifier_body
BackendMapping.ts
true, draggable : true }; // チームに関するデータ private teamSetting:any = []; private teamData:any = []; private teamMarker:any = []; private teamRoot:any = []; // テンプレート private template = { filterTeam: Cmn.dir + '/mus/filterTeam.mustache', fukudashi : Cmn.dir + '/mus/fukidashi.mustache',...
/** * チームデータの格納 * @param data */ setTeamList(data) { var elem = '', count = data.length; $.get(this.template.filterTeam, (template)=> { for (var i = 0, iLen = data.length; i < iLen; i++) { var obj = data[i], data_id = 0, isArr = this.teamSetting.filter((elem...
}); }
identifier_name
BackendMapping.ts
true, draggable : true }; // チームに関するデータ private teamSetting:any = []; private teamData:any = []; private teamMarker:any = []; private teamRoot:any = []; // テンプレート private template = { filterTeam: Cmn.dir + '/mus/filterTeam.mustache', fukudashi : Cmn.dir + '/mus/fukidashi.mustache',...
visible = (this.viewTeam === obj.team || this.viewTeam == = '') ? '' : ' hide'; obj.color = this.teamSetting[obj.team_id].color; obj.category = this.category[obj.cat]; obj.cls = visible; obj.created = this.getTimeDiff(obj.created_at); elem += Mustache.render(template, ...
this.teamData.push(obj); } $('#filter-team').append(elem); this.setMarker(count); this.setList(count); }); } /** * 登録データの表示 * @param count */ setList(count){ var diff = this.teamData.length - count; // 追加データの個数を返却 $.get(this.template.list, (template)=>{ v...
conditional_block
BackendMapping.ts
true, draggable : true }; // チームに関するデータ private teamSetting:any = []; private teamData:any = []; private teamMarker:any = []; private teamRoot:any = []; // テンプレート private template = { filterTeam: Cmn.dir + '/mus/filterTeam.mustache', fukudashi : Cmn.dir + '/mus/fukidashi.mustache',...
} /** * チームデータの格納 * @param data */ setTeamList(data) { var elem = '', count = data.length; $.get(this.template.filterTeam, (template)=> { for (var i = 0, iLen = data.length; i < iLen; i++) { var obj = data[i], data_id = 0, isArr = this.teamSetting.filter(...
} });
random_line_split
BackendMapping.ts
true, draggable : true }; // チームに関するデータ private teamSetting:any = []; private teamData:any = []; private teamMarker:any = []; private teamRoot:any = []; // テンプレート private template = { filterTeam: Cmn.dir + '/mus/filterTeam.mustache', fukudashi : Cmn.dir + '/mus/fukidashi.mustache',...
f (isArr.length === 0) { var len = this.teamSetting.length, //color_code = Math.floor(Math.random() * 16777215).toString(16), color_code = this.getRandomColor(this.teamSetting), team = { name : obj.team, color: color_code, id : le...
** * チームデータの格納 * @param data */ setTeamList(data) { var elem = '', count = data.length; $.get(this.template.filterTeam, (template)=> { for (var i = 0, iLen = data.length; i < iLen; i++) { var obj = data[i], data_id = 0, isArr = this.teamSetting.filter((elem, i...
identifier_body
download_params_and_roslaunch_agent.py
ore import boto3 import yaml import rospy from markov import utils_parse_model_metadata from markov.utils import force_list from markov.constants import DEFAULT_COLOR from markov.architecture.constants import Input from markov.utils import get_boto_config from markov.log_handler.constants import (SIMAPP_EVENT_ERROR_CO...
(yaml_values, multicar): """ Validate that the parameter provided in the yaml file for configuration is correct. Some of the params requires list of two values. This is mostly checked as part of this function Arguments: yaml_values {[dict]} -- [All the yaml parameter as a list] multicar {[bo...
validate_yaml_values
identifier_name
download_params_and_roslaunch_agent.py
markov.utils import force_list from markov.constants import DEFAULT_COLOR from markov.architecture.constants import Input from markov.utils import get_boto_config from markov.log_handler.constants import (SIMAPP_EVENT_ERROR_CODE_400, SIMAPP_EVENT_ERROR_CODE_500, SIMAPP_SIMULA...
'''local_yaml_path - path to the local yaml file ''' with open(local_yaml_path, 'r') as stream: try: return yaml.safe_load(stream) except yaml.YAMLError as exc: log_and_exit("yaml read error: {}".format(exc), SIMAPP_SIMULATION_WORKER_EXCEPTION, SI...
identifier_body
download_params_and_roslaunch_agent.py
ore import boto3 import yaml import rospy from markov import utils_parse_model_metadata from markov.utils import force_list from markov.constants import DEFAULT_COLOR from markov.architecture.constants import Input from markov.utils import get_boto_config from markov.log_handler.constants import (SIMAPP_EVENT_ERROR_CO...
cmd = [''.join(("roslaunch deepracer_simulation_environment {} ".format(launch_name), "local_yaml_path:={} ".format(local_yaml_path), "racecars_with_stereo_cameras:={} ".format(','.join(racecars_with_stereo_cameras)), "racecars_with_lida...
racecars_with_lidars.append(racecar_name)
conditional_block
download_params_and_roslaunch_agent.py
APP_SIMULATION_WORKER_EXCEPTION) from markov.log_handler.logger import Logger from markov.log_handler.exception_handler import log_and_exit LOG = Logger(__name__, logging.INFO).get_logger() # Pass a list with 2 values for CAR_COLOR, MODEL_S3_BUCKET, MODEL_S3_PREFIX, MODEL_METADATA_FILE_S3_KEY for multicar CAR_COLOR_Y...
default_val_keys = default_vals.keys() if default_vals else []
random_line_split
2_tracking.py
]] # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1]) # computing the sum_area sum_area = S_rec1 + S_rec2 # find the each edge of intersect rectangle left_line = max(rec1[1], rec2[1]) right_line = m...
def Hungary(task_matrix): b = task_matrix.copy() # 行和列减0 for i in range(len(b)): row_min = np.min(b[i]) for j in range(len(b[i])): b[i][j] -= row_min for i in range(len(b[0])): col_min = np.min(b[:, i]) for j in range(len(b)): b[j][i] -= col_min ...
box = self.boxes[i] print('box', i, ': ', box)
random_line_split
2_tracking.py
]] # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1]) # computing the sum_area sum_area = S_rec1 + S_rec2 # find the each edge of intersect rectangle left_line = max(rec1[1], rec2[1]) right_line = m...
ottom_line - top_line) return float(intersect) / (sum_area - intersect) class Box(object): """ match_state:一个box是否匹配到一个track中,若没有,应该生成新的track """ def __init__(self, frame_index, id, box, score, gps_coor, feature): self.frame_index = frame_index self.id = id self.box = b...
line) * (b
conditional_block
2_tracking.py
]] # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1]) # computing the sum_area sum_area = S_rec1 + S_rec2 # find the each edge of intersect rectangle left_line = max(rec1[1], rec2[1]) right_line = m...
.index) + ' : ', "length-" + len(self.boxes)) for i in range(len(self.boxes)): box = self.boxes[i] print('box', i, ': ', box) def Hungary(task_matrix): b = task_matrix.copy() # 行和列减0 for i in range(len(b)): row_min = np.min(b[i]) for j in range(len(b[i])): ...
: print("For frame index-" + str(self
identifier_body
2_tracking.py
, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ rec1 = [box1[0], box1[1], box1[0] + box1[2], box1[1] + box1[3]] rec2 = [box2[0], box2[1], box2[0] + box2[2], box2[1] + box2[3]] # computing area of each rectangles ...
m rec1: (y0
identifier_name
add-action-form.component.ts
boolean = false; resultValue: any = {}; appAttributeParams: any = {}; validateForm: FormGroup; code: any; nameverification: any;//name conturi: any; //功能地址 contauthorizationUri: any = '只能输入数字、26个英文字母(大小写)、:/?&#-_{}.=,多个URL以英文逗号分隔'; private checkPwd: any = CheckRegExp(this.regService.getPwd()) idNum: ...
rols['checkPassword'].updateValueAndValidity(); }); } getCaptcha(e: MouseEvent) { e.preventDefault(); } // confirmationValidator = (control: FormControl): { [s: string]: boolean } => { // if (!control.value) { // return { required: true }; // } else if (control.value !== this.validateFor...
} updateConfirmValidator() { /** wait for refresh value */ setTimeout(() => { this.validateForm.cont
identifier_body
add-action-form.component.ts
refresh value */ setTimeout(() => { this.validateForm.controls['checkPassword'].updateValueAndValidity(); }); } getCaptcha(e: MouseEvent) { e.preventDefault(); } // confirmationValidator = (control: FormControl): { [s: string]: boolean } => { // if (!control.value) { // return { r...
this.action =
identifier_name
add-action-form.component.ts
if (this.validateForm.invalid) { return; } this.resultData.emit(this.resultValue); this.onSubmit.emit(this.validateForm); } constructor(private regService: RegexpSService, private fb: FormBuilder, private service: AddActionFormService, private route: ActivatedRoute ) { this.subscriptio...
random_line_split
add-action-form.component.ts
boolean = false; resultValue: any = {}; appAttributeParams: any = {}; validateForm: FormGroup; code: any; nameverification: any;//name conturi: any; //功能地址 contauthorizationUri: any = '只能输入数字、26个英文字母(大小写)、:/?&#-_{}.=,多个URL以英文逗号分隔'; private checkPwd: any = CheckRegExp(this.regService.getPwd()) idNum: ...
() { //监听service里的id值,当编辑时传id if (this.validateForm) { return false; } const that = this; if (this.id) {//当操作为编辑时,添加id值 this.validateForm = this.fb.group({ name: [null, [Validators.required, Validators.minLength(2), Validators.maxLength(100), Validators.pattern(/^\S.*\S$|^\S$/)]...
null; } }; initValidateForm
conditional_block
__init__.py
process.communicate() if stdout: stdout = stdout.rstrip(' \n') else: stdout = "" if stderr: stderr = stderr.rstrip(' \n') else: stderr = "" return (process.returncode, stdout, stderr) def detectSystem(): (returncode, stdout, stderr) = runCommand("hostname") if returncode != 0: raise BatchelorExcepti...
error = False if system != "" and not config.has_section(system): print("ERROR: System set but corresponding section is missing in config file.") error = True requiredOptions = { "c2pap": [ "group", "notification", "notify_user", "node_usage", "wall_clock_limit", "resources", "job_type", "class" ], ...
print("ERROR: Could not read config file '" + configFileName + "'.") return False
conditional_block
__init__.py
process.communicate() if stdout: stdout = stdout.rstrip(' \n') else: stdout = "" if stderr: stderr = stderr.rstrip(' \n') else: stderr = "" return (process.returncode, stdout, stderr) def detectSystem(): (returncode, stdout, stderr) = runCommand("hostname") if returncode != 0: raise BatchelorExcepti...
self._config = ConfigParser.RawConfigParser() def bprint(self, msg): self.bprintTicker += ('' if self.bprintTicker == '' else '\n') + msg if self.debug: print(msg) def initialize(self, configFileName, systemOverride = ""): self.bprint("Initializing...") if not self._config.read(os.path.abspath(configFi...
bprintTicker = "" batchFunctions = None def __init__(self):
random_line_split
__init__.py
process.communicate() if stdout: stdout = stdout.rstrip(' \n') else: stdout = "" if stderr: stderr = stderr.rstrip(' \n') else: stderr = "" return (process.returncode, stdout, stderr) def detectSystem(): (returncode, stdout, stderr) = runCommand("hostname") if returncode != 0: raise BatchelorExcepti...
(self, jobs): # 'jobs' should be a list of arguments as they need to be specified for # 'submitJob', e.g.: # [ [ "command 1", "output file 1", "name 1" ], # [ "command 2", "output file 2", None ], # ... ] # The return value is a list of job IDs in the same order as the jobs. # A job ID of ...
submitJobs
identifier_name
__init__.py
def runCommand(commandString): commandString = "errHandler() { (( errcount++ )); }; trap errHandler ERR\n" + commandString.rstrip('\n') + "\nexit $errcount" process = subprocess.Popen(commandString, shell=True, stdout=subprocess.PIPE, ...
def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
identifier_body
clob.rs
/// Создает читателя данного символьного объекта. Каждый вызов метода `read` читателя читает очередную порцию данных. /// Данные читаются из CLOB-а в кодировке `UTF-8`. #[inline] pub fn new_reader<'lob>(&'lob mut self) -> Result<ClobReader<'lob, 'conn>> { self.new_reader_with_charset(Charset::AL32UTF8) } ...
res, piece) = self.lob.impl_.read(self.piece, self.charset, self.lob.for
conditional_block
clob.rs
символьного объекта. Каждый вызов метода `read` читателя читает очередную порцию данных. /// Данные читаются из CLOB-а в кодировке `UTF-8`. #[inline] pub fn new_reader<'lob>(&'lob mut self) -> Result<ClobReader<'lob, 'conn>> { self.new_reader_with_charset(Charset::AL32UTF8) } /// Создает читателя данного...
читателем. pub fn lob(&mut self) -> &mut Clob<'conn> { self.lob } } impl<'lob, 'conn: 'lob> io::Read for ClobReader<'lob, 'conn> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let (res, piece) = self.lob.impl_.read(self.piece, self.charset, self.lob.form, buf); self.piece = p
identifier_body
clob.rs
/// В зависимости от настроек сервера базы данных данное значение может варьироваться от /// 8 до 128 терабайт (TB). #[inline] pub fn capacity(&self) -> Result<Bytes> { let len = try!(self.impl_.capacity()); Ok(Bytes(len)) } /// For LOBs with storage parameter `BASICFILE`, the amount of a chunk's spa...
} /// Создает читателя данного символьного объекта. Каждый вызов метода `read` читателя читает очередную порцию данных. /// Данные читаются из CLOB-а в указанной кодировке. /// /// Каждый вызов `read` будет заполнять массив байтами в запрошенной кодировке. Так как стандартные методы Rust для /// работы чита...
/// Данные читаются из CLOB-а в кодировке `UTF-8`. #[inline] pub fn new_reader<'lob>(&'lob mut self) -> Result<ClobReader<'lob, 'conn>> { self.new_reader_with_charset(Charset::AL32UTF8)
random_line_split
clob.rs
2UTF8) } /// Создает читателя данного символьного объекта. Каждый вызов метода `read` читателя читает очередную порцию данных. /// Данные читаются из CLOB-а в указанной кодировке. /// /// Каждый вызов `read` будет заполнять массив байтами в запрошенной кодировке. Так как стандартные методы Rust для /// рабо...
identifier_name
visualization.py
(x): if '__' in x: return [int(x) for x in x.split('__')[1].split('_')] else: return [0] df['var type'] = df['index'].apply(lambda x: x.split('__')[0]) df = df.loc[df['var type'] == var, :] var_idxs = df['index'].apply(split_fun) indexs = np.stack(var_idxs) i...
split_fun
identifier_name
visualization.py
def stage_parameters(trace, stage_param_names, stage_map, label_plot=True): stage_map = {v:k for k,v in stage_map.items()} _, axs = model_parameters(trace, stage_param_names) for param in stage_param_names: if trace[param].dtype == np.float64: means = extract_mean_as_array(trace, para...
summary_df = pm.summary(trace, varnames=varnames) print(summary_df) axs = pm.traceplot(trace, varnames=varnames) return summary_df, axs
identifier_body
visualization.py
('__')[1].split('_')] else: return [0] df['var type'] = df['index'].apply(lambda x: x.split('__')[0]) df = df.loc[df['var type'] == var, :] var_idxs = df['index'].apply(split_fun) indexs = np.stack(var_idxs) if astype == 'array': sizes = indexs.max(axis=0) + 1 va...
x_data = np.linspace(data[x].min(), data[x].max(), samples_per_x_range) df = pd.DataFrame({x:x_data}) for var in mean_sample_vars: var_mean = data[var].mean(skipna=True) var_std = data[var].std(skipna=True) df[var] = var_mean data_points = data_points.loc[(var_mean-va...
else: if truncate_to_percentile: x_data = np.linspace(np.percentile(data[x],truncate_to_percentile), np.percentile(data[x],100-truncate_to_percentile), samples_per_x_range) else:
random_line_split
visualization.py
')[1].split('_')] else: return [0] df['var type'] = df['index'].apply(lambda x: x.split('__')[0]) df = df.loc[df['var type'] == var, :] var_idxs = df['index'].apply(split_fun) indexs = np.stack(var_idxs) if astype == 'array': sizes = indexs.max(axis=0) + 1 var_ar...
df['var type'] = df['index'].apply(lambda x: x.split('__')[0]) df = df.loc[df['var type'] == var, :] var_idxs = df['index'].apply(split_fun) indexs = np.stack(var_idxs) if astype == 'array': sizes = indexs.max(axis=0)+1 var_array = df['mean'].copy().values.reshape(sizes) re...
return [0]
conditional_block
train_ddpg_selfplay.py
os.path.join('runs', current_time + '_' + hp.ENV_NAME + '_' + hp.EXP_NAME) pi_atk = DDPGActor(hp.N_OBS, hp.N_ACTS).to(device) Q_atk = DDPGCritic(hp.N_OBS, hp.N_ACTS).to(device) pi_gk = DDPGActor(hp.N_OBS, hp.N_ACTS).to(device) Q_gk = DDPGCritic(hp.N_OBS, hp.N_ACTS).to(device...
metrics[key] = np.mean([info[key] for info in ep_infos])
conditional_block
train_ddpg_selfplay.py
import numpy as np import rc_gym import torch.multiprocessing as mp import torch.nn.functional as F import torch.optim as optim import wandb from agents.ddpg_selfplay import (DDPGHP, DDPGActor, DDPGCritic, TargetActor, TargetCritic, data_func) from agents.utils import ReplayBuffer, save_checkp...
import gym
random_line_split
spatialfr.py
length-cropped_length)/2) return matrix[i1:i2, i1:i2] def determine_radius(df): # Determine the radius of the primary beam. # Fit a Gaussian to the distribution of RA and Dec positions. # Use 2x the determined sigma as a cutoff for sources, in steps of 2.5 deg. ra_hist, ra_bins = np.histogram(df.r...
fig, ax = plt.subplots(1, 1, figsize=(15, 12)) img1 = ax.imshow(grid_sub, extent=beam_extent, cmap="plasma") ax.set_xlabel("RA [deg]") ax.set_ylabel("Dec [deg]") ax.set_title("Faraday depth residuals after plane surface fit") fig.colorbar(img1, ax=ax, format="%.2f", fraction=0.046, pad=0.04) plt...
identifier_body
spatialfr.py
file who's path is given. ''' yaml_file = '/home/chege/Desktop/curtin_work/vega/%s.yaml' % (obsid) ras = [] decs = [] fluxes = [] ampscales = [] stds = [] with open(yaml_file, 'r') as f: unpacked = yaml.load(f, Loader=SafeLoader) for sos in sources: for soc i...
(df): # Determine the radius of the primary beam. # Fit a Gaussian to the distribution of RA and Dec positions. # Use 2x the determined sigma as a cutoff for sources, in steps of 2.5 deg. ra_hist, ra_bins = np.histogram(df.ra, bins=50) dec_hist, dec_bins = np.histogram(df.dec, bins=50) ra_p0 = [...
determine_radius
identifier_name
spatialfr.py
yaml file who's path is given. ''' yaml_file = '/home/chege/Desktop/curtin_work/vega/%s.yaml' % (obsid) ras = [] decs = [] fluxes = [] ampscales = [] stds = [] with open(yaml_file, 'r') as f: unpacked = yaml.load(f, Loader=SafeLoader) for sos in sources: for ...
np.vstack((ra, dec)).T, fr, (grid_x, grid_y), method=interp_method, fill_value=0)) beam_extent = ( ra_centre+radius, ra_centre-radius, dec_centre-radius, ...
grid_fr = np.fliplr( griddata(
random_line_split
spatialfr.py
return fr_value, fr_value_err def get_radec(sources, obsid): ''' Gets the Ra and Dec of a source from the yaml file who's path is given. ''' yaml_file = '/home/chege/Desktop/curtin_work/vega/%s.yaml' % (obsid) ras = [] decs = [] fluxes = [] ampscales = [] stds = [] with op...
print('found the hr, reading its fr value') fr_value = row[3] fr_value_err = row[4]
conditional_block
functions.py
)/3) plt.rc('axes', labelsize=22) plt.grid(b=True, which='major', color='#666666', linestyle='-', alpha=0.2) trans1 = Affine2D().translate(-0.1, 0.0) + ax.transData trans2 = Affine2D().translate(+0.1, 0.0) + ax.transData er1 = ax.errorbar(y1, x, xerr=yerr1, marker="o", linestyle="none", transform=tr...
def get_bs_from_http(link): html = requests.get(link) return BeautifulSoup(html.text, "html.parser") def get_html_request(link): return requests.get(link) def merge_dicts(dic1, dic2): try: dic3 = dict(dic2) for k, v in dic1.items(): dic3[k] = Flatten([dic3[k], v]) if k in...
random_line_split
functions.py
)/3) plt.rc('axes', labelsize=22) plt.grid(b=True, which='major', color='#666666', linestyle='-', alpha=0.2) trans1 = Affine2D().translate(-0.1, 0.0) + ax.transData trans2 = Affine2D().translate(+0.1, 0.0) + ax.transData er1 = ax.errorbar(y1, x, xerr=yerr1, marker="o", linestyle="none", transform=tr...
_main_text(soup): text = soup.find(id="ad_description_text").text text = clean_string2(text) cut_string = "ihr wg gesucht team" try: return text.split(cut_string, 1)[1] except: return text def get_text(link): bs = get_bs_from_http(link) text = get_main_text(bs) return cl...
e.sub(r"[\W\_]|\d+", ' ', liste) liste = " ".join(liste.split()) liste = liste.lower() return liste def get
identifier_body
functions.py
)/3) plt.rc('axes', labelsize=22) plt.grid(b=True, which='major', color='#666666', linestyle='-', alpha=0.2) trans1 = Affine2D().translate(-0.1, 0.0) + ax.transData trans2 = Affine2D().translate(+0.1, 0.0) + ax.transData er1 = ax.errorbar(y1, x, xerr=yerr1, marker="o", linestyle="none", transform=tr...
ct(dict12) dict_list = [dict1, dict2, dict3, dict4, dict5, dict8, dict6, dict7, dict7, dict9, dict10, dict11, dict12] for item in dict_list: dict1.update(item) return dict1 def get_bs_from_html(html): return BeautifulSoup(html.text, "html.parser") def get_bs_from_http(link): html = requ...
g, 0]) dict12 = di
conditional_block
functions.py
)/3) plt.rc('axes', labelsize=22) plt.grid(b=True, which='major', color='#666666', linestyle='-', alpha=0.2) trans1 = Affine2D().translate(-0.1, 0.0) + ax.transData trans2 = Affine2D().translate(+0.1, 0.0) + ax.transData er1 = ax.errorbar(y1, x, xerr=yerr1, marker="o", linestyle="none", transform=tr...
text = soup.find(id="ad_description_text").text text = clean_string2(text) cut_string = "ihr wg gesucht team" try: return text.split(cut_string, 1)[1] except: return text def get_text(link): bs = get_bs_from_http(link) text = get_main_text(bs) return clean_string2(text) ...
text(soup):
identifier_name
agent_sample_stats.py
s))) any_ungrounded_ratio = 100 * (any_ungrounded / float(len(stmts))) return all_ungrounded_ratio, any_ungrounded_ratio def get_agent_counts(stmts): agents = gm.ungrounded_texts(stmts) agent_counts = [t[1] for t in agents] return agent_counts fname = '../step3_sample_t...
plt.ion() ax = fig.gca() for i, (bin_starts, fracs_total) in \ enumerate(zip(bin_starts_list, fracs_total_list)): xvals = np.array(bin_starts) / len(counts_list[i]) yvals = fracs_total / float(np.sum(counts_list[i])) ax.plot(xvals, yvals, color=colors[i]) ax.plot(xvals, x...
"""Plot the distribution of ungrounded strings in training vs test corpus. """ bin_interval = 1 fracs_total_list = [] bin_starts_list = [] for counts in counts_list: freq_dist = [] bin_starts = list(range(0, len(counts), bin_interval)) bin_starts_list.append(bin_starts) ...
identifier_body
agent_sample_stats.py
s))) any_ungrounded_ratio = 100 * (any_ungrounded / float(len(stmts))) return all_ungrounded_ratio, any_ungrounded_ratio def get_agent_counts(stmts): agents = gm.ungrounded_texts(stmts) agent_counts = [t[1] for t in agents] return agent_counts fname = '../step3_sample_t...
width = 0.3 bef_color = pf.ORANGE aft_color = pf.GREEN ax = plt.gca() error_kw = dict(ecolor='black', lw=1, capsize=2, capthick=1) befh = plt.bar(-0.5*width, prot_bef, width=width, yerr=prot_bef_err, color=bef_color, error_kw=error_kw) afth = plt.bar(0.5*width, prot_aft, w...
random_line_split
agent_sample_stats.py
all_ungrounded_ratio = 100 * (all_ungrounded / float(len(stmts))) any_ungrounded_ratio = 100 * (any_ungrounded / float(len(stmts))) return all_ungrounded_ratio, any_ungrounded_ratio def get_agent_counts(stmts): agents = gm.ungrounded_texts(stmts) agent_counts = [t[1] for t ...
agents_ungrounded = [] for ag in stmt.agent_list(): if ag is not None and list(ag.db_refs.keys()) == ['TEXT']: agents_ungrounded.append(True) else: agents_ungrounded.append(False) if all(agents_ungrounded): a...
conditional_block
agent_sample_stats.py
s))) any_ungrounded_ratio = 100 * (any_ungrounded / float(len(stmts))) return all_ungrounded_ratio, any_ungrounded_ratio def get_agent_counts(stmts): agents = gm.ungrounded_texts(stmts) agent_counts = [t[1] for t in agents] return agent_counts fname = '../step3_sample_t...
(results): prot_bef, prot_bef_err = results['training'][0][4:6] fam_bef, fam_bef_err = results['training'][1][4:6] prot_aft, prot_aft_err = results['test'][0][4:6] fam_aft, fam_aft_err = results['test'][1][4:6] plt.figure(figsize=(2.8, 2.2), dpi=300) width = 0.3 bef_color = pf.ORANGE aft...
combined_graph
identifier_name
nextbus_test.go
.77513" lon="-122.41946" secsSinceReport="4" predictable="true" heading="225" speedKmHr="0" leadingVehicleId="1112"/> <vehicle id="2222" routeTag="2" dirTag="2_inbound" lat="37.74891" lon="-122.45848" secsSinceReport="5" predictable="true" heading="217" speedKmHr="0" leadingVehicleId="2223"/> <lastTime time="1234567890...
}, VehicleLocation{ xmlName("vehicle"), "2222", "2", "2_inbound", "37.74891", "-122.45848", "5", "true", "217", "0", "2
{ nb := NewClient(testingClient(t)) found, err := nb.GetVehicleLocations("alpha") ok(t, err) expected := LocationResponse{ xmlName("body"), []VehicleLocation{ VehicleLocation{ xmlName("vehicle"), "1111", "1", "1_outbound", "37.77513", "-122.41946", "4", "true", "225", ...
identifier_body
nextbus_test.go
.77513" lon="-122.41946" secsSinceReport="4" predictable="true" heading="225" speedKmHr="0" leadingVehicleId="1112"/> <vehicle id="2222" routeTag="2" dirTag="2_inbound" lat="37.74891" lon="-122.45848" secsSinceReport="5" predictable="true" heading="217" speedKmHr="0" leadingVehicleId="2223"/> <lastTime time="1234567890...
(t *testing.T) { nb := NewClient(testingClient(t)) found, err := nb.GetAgencyList() ok(t, err) expected := []Agency{ Agency{xmlName("agency"), "alpha", "The First", "What a Transit Agency"}, Agency{xmlName("agency"), "beta", "The Second", "Never never land"}, } equals(t, expected, found) } func TestGetRoute...
TestGetAgencyList
identifier_name
nextbus_test.go
.77513" lon="-122.41946" secsSinceReport="4" predictable="true" heading="225" speedKmHr="0" leadingVehicleId="1112"/> <vehicle id="2222" routeTag="2" dirTag="2_inbound" lat="37.74891" lon="-122.45848" secsSinceReport="5" predictable="true" heading="217" speedKmHr="0" leadingVehicleId="2223"/> <lastTime time="1234567890...
"ffffff", "12.3456789", "45.6789012", "-123.4567890", "-456.78901", []Direction{ Direction{ xmlName("direction"), "1out", "Outbound to somewhere", "Outbound", "true", stopMarkers("1123", "1234"), }, Direction{ xmlName("direction"), "1in", "Inbound to somewhere", "I...
"1-first", "660000",
random_line_split
nextbus_test.go
77513" lon="-122.41946" secsSinceReport="4" predictable="true" heading="225" speedKmHr="0" leadingVehicleId="1112"/> <vehicle id="2222" routeTag="2" dirTag="2_inbound" lat="37.74891" lon="-122.45848" secsSinceReport="5" predictable="true" heading="217" speedKmHr="0" leadingVehicleId="2223"/> <lastTime time="12345678901...
url := req.URL.String() xml, ok := fakes[url] if !ok { valid := []string{} for k := range fakes { valid = append(valid, k) } f.t.Fatalf("Unexpected url %q. allowable urls are=%q", url, valid) return nil, nil } res := http.Response{} res.StatusCode = http.StatusOK res.Body = ioutil.NopCloser(stri...
{ req.Body.Close() req.Body = nil }
conditional_block
battle.py
'#': other = unit_at(x, y, units) if other is not None and other.race != self.race and not other.dead: targets.append(other) return targets def find_in_range_tiles(self, arena, units): # Find tiles in range to an enemy in_range_...
start = time.time() round_end = time.time() arena, units = read_arena() initial_arena = copy.deepcopy(arena) initial_units = copy.deepcopy(units) #Loop until no deaths deaths = 1 power = 2 while deaths > 0: #Update elf powers power += 1 arena = co...
identifier_body
battle.py
elf': return 'goblin' else: raise ValueError('Invalid race') def find_open_tiles(self, arena, units): """ Returns a list of all open tiles adjacent to the unit. """ tiles = [] for x, y in [(self.x+1, self.y), (self.x, self.y+1), (sel...
return 'no-reachable', {} # If multiple paths exist, pick the starting point using reading order optimal_paths = find_optimal_paths((self.x, self.y), target, paths) choices = sorted([op[0] for op in optimal_paths]) x, y = choices[0] # Update position ...
if target is None:
random_line_split
battle.py
'elf': return 'goblin' else: raise ValueError('Invalid race') def find_open_tiles(self, arena, units): """ Returns a list of all open tiles adjacent to the unit. """ tiles = [] for x, y in [(self.x+1, self.y), (self.x, self.y+1), (s...
optimal_paths = [] update_paths(source, target, (), graph, optimal_paths) return optimal_paths def find_next_step(start, end, paths): """ Given initial and final (x,y) coordinates and a dictionary of partial paths, return the next step towards reaching """ def find_paths(...
path = (current,) + path update_paths(source, (x, y), path, graph, optimal_paths)
conditional_block
battle.py
'elf': return 'goblin' else: raise ValueError('Invalid race') def find_open_tiles(self, arena, units): """ Returns a list of all open tiles adjacent to the unit. """ tiles = [] for x, y in [(self.x+1, self.y), (self.x, self.y+1), (s...
(start, current, distance, paths, choices): """ Given the start point, and the current point, builds a dictionary indicating the first step and the minimum distance to the end using that step. Distance indicates the distance from current to end. """ # Find all paths...
find_paths
identifier_name
lib.rs
(&mut self) { let p = self.data; if p != 0 as *mut _ { self.data = 0 as *mut _; let _ = unsafe { Vec::from_raw_parts(p as *mut u8, 0, self.byte_len()) }; } } } impl Bitmap { /// Create a new bitmap, returning None if the data can't be allocated or /// if the ...
drop
identifier_name
lib.rs
: usize, width: usize) -> Option<Bitmap> { if width > (std::mem::size_of::<usize>() * 8) || width == 0 { None } else { entries.checked_mul(width) .and_then(|bits| bits.checked_add(8 - (bits % 8))) .and_then(|rbits| rbits.checked_div(8)) .and_th...
else { let mut bit_offset = i * self.width; let mut in_byte_offset = bit_offset % 8; let mut byte_offset = (bit_offset - in_byte_offset) / 8; let mut bits_left = self.width; let mut value: usize = 0; while bits_left > 0 { // ho...
{ None }
conditional_block