file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
rastermanager.py
import os import sys import numpy as np import time import yaml import calendar from datetime import datetime, timedelta, date from s3fs.core import S3FileSystem import boto3 import fiona import pandas as pd import rasterio.mask from rasterio.crs import CRS from rasterio.enums import Resampling from rasterio import s...
else: print('PATH MODE in config is not set properly for the cloud implementation of output_Rasters') sys.exit(0) # ----------- create output rasters ----------------- def output_rasters(self, arr, outdir, outname): """ This function creates geotiff files from...
print('google path mode not yet implemented') sys.exit(0)
conditional_block
rastermanager.py
import os import sys import numpy as np import time import yaml import calendar from datetime import datetime, timedelta, date from s3fs.core import S3FileSystem import boto3 import fiona import pandas as pd import rasterio.mask from rasterio.crs import CRS from rasterio.enums import Resampling from rasterio import s...
self.log.info('tile name is - {}'.format(tile)) if 'tile' in tile: self.log.info("using scalable tile names {}".format(tile)) #bucket_name = self.config_dict['out_root'].split('/')[0] #today = date.today() #print("Current date =", today) ...
random_line_split
rastermanager.py
import os import sys import numpy as np import time import yaml import calendar from datetime import datetime, timedelta, date from s3fs.core import S3FileSystem import boto3 import fiona import pandas as pd import rasterio.mask from rasterio.crs import CRS from rasterio.enums import Resampling from rasterio import s...
(self, warpfile, rs): t0 = t_now() cnt=10 while(cnt>0): try: with rasterio.open(warpfile) as src: if src.crs == None: src.crs = CRS.from_epsg(4326) # create the virtual raster based on the standard raster...
_warp_one
identifier_name
rastermanager.py
import os import sys import numpy as np import time import yaml import calendar from datetime import datetime, timedelta, date from s3fs.core import S3FileSystem import boto3 import fiona import pandas as pd import rasterio.mask from rasterio.crs import CRS from rasterio.enums import Resampling from rasterio import s...
def s3_delete_local(self, local_file, bucket, bucket_filepath): """ This function will move the model outputs from a local folder to a cloud bucket. :param local_file: path the the local geo file :param outpath: path of a directory to be created in the cloud bucket :param...
""" Uses rasterio virtual raster to standardize grids of different crs, resolution, boundaries based on a shapefile geometry feature :param inputs: a list of (daily) raster input files for the water balance. :param outloc: output locations 'temp' for the virtual files :return: list of n...
identifier_body
tools.rs
//! Download management for external tools and applications. Locate and automatically download //! applications (if needed) to use them in the build pipeline. use std::path::{Path, PathBuf}; use anyhow::{anyhow, bail, ensure, Context, Result}; use async_compression::tokio::bufread::GzipDecoder; use directories_next::...
.nth(1) .with_context(|| format!("missing or malformed version output: {}", text))? .to_owned(), Application::WasmOpt => format!( "version_{}", text.split(' ') .nth(2) .with_context(|| for...
let text = text.trim(); let formatted_version = match self { Application::WasmBindgen => text .split(' ')
random_line_split
tools.rs
//! Download management for external tools and applications. Locate and automatically download //! applications (if needed) to use them in the build pipeline. use std::path::{Path, PathBuf}; use anyhow::{anyhow, bail, ensure, Context, Result}; use async_compression::tokio::bufread::GzipDecoder; use directories_next::...
(&self, version: &str) -> Result<String> { Ok(match self { Self::WasmBindgen => format!( "https://github.com/rustwasm/wasm-bindgen/releases/download/{version}/wasm-bindgen-{version}-x86_64-{target}.tar.gz", version = version, target = self.target()? ...
url
identifier_name
tools.rs
//! Download management for external tools and applications. Locate and automatically download //! applications (if needed) to use them in the build pipeline. use std::path::{Path, PathBuf}; use anyhow::{anyhow, bail, ensure, Context, Result}; use async_compression::tokio::bufread::GzipDecoder; use directories_next::...
/// Path of the executable within the downloaded archive. fn path(&self) -> &str { if cfg!(windows) { match self { Self::WasmBindgen => "wasm-bindgen.exe", Self::WasmOpt => "bin/wasm-opt.exe", } } else { match self { ...
{ match self { Self::WasmBindgen => "wasm-bindgen", Self::WasmOpt => "wasm-opt", } }
identifier_body
mod.rs
//! This module handles connections to Content Manager Server //! First you connect into the ip using a tcp socket //! Then reads/writes into it //! //! Packets are sent at the following format: packet_len + packet_magic + data //! packet length: u32 //! packet magic: VT01 //! //! Apparently, bytes received are in litt...
_ => { unimplemented!() } }; } Ok(()) } } #[cfg(not(feature = "websockets"))] #[async_trait] impl Connection<TcpStream> for SteamConnection<TcpStream> { /// Opens a tcp stream to specified IP async fn new_connection(ip_addr: ...
{ handle_encryption_negotiation(sender.clone(), connection_state, packet_message).unwrap(); }
conditional_block
mod.rs
//! This module handles connections to Content Manager Server //! First you connect into the ip using a tcp socket //! Then reads/writes into it //! //! Packets are sent at the following format: packet_len + packet_magic + data //! packet length: u32 //! packet magic: VT01 //! //! Apparently, bytes received are in litt...
(mut self) -> Result<(), ConnectionError> { let (sender, mut receiver): (UnboundedSender<DynBytes>, UnboundedReceiver<DynBytes>) = mpsc::unbounded_channel(); let connection_state = &mut self.state; let (stream_rx, stream_tx) = self.stream.into_split(); let mut framed_read =...
main_loop
identifier_name
mod.rs
//! This module handles connections to Content Manager Server //! First you connect into the ip using a tcp socket //! Then reads/writes into it //! //! Packets are sent at the following format: packet_len + packet_magic + data //! packet length: u32 //! packet magic: VT01 //! //! Apparently, bytes received are in litt...
#[inline] async fn write_packets(&mut self, data: &[u8]) -> Result<(), Box<dyn Error>> { let mut output_buffer = BytesMut::with_capacity(1024); trace!("payload size: {} ", data.len()); output_buffer.extend_from_slice(&(data.len() as u32).to_le_bytes()); output_buffer.extend_fro...
}
random_line_split
mod.rs
//! This module handles connections to Content Manager Server //! First you connect into the ip using a tcp socket //! Then reads/writes into it //! //! Packets are sent at the following format: packet_len + packet_magic + data //! packet length: u32 //! packet magic: VT01 //! //! Apparently, bytes received are in litt...
} #[cfg(not(feature = "websockets"))] #[async_trait] impl Connection<TcpStream> for SteamConnection<TcpStream> { /// Opens a tcp stream to specified IP async fn new_connection(ip_addr: &str) -> Result<SteamConnection<TcpStream>, Box<dyn Error>> { trace!("Connecting to ip: {}", &ip_addr); let ...
{ let (sender, mut receiver): (UnboundedSender<DynBytes>, UnboundedReceiver<DynBytes>) = mpsc::unbounded_channel(); let connection_state = &mut self.state; let (stream_rx, stream_tx) = self.stream.into_split(); let mut framed_read = FramedRead::new(stream_rx, PacketMessageC...
identifier_body
zipfian_generator.go
package generator import ( "math" ) const ( ZipfianConstant = float64(0.99) ) // Compute the zeta constant needed for the distribution. // Do this incrementally for a distribution that has n items now // but used to have st items. Use the zipfian constant theta. // Remember the new value of n so that if we change ...
zipfianConstant float64 // Computed parameters for generating the distribution. alpha, zetan, eta, theta, zeta2theta float64 // The number of items used to compute zetan the last time. countForzata int64 // Flag to prevent problems. If you increase the number of items which // the zipfian generator is allowed t...
base int64 // The zipfian constant to use.
random_line_split
zipfian_generator.go
package generator import ( "math" ) const ( ZipfianConstant = float64(0.99) ) // Compute the zeta constant needed for the distribution. // Do this incrementally for a distribution that has n items now // but used to have st items. Use the zipfian constant theta. // Remember the new value of n so that if we change ...
u := NextFloat64() uz := u * self.zetan if uz < 1.0 { ret = self.base return ret } if uz < 1.0+math.Pow(0.5, self.theta) { ret = self.base + 1 return ret } ret = self.base + int64(float64(itemCount)*math.Pow(self.eta*u-self.eta+1.0, self.alpha)) return ret } func (self *ZipfianGenerator) NextString()...
{ if itemCount > self.countForzata { self.countForzata, self.zetan = zeta(self.countForzata, itemCount, self.theta, self.zetan) self.eta = (1 - math.Pow(float64(2.0/self.items), 1-self.theta)) / (1 - self.zeta2theta/self.zetan) } else if (itemCount < self.countForzata) && (self.allowItemCountDecrease) { se...
conditional_block
zipfian_generator.go
package generator import ( "math" ) const ( ZipfianConstant = float64(0.99) ) // Compute the zeta constant needed for the distribution. // Do this incrementally for a distribution that has n items now // but used to have st items. Use the zipfian constant theta. // Remember the new value of n so that if we change ...
// Compute the zeta constant needed for the distribution. Do this incrementally // for a distribution that has h items now but used to have st items. // Use the zipfian constant theta. Remember the new value of n so that // if we change itemCount, we'll know to recompute zeta. func zetaStatic(st, n int64, theta, init...
{ countForzata := n return countForzata, zetaStatic(st, n, theta, initialSum) }
identifier_body
zipfian_generator.go
package generator import ( "math" ) const ( ZipfianConstant = float64(0.99) ) // Compute the zeta constant needed for the distribution. // Do this incrementally for a distribution that has n items now // but used to have st items. Use the zipfian constant theta. // Remember the new value of n so that if we change ...
(items int64) *ScrambledZipfianGenerator { return NewScrambledZipfianGenerator(0, items-1) } // Create a zipfian generator for items between min and max (inclusive) for // the specified zipfian constant. If you use a zipfian constant other than // 0.99, this will take a long time complete because we need to recompute...
NewScrambledZipfianGeneratorByItems
identifier_name
mapnificent.js
/* Mapnificent - transit shed (travel time) visualisations Copyright (C) 2015 Stefan Wehrmeyer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opti...
function MapnificentPosition(mapnificent, latlng, time) { this.mapnificent = mapnificent; this.latlng = latlng; this.stationMap = null; this.progress = 0; this.time = time === undefined ? 15 * 60 : time; this.init(); } MapnificentPosition.prototype.init = function(){ var self = ...
{ progressBar.find('.progress-bar').attr({ 'aria-valuenow': percent, style: 'width: ' + percent + '%' }); progressBar.find('.sr-only').text(percent + '% Complete'); }
identifier_body
mapnificent.js
/* Mapnificent - transit shed (travel time) visualisations Copyright (C) 2015 Stefan Wehrmeyer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opti...
(mapnificent, latlng, time) { this.mapnificent = mapnificent; this.latlng = latlng; this.stationMap = null; this.progress = 0; this.time = time === undefined ? 15 * 60 : time; this.init(); } MapnificentPosition.prototype.init = function(){ var self = this; // this.marker = new ...
MapnificentPosition
identifier_name
mapnificent.js
/* Mapnificent - transit shed (travel time) visualisations Copyright (C) 2015 Stefan Wehrmeyer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opti...
if (x + radius < 0 || x - radius > tileSize || y + radius < 0 || y - radius > tileSize) { return null; } return {x: x, y: y, r: radius}; }; var stations = []; if (this.stationMap === null) { return stations; } // You start walking from your position...
var radius = Math.max(Math.round(lpoint.x - point2.x), 1); var p = self.mapnificent.map.project(point); var x = Math.round(p.x - start.x); var y = Math.round(p.y - start.y);
random_line_split
mapnificent.js
/* Mapnificent - transit shed (travel time) visualisations Copyright (C) 2015 Stefan Wehrmeyer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opti...
}); }; Mapnificent.prototype.logDebugMessage = function(latlng) { var self = this; var stationsAround = this.quadtree.searchInRadius(latlng.lat, latlng.lng, 300); this.positions.forEach(function(pos, i){ console.log('Position ', i); if (pos.debugMap === undefined) { console.l...
{ // self.hash.update(); if (self.positions.length === 0) { self.addPosition(L.latLng( self.settings.coordinates[1], self.settings.coordinates[0] )); } }
conditional_block
formula.py
""" Provides the basic classes needed to specify statistical models. """ import copy import types import numpy as N __docformat__ = 'restructuredtext' default_namespace = {} class term(object): """ This class is very simple: it is just a named term in a model formula. It is also callable: by default it ...
(self, other): """ formula(self) + formula(other) When adding \'intercept\' to a factor, this just returns formula(self, namespace=self.namespace) """ if other.name is 'intercept': return formula(self, namespace=self.namespace) else: ...
__add__
identifier_name
formula.py
""" Provides the basic classes needed to specify statistical models. """ import copy import types import numpy as N __docformat__ = 'restructuredtext' default_namespace = {} class term(object): """ This class is very simple: it is just a named term in a model formula. It is also callable: by default it ...
return N.array(out) sumterms = self + other sumterms.terms = [self, other] # enforce the order we want sumterms.namespace = self.namespace _term = quantitative(names, func=sumterms, termname=termname, ...
out = [] for r in range(d1): for s in range(d2): out.append(value[r] * value[d1+s])
random_line_split
formula.py
""" Provides the basic classes needed to specify statistical models. """ import copy import types import numpy as N __docformat__ = 'restructuredtext' default_namespace = {} class term(object): """ This class is very simple: it is just a named term in a model formula. It is also callable: by default it ...
def termcolumns(self, query_term, dict=False): """ Return a list of the indices of all columns associated to a given term. """ if self.hasterm(query_term): names = query_term.names() value = {} for name in names: value[na...
t = self.termnames() if name in t: return self.terms[t.index(name)] else: raise KeyError, 'formula has no such term: %s' % repr(name)
identifier_body
formula.py
""" Provides the basic classes needed to specify statistical models. """ import copy import types import numpy as N __docformat__ = 'restructuredtext' default_namespace = {} class term(object): """ This class is very simple: it is just a named term in a model formula. It is also callable: by default it ...
val = N.asarray(val) return N.squeeze(val) class factor(term): """ A categorical factor. """ def __init__(self, termname, keys, ordinal=False): """ factor is initialized with keys, representing all valid levels of the factor. """ se...
if hasattr(val, "namespace"): val.namespace = self.namespace val = val(*args, **kw)
conditional_block
backup_slack.py
#!/usr/bin/env python # Slack scraper for logging messages and attachments in slack # clarence.wret@gmail.com, cwret@fnal.gov # Slacker import from slacker import Slacker import os import operator import datetime import time import re # Neede for exit import sys # Needed to pull files from Slack import urllib2 from s...
post=subject+"/private" slack.chat.post_message( channel=log_channel_id_priv, as_user=False, username=user, icon_url=icon, attachments=[{"pretext": post, "fallback": post, "color": "#36a64f", "footer": user, "text": body}]) return # G...
output = "Wrote "+`n`+" private messages for #"+priv_channels[chan_id] body += output+"\n" print output
conditional_block
backup_slack.py
#!/usr/bin/env python # Slack scraper for logging messages and attachments in slack # clarence.wret@gmail.com, cwret@fnal.gov # Slacker import from slacker import Slacker import os import operator import datetime import time import re # Neede for exit import sys # Needed to pull files from Slack import urllib2 from s...
# Get a dict of private channels for a given slack def GetChannelsPrivate(): Priv_Channels = dict() l = slack.groups.list().body["groups"] for c in l: Priv_Channels[c["id"]] = c["name"] return Priv_Channels def GetFiles(): Files = dict() l = slack.files.list() # Get a full list of messages from Slac...
Channels = dict() l = slack.channels.list().body["channels"] for c in l: Channels[c["id"]] = c["name"] return Channels
identifier_body
backup_slack.py
#!/usr/bin/env python # Slack scraper for logging messages and attachments in slack # clarence.wret@gmail.com, cwret@fnal.gov # Slacker import from slacker import Slacker import os import operator import datetime import time import re # Neede for exit import sys # Needed to pull files from Slack import urllib2 from s...
self.subtype = None self.link = [] self.linkname = [] # Get some file shares and hosted if self.subtype != None: # May be many attachments in one message for tempfile in message["files"]: # Only care about hosted files if tempfile["mode"] == "hosted": self.l...
except KeyError:
random_line_split
backup_slack.py
#!/usr/bin/env python # Slack scraper for logging messages and attachments in slack # clarence.wret@gmail.com, cwret@fnal.gov # Slacker import from slacker import Slacker import os import operator import datetime import time import re # Neede for exit import sys # Needed to pull files from Slack import urllib2 from s...
(): Users = dict() l = slack.users.list().body["members"] for u in l: Users[u["id"]] = u["name"] return Users # Get a dict of channels for a given slack def GetChannels(): Channels = dict() l = slack.channels.list().body["channels"] for c in l: Channels[c["id"]] = c["name"] return Channels # G...
GetUsers
identifier_name
api.py
#!/usr/bin/env python2.7 # coding=utf8 import ast import os import sqlite3 as lite from config import (client_id, client_secret, redirect_uri, twitch_client_id, twitch_client_secret, twitch_redirect_uri, twitch_scopes) import MySQLdb as mdb import requests from flask import Flask, json, redirect, ...
@app.route("/api/pokemon/<string:username>") def api_pokemon_username(username): api = API() party = api.pokemon_username(username) return party """ { "party": [ { "caughtBy": "singlerider", "level": 5, "nickname": "Scyther", "pokemonId": 123,...
api = API() items = api.items_username(username) return items """ { "itemCount": 1, "items": [ { "itemId": 2, "itemName": "Water Stone", "itemQuantity": 1 } ] } """
identifier_body
api.py
#!/usr/bin/env python2.7 # coding=utf8 import ast import os import sqlite3 as lite from config import (client_id, client_secret, redirect_uri, twitch_client_id, twitch_client_secret, twitch_redirect_uri, twitch_scopes) import MySQLdb as mdb import requests from flask import Flask, json, redirect, ...
@app.route("/api/items/<string:username>") def api_items_username(username): api = API() items = api.items_username(username) return items """ { "itemCount": 1, "items": [ { "itemId": 2, "itemName": "Water Stone", "itemQuantity": 1 } ]...
random_line_split
api.py
#!/usr/bin/env python2.7 # coding=utf8 import ast import os import sqlite3 as lite from config import (client_id, client_secret, redirect_uri, twitch_client_id, twitch_client_secret, twitch_redirect_uri, twitch_scopes) import MySQLdb as mdb import requests from flask import Flask, json, redirect, ...
os.environ["DEBUG"] = "1" app.secret_key = os.urandom(24) app.run(threaded=True, host="0.0.0.0", port=8080)
conditional_block
api.py
#!/usr/bin/env python2.7 # coding=utf8 import ast import os import sqlite3 as lite from config import (client_id, client_secret, redirect_uri, twitch_client_id, twitch_client_secret, twitch_redirect_uri, twitch_scopes) import MySQLdb as mdb import requests from flask import Flask, json, redirect, ...
(channel): api = API() commands = api.channel_commands(channel) return commands """ { "commandCount": 2, "commands": [ { "command": "!testcommand1", "creator": "exampleusername1", "response": "Example string response for command", "time": "...
api_channel_commands
identifier_name
main.py
#!/usr/bin/env python """Process the 3d model data and create required files for NMS. This function will take all the data provided by the blender script and create a number of .exml files that contain all the data required by the game to view the 3d model created. """ __author__ = "monkeyman192" __credits__ = ["monk...
(self): # this combines all the input streams into one single stream with the correct offset etc as specified by the VertexLayout # This also flattens each stream # Again, for now just make the SmallVertexStream the same. Later, change this. VertexStream = array('f') Sma...
mix_streams
identifier_name
main.py
#!/usr/bin/env python """Process the 3d model data and create required files for NMS. This function will take all the data provided by the blender script and create a number of .exml files that contain all the data required by the game to view the 3d model created. """ __author__ = "monkeyman192" __credits__ = ["monk...
x_bounds = (min(x_verts), max(x_verts)) y_bounds = (min(y_verts), max(y_verts)) z_bounds = (min(z_verts), max(z_verts)) self.GeometryData['MeshAABBMin'].append(Vector4f(x=x_bounds[0], y=y_bounds[0], z=z_bounds[0], t=1)) self.GeometryData['MeshAABBMax'].append...
z_verts = [i[2] for i in v_stream]
random_line_split
main.py
#!/usr/bin/env python """Process the 3d model data and create required files for NMS. This function will take all the data provided by the blender script and create a number of .exml files that contain all the data required by the game to view the 3d model created. """ __author__ = "monkeyman192" __credits__ = ["monk...
print(self.index_mapping, 'index_mapping') # populate the lists containing the lengths of each individual stream for index in range(self.num_mesh_objs): self.i_stream_lens.append(len(self.index_stream[index])) self.v_stream_lens.append(len(self.vertex_stream[index])) ...
self.index_mapping = movetofront(self.index_mapping, i) # move the index it is now located at so we can construct it correctly in the scene
conditional_block
main.py
#!/usr/bin/env python """Process the 3d model data and create required files for NMS. This function will take all the data provided by the blender script and create a number of .exml files that contain all the data required by the game to view the 3d model created. """ __author__ = "monkeyman192" __credits__ = ["monk...
# simple function to take a list and move the entry at the ith index to the first place def movetofront(lst, i): k = lst.pop(i) # this will break if i > len(lst)... return [k] + lst class Create_Data(): def __init__(self, name, directory, model, anim_data = dict(), descriptor = None, **commands)...
for child in obj.Children: for subvalue in traverse(child): yield subvalue else: yield obj
identifier_body
lib.rs
// The MIT License (MIT) // Copyright (c) 2018 Matrix.Zhang <113445886@qq.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the...
z_id: String, } #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct DayuQueryDetail { pub phone_num: String, pub send_date: String, pub send_status: u8, pub receive_date: String, pub template_code: String, pub content: String, pub err_code: String, } ...
se { pub bi
identifier_name
lib.rs
// The MIT License (MIT) // Copyright (c) 2018 Matrix.Zhang <113445886@qq.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the...
#[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct DayuFailResponse { pub code: String, pub message: String, pub request_id: String, } impl Display for DayuFailResponse { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", serde_json:...
random_line_split
lib.rs
// The MIT License (MIT) // Copyright (c) 2018 Matrix.Zhang <113445886@qq.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the...
page_size > MAX_PAGE_SIZE { return Err(DayuError::PageTooLarge(page_size)); } let send_date = send_date.format("%Y%m%d").to_string(); let page_size = page_size.to_string(); let current_page = current_page.to_string(); do_request!( self, ...
identifier_body
lib.rs
// The MIT License (MIT) // Copyright (c) 2018 Matrix.Zhang <113445886@qq.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the...
u.sign_name.is_empty() { return Err(DayuError::ConfigAbsence("sign_name")); } let timestamp = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); TextNonce::sized(32) .map_err(DayuError::TextNonce) .map(|v| v.to_string()) .and_then(|text_nonce| { let ...
urn Err(DayuError::ConfigAbsence("access_secret")); } if day
conditional_block
main.go
/** * Ask user for search keywords * Ask for duration * Ask user for tweet include a template to insert usernames * Ask user if they want to include multiple users in single tweet * TODO: * 1. [x] Tweet length * 2. [ ] Tweet velocity * [x] There is a limit on GET requests * So we can run a subroutine will...
() { userList.Init() xReplyStatuses.Init() // Inital Logging InitLogging(true, true, true, true, false) // Trace.Println("Tracing 123") // Info.Println("Info 123") // Warning.Println("Warning 123") // Error.Println("Error 123") // Debug.Println("Debug 123") // os.Exit(0) var endCriteriaValue int = 0 var tw...
main
identifier_name
main.go
/** * Ask user for search keywords * Ask for duration * Ask user for tweet include a template to insert usernames * Ask user if they want to include multiple users in single tweet * TODO: * 1. [x] Tweet length * 2. [ ] Tweet velocity * [x] There is a limit on GET requests * So we can run a subroutine will...
if direction == "o" { form = url.Values{"q": {keywordSearch}, "count": {"2"}, "result_type": {"recent"}, "max_id": {strconv.FormatInt(minId-1, 10)}} //Debug.Println("OLD: MinId = ", minId) } if direction == "n" { form = url.Values{"q": {keywordSearch}, "count": {"2"}, "result_type": {"recent"}, "since_i...
{ form = url.Values{"q": {keywordSearch}, "count": {"2"}, "result_type": {"recent"}} //Debug.Println("No min No max") }
conditional_block
main.go
/** * Ask user for search keywords * Ask for duration * Ask user for tweet include a template to insert usernames * Ask user if they want to include multiple users in single tweet * TODO: * 1. [x] Tweet length * 2. [ ] Tweet velocity * [x] There is a limit on GET requests * So we can run a subroutine will...
"strconv" "strings" "time" ) var oauthClient = oauth.Client{ TemporaryCredentialRequestURI: "https://api.twitter.com/oauth/request_token", ResourceOwnerAuthorizationURI: "https://api.twitter.com/oauth/authorize", TokenRequestURI: "https://api.twitter.com/oauth/access_token", } var credPath = flag....
"os"
random_line_split
main.go
/** * Ask user for search keywords * Ask for duration * Ask user for tweet include a template to insert usernames * Ask user if they want to include multiple users in single tweet * TODO: * 1. [x] Tweet length * 2. [ ] Tweet velocity * [x] There is a limit on GET requests * So we can run a subroutine will...
var userList XUserList var xReplyStatuses XReplyStatuses var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func randSeq(n int) string { b := make([]rune, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return string(b) } func main() { userList.Init() xReplyStatuses...
{ b, err := ioutil.ReadFile(*credPath) if err != nil { return err } return json.Unmarshal(b, &oauthClient.Credentials) }
identifier_body
openapi.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
func (o *openAPI) buildRequestBody(parameters []common.Parameter, consumes []string, bodySample interface{}) (*spec3.RequestBody, error) { for _, param := range parameters { if param.Kind() == common.BodyParameterKind && bodySample != nil { schema, err := o.toSchema(util.GetCanonicalTypeName(bodySample)) if ...
{ ret := &spec3.Operation{ OperationProps: spec3.OperationProps{ Description: route.Description(), Responses: &spec3.Responses{ ResponsesProps: spec3.ResponsesProps{ StatusCodeResponses: make(map[int]*spec3.Response), }, }, }, } for k, v := range route.Metadata() { if strings.HasPrefix(k,...
identifier_body
openapi.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
(config *common.Config, names ...string) (map[string]*spec.Schema, error) { o := newOpenAPI(config) // We can discard the return value of toSchema because all we care about is the side effect of calling it. // All the models created for this resource get added to o.swagger.Definitions for _, name := range names { ...
BuildOpenAPIDefinitionsForResources
identifier_name
openapi.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
pathItem.Head = op case "PUT": pathItem.Put = op case "DELETE": pathItem.Delete = op case "OPTIONS": pathItem.Options = op case "PATCH": pathItem.Patch = op } } o.spec.Paths.Paths[path] = pathItem } } return nil } // BuildOpenAPISpec builds OpenAPI v3 spec given ...
pathItem.Get = op case "POST": pathItem.Post = op case "HEAD":
random_line_split
openapi.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
if o.config.GetOperationIDAndTagsFromRoute == nil { // Map the deprecated handler to the common interface, if provided. if o.config.GetOperationIDAndTags != nil { o.config.GetOperationIDAndTagsFromRoute = func(r common.Route) (string, []string, error) { restfulRouteAdapter, ok := r.(*restfuladapter.RouteA...
{ o.spec.Components.SecuritySchemes[k] = securityScheme }
conditional_block
repository_analytics.py
# Copyright (c) 2015 Faculty of Engineering of the University of Porto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use,...
def strip_path(path): """ Extracts only the file name of a path """ name_re = re.compile("[^/]*\.([a-z]+)$") return name_re.search(path).group(0) class RepositoryAnalytics(Metrics): """ Represents the Analytics of a Repository. It stores the files analytics using a dict. Attributes: ...
""" A class for representing a set of Metrics. In analysis, each component have their analytics represented by a Metric instance. Attributes: fixes_dataset: A set of (revisions_twr, fixes_twr, authors_twr) that had a bug. FIXES_WEIGHT: A Decimal having the fixes weight for the defect probabili...
identifier_body
repository_analytics.py
# Copyright (c) 2015 Faculty of Engineering of the University of Porto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use,...
(self): super().__init__() self.classes_analytics = {} def compute_defect_probability(self): self.defect_prob = self.defect_probability() for class_analytics in self.classes_analytics.values(): class_analytics.compute_defect_probability() def to_dict(self, path): ...
__init__
identifier_name
repository_analytics.py
# Copyright (c) 2015 Faculty of Engineering of the University of Porto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use,...
since results were accumulating errors. """ import re from decimal import Decimal class Metrics: """ A class for representing a set of Metrics. In analysis, each component have their analytics represented by a Metric instance. Attributes: fixes_dataset: A set of (revisions_twr, fixes_twr, autho...
""" Module for declaring classes for the analytics/metrics. This module is the most important to understand the Schwa API. Here the analytics structure is declared and the defect probability is computed. Science is being done here! We use Decimal from the standard library
random_line_split
repository_analytics.py
# Copyright (c) 2015 Faculty of Engineering of the University of Porto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use,...
# Updates revisions self.revisions += 1 self.revisions_timestamps.append(ts) self.revisions_twr += Metrics.twr(begin_ts, ts, current_ts) # Updates authors if author not in self.authors: self.authors.add(author) self.authors_timestamps.append(ts) ...
self.add_to_dataset(begin_ts) self.fixes += 1 self.fixes_timestamps.append(ts) self.fixes_twr += Metrics.twr(begin_ts, ts, current_ts)
conditional_block
main.rs
#![allow(dead_code)] #![allow(unused_variables)] use std::collections::{HashMap, HashSet}; use std::io::stdin; use std::mem; mod pm; // const MEANING_OF_LIFE: u16 = 456; // no fixed address fn main() { // primitive_types (); // operators(); // scope_and_shadowing(); // println!("const MEANING_OF_L...
() { let a = 123; println!("a = {}", a); let a = 777; println!("a = {}", a); { let a = 888; let b = 456; println!("a = {}, b = {}", a, b); } } fn operators() { //arithmetic operators let mut a = 2 + 3 * 4; println!("{}", a); a += 1; a -= 2; pr...
scope_and_shadowing
identifier_name
main.rs
#![allow(dead_code)] #![allow(unused_variables)] use std::collections::{HashMap, HashSet}; use std::io::stdin; use std::mem; mod pm; // const MEANING_OF_LIFE: u16 = 456; // no fixed address fn main() { // primitive_types (); // operators(); // scope_and_shadowing(); // println!("const MEANING_OF_L...
fn structures() { struct Point { x: f64, y: f64, } let p = Point { x: 34.5, y: 4.0 }; println!("point p is at ({}, {})", p.x, p.y); let p2 = Point { x: 3.0, y: 4.0 }; struct Line { start: Point, end: Point, } let myline = Line { start: p, end: p2 }; } ...
{ enum Color { Red, Green, Blue, RgbColor(u8, u8, u8), //tuple Cmyk { cyan: u8, magenta: u8, yellow: u8, black: u8 }, //struct } let c: Color = Color::Cmyk { cyan: 0, magenta: 128, yellow: 0, black: 0 }; match c { Color::Red => println!("r"), ...
identifier_body
main.rs
#![allow(dead_code)] #![allow(unused_variables)] use std::collections::{HashMap, HashSet}; use std::io::stdin; use std::mem; mod pm; // const MEANING_OF_LIFE: u16 = 456; // no fixed address fn main() { // primitive_types (); // operators(); // scope_and_shadowing(); // println!("const MEANING_OF_L...
for (key, value) in &shapes { println!("key: {}, value: {}", key, value); } shapes.entry("circle".into()).or_insert(1); { let actual = shapes.entry("circle".into()).or_insert(2); *actual = 0; } println!("{:?}", shapes); let _1_5: HashSet<_> = (1..=5).collect(); ...
println!("a square has {} sides", shapes["square"]); shapes.insert("square".into(), 5); println!("{:?}", shapes);
random_line_split
main.rs
#![allow(dead_code)] #![allow(unused_variables)] use std::collections::{HashMap, HashSet}; use std::io::stdin; use std::mem; mod pm; // const MEANING_OF_LIFE: u16 = 456; // no fixed address fn main() { // primitive_types (); // operators(); // scope_and_shadowing(); // println!("const MEANING_OF_L...
} } } fn unions() { let mut iof = IntOrFloat { i: 123 }; iof.i = 234; let value = unsafe { iof.i }; println!("iof.i = {}", value); process_value(IntOrFloat { i: 5 }) } fn enums() { enum Color { Red, Green, Blue, RgbColor(u8, u8, u8), //tup...
{ println!("value = {}", f) }
conditional_block
main.rs
use std::{env, io, fmt}; use std::time::{Duration, SystemTime}; use std::error::Error; use std::collections::HashMap; use tokio::sync; use tokio::net::UdpSocket; use log::{debug, info, warn}; use futures::select; use futures::future::FutureExt; // Delta between NTP epoch (1900-01-01 00:00:00) and Unix epoch (1970-01-...
#[cfg(test)] mod tests { use crate::timetag_to_unix; #[test] fn time_tag_to_unix_1() { // 2^32 / 2 fractional seconds, i.e. 500,000μs assert_eq!(timetag_to_unix(3_608_146_800, 2_147_483_648), (1_399_158_000, 500_000)); } #[test] fn time_tag_to_unix_2() { assert_eq!(tim...
let addr = env::args().nth(1).unwrap_or_else(|| "127.0.0.1:4560".to_string()); Server::new(&addr).await?.run().await }
random_line_split
main.rs
use std::{env, io, fmt}; use std::time::{Duration, SystemTime}; use std::error::Error; use std::collections::HashMap; use tokio::sync; use tokio::net::UdpSocket; use log::{debug, info, warn}; use futures::select; use futures::future::FutureExt; // Delta between NTP epoch (1900-01-01 00:00:00) and Unix epoch (1970-01-...
(&mut self) -> Result<&[u8], io::Error> { let (size, _) = self.socket.recv_from(&mut self.buf).await?; Ok(&self.buf[..size]) } /// Handles /flush messages. fn handle_msg_flush(&mut self, msg: &rosc::OscMessage) { match msg.args.first() { Some(rosc::OscType::String(tag)) ...
recv_udp_packet
identifier_name
main.rs
use std::{env, io, fmt}; use std::time::{Duration, SystemTime}; use std::error::Error; use std::collections::HashMap; use tokio::sync; use tokio::net::UdpSocket; use log::{debug, info, warn}; use futures::select; use futures::future::FutureExt; // Delta between NTP epoch (1900-01-01 00:00:00) and Unix epoch (1970-01-...
} impl Error for ServerError {} impl From<io::Error> for ServerError { fn from(err: io::Error) -> Self { Self::Io(err) } } impl From<rosc::OscError> for ServerError { fn from(err: rosc::OscError) -> Self { Self::Osc(err) } } #[tokio::main] async fn main() -> Result<(), io::Error> {...
{ match self { Self::Io(err) => write!(f, "IO error: {}", err), Self::Osc(err) => write!(f, "Failed to decode OSC packet: {:?}", err), Self::Protocol(err) => write!(f, "{}", err), } }
identifier_body
001-rnn+lstm+crf.py
""" @file : 001-rnn+lstm+crf.py @author: xiaolu @time : 2019-09-06 """ import re import numpy as np import tensorflow as tf from sklearn.metrics import classification_report class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_l...
ar_seq(batch): ''' 传进来是50一个块 总共有多少块 然后将每块的单词转为字符序列 :param batch: :return: ''' x = [[len(idx2word[i]) for i in k] for k in batch] # 得出每个单词的长度 maxlen = max([j for i in x for j in i]) # 最大长度 temp = np.zeros((batch.shape[0], batch.shape[1], maxlen), dtype=np.int32) for i in range(...
eturn [iter_seq(x) for x in args] def generate_ch
conditional_block
001-rnn+lstm+crf.py
""" @file : 001-rnn+lstm+crf.py @author: xiaolu @time : 2019-09-06 """ import re import numpy as np import tensorflow as tf from sklearn.metrics import classification_report class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_l...
if text not in word2idx: # 词表 word2idx[text] = word_idx word_idx += 1 X.append(word2idx[text]) # 将词转为id的标号 return X, np.array(Y) def iter_seq(x): return np.array([x[i: i+seq_len] for i in range(0, len(x)-seq_len, 1)]) def to_train_seq(*args): ''' :param arg...
random_line_split
001-rnn+lstm+crf.py
""" @file : 001-rnn+lstm+crf.py @author: xiaolu @time : 2019-09-06 """ import re import numpy as np import tensorflow as tf from sklearn.metrics import classification_report class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_l...
open: texts = fopen.read().split('\n') left, right = [], [] for text in texts: if '-DOCSTART' in text or not len(text): continue splitted = text.split() left.append(splitted[0]) right.append(splitted[-1]) return left, right def process_string(string): ...
as f
identifier_name
001-rnn+lstm+crf.py
""" @file : 001-rnn+lstm+crf.py @author: xiaolu @time : 2019-09-06 """ import re import numpy as np import tensorflow as tf from sklearn.metrics import classification_report class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_l...
# print(train_Y[:20]) idx2word = {idx: tag for tag, idx in word2idx.items()} idx2tag = {i: w for w, i in tag2idx.items()} seq_len = 50 X_seq, Y_seq = to_train_seq(train_X, train_Y) # 长度为50为一个段落 X_char_seq = generate_char_seq(X_seq) print(X_seq.shape) # (203571, 50) print(X_char_seq.s...
char_idx = 1 train_X, train_Y = parse_XY(left_train, right_train) test_X, test_Y = parse_XY(left_test, right_test) # print(train_X[:20])
identifier_body
lz4.rs
/*! LZ4 Decompression and Compression. Requires `lz4` feature, enabled by default This module contains an implementation in Rust of decompression and compression of LZ4-encoded streams. These are exposed as a standard `Reader` and `Writer` interfaces wrapping an underlying stream. # Example ```rust,ignore use compr...
// FIXME: find out why slicing syntax fails tests //self.output[self.dest_pos as usize .. (self.dest_pos + len) as usize] = self.input[pos as uint.. (pos + len) as uint]; for i in 0..(len as usize) { self.output[self.dest_pos as usize + i] = self.input[pos as usize + i]; } ...
ln -= RUN_MASK; while ln > 254 { self.output[self.dest_pos as usize] = 255; self.dest_pos += 1; ln -= 255; } self.output[self.dest_pos as usize] = ln as u8; self.dest_pos += 1; }
conditional_block
lz4.rs
/*! LZ4 Decompression and Compression. Requires `lz4` feature, enabled by default This module contains an implementation in Rust of decompression and compression of LZ4-encoded streams. These are exposed as a standard `Reader` and `Writer` interfaces wrapping an underlying stream. # Example ```rust,ignore use compr...
> { w: W, buf: Vec<u8>, tmp: Vec<u8>, wrote_header: bool, limit: usize, } impl<W: Write> Encoder<W> { /// Creates a new encoder which will have its output written to the given /// output stream. The output stream can be re-acquired by calling /// `finish()` /// /// NOTE: compres...
coder<W
identifier_name
lz4.rs
/*! LZ4 Decompression and Compression. Requires `lz4` feature, enabled by default This module contains an implementation in Rust of decompression and compression of LZ4-encoded streams. These are exposed as a standard `Reader` and `Writer` interfaces wrapping an underlying stream.
use std::fs::File; use std::path::Path; use std::io::Read; let stream = File::open(&Path::new("path/to/file.lz4")).unwrap(); let mut decompressed = Vec::new(); lz4::Decoder::new(stream).read_to_end(&mut decompressed); ``` # Credit This implementation is largely based on Branimir Karadžić's implementation which can b...
# Example ```rust,ignore use compress::lz4;
random_line_split
single_two_stage17_6_prw.py
import torch import torch.nn as nn import numpy as np from collections import defaultdict import torch.nn.functional as F # from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler from ..builder import DETECTORS, build_backbone, build_head, build_neck from .base import BaseDetector from mmdet.core ...
if roi_head is not None: # update train and test cfg here for now # TODO: refactor assigner & sampler rcnn_train_cfg = train_cfg.rcnn if train_cfg is not None else None roi_head.update(train_cfg=rcnn_train_cfg) roi_head.update(test_cfg=test_cfg.rcnn) ...
rpn_train_cfg = train_cfg.rpn if train_cfg is not None else None rpn_head_ = rpn_head.copy() rpn_head_.update(train_cfg=rpn_train_cfg, test_cfg=test_cfg.rpn) self.rpn_head = build_head(rpn_head_)
random_line_split
single_two_stage17_6_prw.py
import torch import torch.nn as nn import numpy as np from collections import defaultdict import torch.nn.functional as F # from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler from ..builder import DETECTORS, build_backbone, build_head, build_neck from .base import BaseDetector from mmdet.core ...
for i in range(len(pids_fcos)): if pids_fcos[i] < 0: continue else: targets2_value = pids_fcos[i].cpu().numpy().item() dic2[targets2_value].append(feats_fcos[i]) all_feats1 = [] all_feats2 = [] for...
if pids_roi[i] < 0: continue else: targets1_value = pids_roi[i].cpu().numpy().item() dic1[targets1_value].append(feats_roi[i])
conditional_block
single_two_stage17_6_prw.py
import torch import torch.nn as nn import numpy as np from collections import defaultdict import torch.nn.functional as F # from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler from ..builder import DETECTORS, build_backbone, build_head, build_neck from .base import BaseDetector from mmdet.core ...
@property def with_roi_head(self): """bool: whether the detector has a RoI head""" return hasattr(self, 'roi_head') and self.roi_head is not None def init_weights(self, pretrained=None): """Initialize the weights in detector. Args: pretrained (str, optional): ...
"""bool: whether the detector has RPN""" return hasattr(self, 'rpn_head') and self.rpn_head is not None
identifier_body
single_two_stage17_6_prw.py
import torch import torch.nn as nn import numpy as np from collections import defaultdict import torch.nn.functional as F # from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler from ..builder import DETECTORS, build_backbone, build_head, build_neck from .base import BaseDetector from mmdet.core ...
(self): """bool: whether the detector has RPN""" return hasattr(self, 'rpn_head') and self.rpn_head is not None @property def with_roi_head(self): """bool: whether the detector has a RoI head""" return hasattr(self, 'roi_head') and self.roi_head is not None def init_weights...
with_rpn
identifier_name
fabric.go
//(C) Copyright [2020] Hewlett Packard Enterprise Development LP // //Licensed under the Apache License, Version 2.0 (the "License"); you may //not use this file except in compliance with the License. You may obtain //a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by a...
// createChassisRequest creates the parameters ready for the plugin communication func (f *fabricFactory) createChassisRequest(ctx context.Context, plugin smodel.Plugin, url, method string, body *json.RawMessage) (pReq *pluginContactRequest, errResp *response.RPC, err error) { l.LogWithFields(ctx).Debug("Inside svc-...
{ l.LogWithFields(ctx).Debug("Inside svc-systems/chassis/fabric.go.getFabricManagerChassis") defer f.wg.Done() req, errResp, err := f.createChassisRequest(ctx, plugin, collectionURL, http.MethodGet, nil) if errResp != nil { l.LogWithFields(ctx).Warn("while trying to create fabric plugin request for " + plugin.ID ...
identifier_body
fabric.go
//(C) Copyright [2020] Hewlett Packard Enterprise Development LP // //Licensed under the Apache License, Version 2.0 (the "License"); you may //not use this file except in compliance with the License. You may obtain //a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by a...
(status int) bool { return status/100 == 2 }
is2xx
identifier_name
fabric.go
//(C) Copyright [2020] Hewlett Packard Enterprise Development LP // //Licensed under the Apache License, Version 2.0 (the "License"); you may //not use this file except in compliance with the License. You may obtain //a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by a...
var statusMessage string switch pluginResponse.StatusCode { case http.StatusOK: statusMessage = response.Success case http.StatusUnauthorized: statusMessage = response.ResourceAtURIUnauthorized case http.StatusNotFound: statusMessage = response.ResourceNotFound default: statusMessage = response.CouldNotE...
{ return nil, "", http.StatusInternalServerError, response.InternalError, fmt.Errorf(err.Error()) }
conditional_block
fabric.go
//(C) Copyright [2020] Hewlett Packard Enterprise Development LP // //Licensed under the Apache License, Version 2.0 (the "License"); you may //not use this file except in compliance with the License. You may obtain //a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by a...
} req.Token = token return contactPlugin(ctx, req) } func callPlugin(ctx context.Context, req *pluginContactRequest) (*http.Response, error) { var reqURL = "https://" + req.Plugin.IP + ":" + req.Plugin.Port + req.URL if strings.EqualFold(req.Plugin.PreferredAuthType, "BasicAuth") { return req.ContactClient(ctx...
if token == "" { resp = common.GeneralError(http.StatusUnauthorized, response.NoValidSession, "error: Unable to create session with plugin "+req.Plugin.ID, []interface{}{}, nil) data, _ := json.Marshal(resp.Body) return data, "", int(resp.StatusCode), response.NoValidSession, fmt.Errorf("error: Unable to crea...
random_line_split
p2p.pb.go
// Copyright (c) 2016-2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
() { *m = AnnouncePieceMessage{} } func (m *AnnouncePieceMessage) String() string { return proto.CompactTextString(m) } func (*AnnouncePieceMessage) ProtoMessage() {} func (*AnnouncePieceMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } // Unused. ty...
Reset
identifier_name
p2p.pb.go
// Copyright (c) 2016-2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
func (x ErrorMessage_ErrorCode) String() string { return proto.EnumName(ErrorMessage_ErrorCode_name, int32(x)) } func (ErrorMessage_ErrorCode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{5, 0} } type Message_Type int32 const ( Message_BITFIELD Message_Type = 0 Message_PIECE_REQUEST Messag...
var ErrorMessage_ErrorCode_value = map[string]int32{ "PIECE_REQUEST_FAILED": 0, }
random_line_split
p2p.pb.go
// Copyright (c) 2016-2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
var fileDescriptor0 = []byte{ // 647 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xac, 0x54, 0x4f, 0x6f, 0xd3, 0x4e, 0x10, 0x6d, 0x12, 0x3b, 0x7f, 0x26, 0x69, 0xeb, 0x6c, 0xa3, 0xdf, 0xcf, 0x14, 0x0e, 0x95, 0x45, 0x45, 0x85, 0xa0, 0xad, 0xcc, 0x05, 0x10, 0x12...
{ proto.RegisterFile("proto/p2p/p2p.proto", fileDescriptor0) }
identifier_body
p2p.pb.go
// Copyright (c) 2016-2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
return nil } // Requests a piece of the given index. Note: offset and length are unused fields // and if set, will be rejected. type PieceRequestMessage struct { Index int32 `protobuf:"varint,2,opt,name=index" json:"index,omitempty"` Offset int32 `protobuf:"varint,3,opt,name=offset" json:"offset,omitempty"` Leng...
{ return m.RemoteBitfieldBytes }
conditional_block
forest.go
// Package forest defines the Forest type. package forest import ( "context" "errors" "fmt" "sort" "strings" "sync" "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1...
// SetParent modifies the namespace's parent, including updating the list of children. It may result // in a cycle being created; this can be prevented by calling CanSetParent before, or seeing if it // happened by calling CycleNames afterwards. func (ns *Namespace) SetParent(p *Namespace) { // Remove old parent and...
{ if ns.allowCascadingDelete == true { return true } if !ns.IsSub { return false } // This is a subnamespace so it must have a non-nil parent. If the parent is missing, it will // return the default false. // // Subnamespaces can never be involved in cycles, since those can only occur at the "top" of a //...
identifier_body
forest.go
// Package forest defines the Forest type. package forest import ( "context" "errors" "fmt" "sort" "strings" "sync" "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1...
(p *Namespace) string { if p == nil { return "" } // Simple case if p == ns { return fmt.Sprintf("%q cannot be set as its own parent", p.name) } // Check for cycles; see if the current namespace (the proposed child) is already an ancestor of // the proposed parent. Start at the end of the ancestry (e.g. at...
CanSetParent
identifier_name
forest.go
// Package forest defines the Forest type. package forest import ( "context" "errors" "fmt" "sort" "strings" "sync" "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1...
pos := ns.GetPropagatedObjects(gvk) for _, po := range pos { if po.GetName() == name { return po } } return nil } // IsAncestor is *not* cycle-safe, so should only be called from namespace trees that are known not // to have cycles. func (ns *Namespace) IsAncestor(other *Namespace) bool { if ns.parent == o...
// Otherwise, return nil. func (ns *Namespace) GetSource(gvk schema.GroupVersionKind, name string) *unstructured.Unstructured {
random_line_split
forest.go
// Package forest defines the Forest type. package forest import ( "context" "errors" "fmt" "sort" "strings" "sync" "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1...
ancestors = ancestors[1:] // don't need the repeated element // Find the smallest name and where it is sidx := 0 snm := ancestors[0] for idx, nm := range ancestors { if nm < snm { sidx = idx snm = nm } } // Rotate the slice, and then duplicate the smallest element ancestors = append(ancestors[sidx:...
{ return nil }
conditional_block
marker.js
/** * * 图片标记器 * Author: tianchungang,wangfeng * e-mail: wfeng007@163.com * Date: 14-1-12 * Time: 下午8:22 * version: 0.2 */ (function ($) { //这三个是? var MarkerManager = { container:{} }; MarkerManager.setMarker = function(id,marker){ this.container[id] = marker; }; Marker...
identifier_body
marker.js
/** * * 图片标记器 * Author: tianchungang,wangfeng * e-mail: wfeng007@163.com * Date: 14-1-12 * Time: 下午8:22 * version: 0.2 */ (function ($) { //这三个是? var MarkerManager = { container:{} }; MarkerManager.setMarker = function(id,marker){ this.container[id] = marker; }; Marker...
return new Dragdrop(opt); } }(this); })(jQuery);
random_line_split
marker.js
/** * * 图片标记器 * Author: tianchungang,wangfeng * e-mail: wfeng007@163.com * Date: 14-1-12 * Time: 下午8:22 * version: 0.2 */ (function ($) { //这三个是? var MarkerManager = { container:{} }; MarkerManager.setMarker = function(id,marker){ this.container[id] = marker; }; Marker...
ft = moveX + 'px'); conf.dragY && (el.style.top = moveY + 'px'); if(conf.callback){ var obj = {moveX:moveX,moveY:moveY}; conf.callback.call(conf,obj); } } } function mouse...
style.le
identifier_name
marker.js
/** * * 图片标记器 * Author: tianchungang,wangfeng * e-mail: wfeng007@163.com * Date: 14-1-12 * Time: 下午8:22 * version: 0.2 */ (function ($) { //这三个是? var MarkerManager = { container:{} }; MarkerManager.setMarker = function(id,marker){ this.container[id] = marker; }; Marker...
return e || window.event; } }; return function(opt){ var conf = null, defaultConf, diffX, diffY; function Config(opt){ this.target = opt.target; this.bridge = opt.bridge; this.dragable = opt.dragable != false; ...
evt : function(e){
conditional_block
pools.rs
use crate::*; use serde::{Deserialize, Serialize}; impl BlockFrostApi { endpoints! { /// List of registered stake pools. pools() -> Vec<String> => "/pools"; ("https://docs.blockfrost.io/#tag/Cardano-Pools/paths/~1pools/get"), /// List of already retired pools. pools_ret...
] "# } test_schema! { test_pool_delegators, Vec<PoolDelegator>, r#" [ { "address": "stake1ux4vspfvwuus9uwyp5p3f0ky7a30jq5j80jxse0fr7pa56sgn8kha", "live_stake": "1137959159981411" }, { "address": "stake1uylayej7esmarzd4mk4aru37zh9yz0luj3g9fsvgpfaxulq564r5u", ...
"ipv6": "https://stakenuts.com/mainnet.json", "dns": "relay1.stakenuts.com", "dns_srv": "_relays._tcp.relays.stakenuts.com", "port": 3001 }
random_line_split
pools.rs
use crate::*; use serde::{Deserialize, Serialize}; impl BlockFrostApi { endpoints! { /// List of registered stake pools. pools() -> Vec<String> => "/pools"; ("https://docs.blockfrost.io/#tag/Cardano-Pools/paths/~1pools/get"), /// List of already retired pools. pools_ret...
{ /// Bech32 pool ID. pub pool_id: String, /// Hexadecimal pool ID. pub hex: String, /// VRF key hash. pub vrf_key: String, /// Total minted blocks. pub blocks_minted: Integer, pub live_stake: String, pub live_size: Float, pub live_saturation: Float, pub live_delegators:...
Pool
identifier_name
course-ripper.py
import requests from lxml import html import subprocess import os import re from bs4 import BeautifulSoup ''' ideas: change the course data structure toa a list of dictionaries. Then each dictionary has a 's_type' (section type: just using 'type' is illadvised because it is built in to Python) key-value pair and the ...
(section): """Creates a TeX formatted string for a given subsubsection""" string = '\\subsubsection*{' + section['heading'] + '}\n' string += section['value'] + '\n' return string def latex_course(course): """Creates a TeX formatted string for a course""" basic_info_list = [ 'session',...
latex_subsection
identifier_name
course-ripper.py
import requests from lxml import html import subprocess import os import re from bs4 import BeautifulSoup ''' ideas: change the course data structure toa a list of dictionaries. Then each dictionary has a 's_type' (section type: just using 'type' is illadvised because it is built in to Python) key-value pair and the ...
return course def bsoup(coursepage): """Given a course page, takes the context and parses it to extract all the useful information and construct a dictionary with the information corresponding to assigned names ready to be written into the TeX file TODO: What a mess. There should be a way...
course[info_tag] = new_dict( info_list[i] + ': ', info_list[i + 1]) i += 2
conditional_block
course-ripper.py
import requests from lxml import html import subprocess import os import re from bs4 import BeautifulSoup ''' ideas: change the course data structure toa a list of dictionaries. Then each dictionary has a 's_type' (section type: just using 'type' is illadvised because it is built in to Python) key-value pair and the ...
def get_info_list(info_string, course): """Each course page has a small info section at the beginning, which I had to extract and formulate in a different way to the main sections. This function constructs the dictionary entries for he course when given a string with all the details required for the ...
"""Creates a dictionary with a heading-value pair, which is the structure of all the sections in the courses dictionary """ value = value.replace('%', '\%').replace('&', '\&').replace(u'\xa0', ' ') # Currently encoding is causeing me problems - the quick fix below removes # all the characters that h...
identifier_body
course-ripper.py
import requests from lxml import html import subprocess import os import re from bs4 import BeautifulSoup ''' ideas: change the course data structure toa a list of dictionaries. Then each dictionary has a 's_type' (section type: just using 'type' is illadvised because it is built in to Python) key-value pair and the ...
There's definitely a better way to do this. """ info_list = [] split_on_newline = info_string.split("\n") for elem in split_on_newline: split = elem.split(": ") for s in split: info_list.append(s) info_list = info_list[1:-1] info_tags = [ 'session', 's...
random_line_split
storeDetail.js
$(document).ready(function() { console.log(window.location.pathname.indexOf("admin")); // 관리자페이지에서만 보이기 if (window.location.pathname.indexOf("admin") == 1) { $("#admin_button_box").css("display", "block"); } let cartStoreNum = null; // 카트에 담긴 메뉴의 가게번호, 서로 다른가게에서 담으면 안됨 let size = $(window).width(); ...
// -------------------- 가게 별점 -------------------- // -------------------- 리뷰탭 그래프 -------------------- const reviewCount = $("#review_count").val(); const fiveScore = $("#five_score").val() / reviewCount * 100 + "%"; const fourScore = $("#four_score").val() / reviewCount * 100 + "%"; const threeScore = $("...
$(".score_box i").eq(score).addClass("fas").prevAll().addClass("fas");
random_line_split
storeDetail.js
$(document).ready(function() { console.log(window.location.pathname.indexOf("admin")); // 관리자페이지에서만 보이기 if (window.location.pathname.indexOf("admin") == 1) { $("#admin_button_box").css("display", "block"); } let cartStoreNum = null; // 카트에 담긴 메뉴의 가게번호, 서로 다른가게에서 담으면 안됨 let size = $(window).width();...
).eq(3).hide(); const tab = $("ul.tab > li"); const menu = $(".menu > li"); tab.click(function() { const index = $(this).index() + 1; tab.removeClass("select"); $(this).addClass("select"); $("main ul").eq(1).hide(); $("main ul").eq(2).hide(); $("main ul").eq(3).hide(); $("main ul").eq(index).s...
dy").css("overflow", "visible"); $("#amount").val(1); optionPrice = 0; /* $("input[type='checkBox']").prop("checked", false); */ $(".plusOption").remove(); }; //탭 눌렀을때 색변경 콘텐츠 변경 $("main ul").eq(2).hide(); $("main ul"
identifier_body
storeDetail.js
$(document).ready(function() { console.log(window.location.pathname.indexOf("admin")); // 관리자페이지에서만 보이기 if (window.location.pathname.indexOf("admin") == 1) { $("#admin_button_box").css("display", "block"); } let cartStoreNum = null; // 카트에 담긴 메뉴의 가게번호, 서로 다른가게에서 담으면 안됨 let size = $(window).width();...
amountBox = $("#amount"); let amount = 1; $(".amount_box button").click(function() { if ($(this).hasClass("minus")) { amountBox.val() == 1 ? amountBox.val(amountBox.val()) : amountBox.val(Number(amountBox.val()) - 1); } else if ($(this).hasClass("plus")) { amountBox.val(Number(amountBox.val()) + 1); ...
-- */ /* ---------------------수량 증가 감소--------------------- */ const
conditional_block
storeDetail.js
$(document).ready(function() { console.log(window.location.pathname.indexOf("admin")); // 관리자페이지에서만 보이기 if (window.location.pathname.indexOf("admin") == 1) { $("#admin_button_box").css("display", "block"); } let cartStoreNum = null; // 카트에 담긴 메뉴의 가게번호, 서로 다른가게에서 담으면 안됨 let size = $(window).width();...
data("total"); function cartList(url, data) { $.ajax({ url: url, type: "post", data: data, async: false, traditional: true, success: function(result) { console.log(result); let ht = ""; let total = 0; if (result.length == 0) { $(".total").html("장바구니가 비었습니다."); $(".cart...
= $(".total").
identifier_name
memcached_test.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
// get global framework variables ctx := framework.NewTestCtx(t) defer ctx.Cleanup() operatorYAML, err := ioutil.ReadFile("deploy/operator.yaml") if err != nil { t.Fatalf("Could not read deploy/operator.yaml: %v", err) } local := *e2eImageName == "" if local { *e2eImageName = "quay.io/example/memcached-oper...
random_line_split
memcached_test.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
func memcachedScaleTest(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) error { // create example-memcached yaml file filename := "deploy/cr.yaml" err := ioutil.WriteFile(filename, []byte(crYAML), fileutil.DefaultFileMode) if err != nil { return err } // create memcached custom resource fr...
{ // get configmap, which is the lock lockName := "memcached-operator-lock" lock := v1.ConfigMap{} err := wait.Poll(retryInterval, timeout, func() (done bool, err error) { err = f.Client.Get(context.TODO(), types.NamespacedName{Name: lockName, Namespace: namespace}, &lock) if err != nil { if apierrors.IsNotF...
identifier_body
memcached_test.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
(t *testing.T) { // get global framework variables ctx := framework.NewTestCtx(t) defer ctx.Cleanup() namespace, err := ctx.GetNamespace() if err != nil { t.Fatal(err) } cmd := exec.Command("operator-sdk", "up", "local", "--namespace="+namespace) stderr, err := os.Create("stderr.txt") if err != nil { t.Fat...
MemcachedLocal
identifier_name
memcached_test.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
t.Log("Building operator docker image") cmdOut, err := exec.Command("operator-sdk", "build", *e2eImageName, "--enable-tests", "--test-location", "./test/e2e", "--namespaced-manifest", "deploy/operator.yaml").CombinedOutput() if err != nil { t.Fatalf("Error: %v\nCommand Output: %s\n", err, string(cmdOut)) }...
{ t.Fatalf("Failed to write deploy/operator.yaml: %v", err) }
conditional_block
utpgo.go
// Copyright (c) 2021 Storj Labs, Inc. // Copyright (c) 2010 BitTorrent, Inc. // See LICENSE for copying information. package utp import ( "context" "crypto/tls" "errors" "fmt" "io" "net" "os" "runtime/pprof" "sync" "syscall" "time" "github.com/go-logr/logr" "storj.io/utp-go/buffers" "storj.io/utp-go/...
return DialUTPOptions(network, nil, rAddr, options...) } func DialUTP(network string, localAddr, remoteAddr *Addr) (net.Conn, error) { return DialUTPOptions(network, localAddr, remoteAddr) } func DialUTPOptions(network string, localAddr, remoteAddr *Addr, options ...ConnectOption) (net.Conn, error) { s := utpDialSt...
return nil, err }
conditional_block