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
rastermanager.py
s = None cols = None rows = None xres = None yres = None # left geo coord 'e.g. Westernmost Longitude" left = None # top geo coord e.g highest Latitude extent top = None transform = [xres, 0.0, left, 0.0, yres, top] geoproperties_file = None # can contain multiple features o...
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
geo coord e.g highest Latitude extent top = None transform = [xres, 0.0, left, 0.0, yres, top] geoproperties_file = None # can contain multiple features of interest shapefile = None temp_folder = None def __init__(self, config_dict, shp=None): self.log = log_make_logger('RASTER ...
_warp_one
identifier_name
rastermanager.py
local_outname = outname.split('/')[-1] local_outpath = os.path.join(self.temp_folder, local_outname) self.log.debug('local_outpath {}'.format(local_outpath)) t0 = t_now() band1 = arr # write to a temp folder with rasterio.open(local_o...
""" 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
gen => "wasm-bindgen.exe", Self::WasmOpt => "bin/wasm-opt.exe", } } else { match self { Self::WasmBindgen => "wasm-bindgen", Self::WasmOpt => "bin/wasm-opt", } } } /// Additonal files included in the archive tha...
.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
=> "wasm-bindgen.exe", Self::WasmOpt => "bin/wasm-opt.exe", } } else { match self { Self::WasmBindgen => "wasm-bindgen", Self::WasmOpt => "bin/wasm-opt", } } } /// Additonal files included in the archive that a...
(&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
/// 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
Ext; use tokio::net::TcpStream; use tokio::sync::mpsc; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use tokio_util::codec::{FramedRead, FramedWrite}; use crate::connection::encryption::handle_encryption_negotiation; use crate::errors::ConnectionError; use crate::messages::codec::PacketMessageCodec; use...
_ => { 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
Ext; use tokio::net::TcpStream; use tokio::sync::mpsc; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use tokio_util::codec::{FramedRead, FramedWrite}; use crate::connection::encryption::handle_encryption_negotiation; use crate::errors::ConnectionError; use crate::messages::codec::PacketMessageCodec; use...
(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
Ext; use tokio::net::TcpStream; use tokio::sync::mpsc; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use tokio_util::codec::{FramedRead, FramedWrite}; use crate::connection::encryption::handle_encryption_negotiation; use crate::errors::ConnectionError; use crate::messages::codec::PacketMessageCodec; use...
#[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
Ext; use tokio::net::TcpStream; use tokio::sync::mpsc; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use tokio_util::codec::{FramedRead, FramedWrite}; use crate::connection::encryption::handle_encryption_negotiation; use crate::errors::ConnectionError; use crate::messages::codec::PacketMessageCodec; use...
match packet_message.emsg() { EMsg::ChannelEncryptRequest | EMsg::ChannelEncryptResponse | EMsg::ChannelEncryptResult => { handle_encryption_negotiation(sender.clone(), connection_state, packet_message).unwrap(); } _ => { ...
{ 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
count-1) or by specifying a min and a max (so that the sequence // is of items from min to max inclusive). After you construct the instance, // you can change the number of items by calling NextInt() or nextLong(). // // Note that the popular items will be clustered together, e.g. item 0 // is the most popular, item 1 ...
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
-1) or by specifying a min and a max (so that the sequence // is of items from min to max inclusive). After you construct the instance, // you can change the number of items by calling NextInt() or nextLong(). // // Note that the popular items will be clustered together, e.g. item 0 // is the most popular, item 1 the s...
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
// 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
-1) or by specifying a min and a max (so that the sequence // is of items from min to max inclusive). After you construct the instance, // you can change the number of items by calling NextInt() or nextLong(). // // Note that the popular items will be clustered together, e.g. item 0 // is the most popular, item 1 the s...
(items int64) *ScrambledZipfianGenerator { return
NewScrambledZipfianGeneratorByItems
identifier_name
mapnificent.js
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, 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
); // var input = $('<input type="range">').attr({ // max: Math.round(this.mapnificent.settings.options.maxWalkTravelTime / 60), // min: 0, // value: minutesTime // }).on('change', function(){ // self.setTime(parseInt($(this).val()) * 60); // }).on('mousemove keyup', function(){ ...
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
// var input = $('<input type="range">').attr({ // max: Math.round(this.mapnificent.settings.options.maxWalkTravelTime / 60), // min: 0, // value: minutesTime // }).on('change', function(){ // self.setTime(parseInt($(this).val()) * 60); // }).on('mousemove keyup', function(){ //...
}); }; 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
self.namespace return f def names(self): """ Return the names of the columns in design associated to the terms, i.e. len(self.names()) = self().shape[0]. """ if type(self.name) is types.StringType: return [self.name] else: return list...
(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
column number to remove. """ if reference is None: reference = 0 names = self.names() def maineffect_func(value, reference=reference): rvalue = [] keep = range(value.shape[0]) keep.pop(reference) for i in range(len(keep)): ...
out = [] for r in range(d1): for s in range(d2): out.append(value[r] * value[d1+s])
random_line_split
formula.py
def __call__(self, *args, **kw): """ Return the columns associated to self in a design matrix. If the term has no 'func' attribute, it returns ``self.namespace[self.termname]`` else, it returns ``self.func(*args, **kw)`` """ if not hasattr(self, ...
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
self.namespace return f def names(self): """ Return the names of the columns in design associated to the terms, i.e. len(self.names()) = self().shape[0]. """ if type(self.name) is types.StringType: return [self.name] else: return list...
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
main class Message: def __init__(self, message, users): # Get the text of the message self.text = message["text"] # Get the time stamp self.timestamp, self.msg_id = map(int, message["ts"].split(".")) # Set the time self.time_formatted = datetime.datetime.fromtimestamp(self.timestamp).strfti...
post=subject+"/private" slack.chat.post_message( channel=log_channel_id_priv, as_user=False, username=user, icon_url=icon, attachments=[{"pretext": post
output = "Wrote "+`n`+" private messages for #"+priv_channels[chan_id] body += output+"\n" print output
conditional_block
backup_slack.py
"] # The logging bot (running this program) formats in a special way if self.username == user: self.text = message["attachments"][0]["pretext"]+message["attachments"][0]["text"] except KeyError: # or maybe this was a comment of a comment try: self.uid =...
Channels = dict() l = slack.channels.list().body["channels"] for c in l: Channels[c["id"]] = c["name"] return Channels
identifier_body
backup_slack.py
main class Message: def __init__(self, message, users): # Get the text of the message self.text = message["text"] # Get the time stamp self.timestamp, self.msg_id = map(int, message["ts"].split(".")) # Set the time self.time_formatted = datetime.datetime.fromtimestamp(self.timestamp).strfti...
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
[-1])[0]+"_"+self.time_formatted+extension).replace(" ", "_")) # Naming of messages is wildly inconsistent... try: self.uid = message["user"] self.username = users[self.uid] # If something goes wrong with our key except KeyError: try: # Maybe this logged as a bot self....
GetUsers
identifier_name
api.py
() messages = api.chat_channel(channel, start, end) return messages """ { "messageCount": 2, "messages": [ { "message": "This is the most recent message response", "time": "Tue, 01 Dec 2015 09:08:46 GMT", "author": "exampleusername1" }, {...
@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
() messages = api.chat_channel(channel, start, end) return messages """ { "messageCount": 2, "messages": [ { "message": "This is the most recent message response", "time": "Tue, 01 Dec 2015 09:08:46 GMT", "author": "exampleusername1" }, {...
@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
/commands/<string:channel>") def api_channel_commands(channel): api = API() commands = api.channel_commands(channel) return commands """ { "commandCount": 2, "commands": [ { "command": "!testcommand1", "creator": "exampleusername1", "response": "Exam...
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
messages = api.chat_channel(channel, start, end) return messages """ { "messageCount": 2, "messages": [ { "message": "This is the most recent message response", "time": "Tue, 01 Dec 2015 09:08:46 GMT", "author": "exampleusername1" }, { ...
(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
self.batches = list((sum(new_index_counts[:i]), new_index_counts[i]) for i in range(self.num_mesh_objs)) print(self.batches, 'batches') # vertices self.vert_bounds = list((sum(self.v_stream_lens[:i]), sum(self.v_stream_lens[:i+1])-1) for i in range(self.num_mesh_objs)) # bounded...
mix_streams
identifier_name
main.py
for i in range(self.num_mesh_objs): new_index_data[self.index_mapping[i]] = self.index_stream[i] self.index_stream = new_index_data #print(self.index_stream) # First we need to find the length of each stream. self.GeometryData['IndexCount'] = 3*sum(self.i_stream_lens) ...
z_verts = [i[2] for i in v_stream]
random_line_split
main.py
self.descriptor = None for material in self.materials: if type(material) != str: material.make_elements(main=True) for anim_name in list(self.anim_data.keys()): self.anim_data[anim_name].make_elements(main=True) # write all the files ...
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
# 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
IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN...
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
SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETH...
#[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
"JSON"; static SIGN_METHOD: &str = "HMAC-SHA1"; static SIGNATURE_VERSION: &str = "1.0"; static VERSION: &str = "2017-05-25"; #[derive(Debug, Error)] pub enum DayuError { #[error("config of '{0}' absence")] ConfigAbsence(&'static str), #[error("dayu response error: {0}")] Dayu(DayuFailRespons...
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
SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETH...
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
() error { b, err := ioutil.ReadFile(*credPath) if err != nil { return err } return json.Unmarshal(b, &oauthClient.Credentials) } var userList XUserList var xReplyStatuses XReplyStatuses var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func randSeq(n int) string { b := make([]rune,...
() { 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
() error { b, err := ioutil.ReadFile(*credPath) if err != nil { return err } return json.Unmarshal(b, &oauthClient.Credentials) } var userList XUserList var xReplyStatuses XReplyStatuses var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func randSeq(n int) string { b := make([]rune,...
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
"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
() error
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
var err error if ret.OperationId, ret.Tags, err = o.config.GetOperationIDAndTagsFromRoute(route); err != nil { return ret, err } // Build responses for _, resp := range route.StatusCodeResponses() { ret.Responses.StatusCodeResponses[resp.Code()], err = o.buildResponse(resp.Model(), resp.Message(), route.Produ...
{ 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
{ 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, common.ExtensionPrefix) { if ret.Extensions == nil { ret.E...
(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
{ 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, common.ExtensionPrefix) { if ret.Extensions == nil { ret.E...
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
{ 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, common.ExtensionPrefix) { if ret.Extensions == nil { ret.E...
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
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHET...
""" fixes_dataset = set() FIXES_WEIGHT = Decimal(0.5) AUTHORS_WEIGHT = Decimal(0.25) REVISIONS_WEIGHT = Decimal(0.25) TIME_RANGE = Decimal(0.4) def __init__(self): self.revisions_timestamps = [] self.fixes_timestamps = [] self.authors_timestamps = [] self.re...
""" 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
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHET...
(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
# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WH...
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
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHET...
# 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
4.5 }; let x: Point1<f64> = Point1 { x: 1f64, y: 2f64 }; let y: Point1<f64> = Point1 { x: 3f64, y: 4f64 }; let myline = Line { start: x, end: y }; } fn tuples() { let x = 3; let y = 4; let sp = sum_and_product(x, y); let (sum, product) = sp; println!("sp = {:?}", (sum, product)); ...
scope_and_shadowing
identifier_name
main.rs
mut greeks = HashSet::new(); greeks.insert("alfa"); greeks.insert("delta"); greeks.insert("hamma"); greeks.insert("delta"); println!("{:?}", greeks); let added_delta = greeks.insert("delta"); if added_delta { println!("We added delta! hooray!") } let added_vega = greeks.ins...
Color::Cmyk { cyan: a, magenta: b, yellow: c, black: d } => println!("cmyk({
{ 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
let mut greeks = HashSet::new(); greeks.insert("alfa"); greeks.insert("delta"); greeks.insert("hamma"); greeks.insert("delta"); println!("{:?}", greeks); let added_delta = greeks.insert("delta"); if added_delta { println!("We added delta! hooray!") } let added_vega = greeks...
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
mut greeks = HashSet::new(); greeks.insert("alfa"); greeks.insert("delta"); greeks.insert("hamma"); greeks.insert("delta"); println!("{:?}", greeks); let added_delta = greeks.insert("delta"); if added_delta { println!("We added delta! hooray!") } let added_vega = greeks.ins...
} } } 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
buf: vec![0; 1024], tags: HashMap::new(), }) } /// Main event loop, runs forever after server is started. async fn run(&mut self) -> Result<(), io::Error> { debug!("Starting main event loop"); loop { if let Err(err) = self.next_event().await { ...
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
u32, ntp_frac_secs: u32) -> (u64, u32) { let unix_secs = ntp_secs as u64 - EPOCH_DELTA; let unix_micros = ((ntp_frac_secs as u64) * 1_000_000) >> 32; (unix_secs, unix_micros as u32) } // TODO: verify time conversions are actually correct, check roundtrips fn timetag_to_duration(ntp_secs: u32, ntp_frac_sec...
(&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
) } */ struct Server { /// Server's listening UDP socket. socket: UdpSocket, /// Internal buffer used for reading/writing UDP packets into. buf: Vec<u8>, /// Maps a tag name to sender/receiver pair. Used for signalling cancellations. tags: HashMap<String, (sync::watch::Sender<bool>, sync::wat...
{ 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
None]) self.maxlen = tf.shape(self.word_ids)[1] self.lengths = tf.count_nonzero(self.word_ids, 1) # 2. embedding self.word_embeddings = tf.Variable(tf.truncated_normal([len(word2idx), dim_word], stddev=1.0 / np.sqrt(dim_word))) self.char_embeddings = tf.Variable(tf.truncated_no...
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
, None]) self.maxlen = tf.shape(self.word_ids)[1] self.lengths = tf.count_nonzero(self.word_ids, 1) # 2. embedding self.word_embeddings = tf.Variable(tf.truncated_normal([len(word2idx), dim_word], stddev=1.0 / np.sqrt(dim_word))) self.char_embeddings = tf.Variable(tf.truncated_n...
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
None]) self.maxlen = tf.shape(self.word_ids)[1] self.lengths = tf.count_nonzero(self.word_ids, 1) # 2. embedding self.word_embeddings = tf.Variable(tf.truncated_normal([len(word2idx), dim_word], stddev=1.0 / np.sqrt(dim_word))) self.char_embeddings = tf.Variable(tf.truncated_no...
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
None]) self.maxlen = tf.shape(self.word_ids)[1] self.lengths = tf.count_nonzero(self.word_ids, 1) # 2. embedding self.word_embeddings = tf.Variable(tf.truncated_normal([len(word2idx), dim_word], stddev=1.0 / np.sqrt(dim_word))) self.char_embeddings = tf.Variable(tf.truncated_no...
# 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
) { if self.output.capacity() < target { debug!("growing {} to {}", self.output.capacity(), target); //let additional = target - self.output.capacity(); //self.output.reserve(additional); while self.output.len() < target { self.output.push(0); ...
// 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
.dest_pos; } let seq = self.seq_at(self.pos); let hash = (Wrapping(seq) * Wrapping(2654435761)).shr(HASH_SHIFT as usize).0; let mut r = (Wrapping(self.hash_table[hash as usize]) + Wrapping(UNINITHASH)).0; self.hash_tabl...
coder<W
identifier_name
lz4.rs
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
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
nn if train_cfg is not None else None roi_head.update(train_cfg=rcnn_train_cfg) roi_head.update(test_cfg=test_cfg.rcnn) self.roi_head = build_head(roi_head) bbox_head.update(train_cfg=train_cfg) bbox_head.update(test_cfg=test_cfg) self.bbox_head = build_head(...
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
nn if train_cfg is not None else None roi_head.update(train_cfg=rcnn_train_cfg) roi_head.update(test_cfg=test_cfg.rcnn) self.roi_head = build_head(roi_head) bbox_head.update(train_cfg=train_cfg) bbox_head.update(test_cfg=test_cfg) self.bbox_head = build_head(...
@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
nn if train_cfg is not None else None roi_head.update(train_cfg=rcnn_train_cfg) roi_head.update(test_cfg=test_cfg.rcnn) self.roi_head = build_head(roi_head) bbox_head.update(train_cfg=train_cfg) bbox_head.update(test_cfg=test_cfg) self.bbox_head = build_head(...
(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
" "github.com/ODIM-Project/ODIM/lib-utilities/response" "github.com/ODIM-Project/ODIM/svc-systems/smodel" "github.com/ODIM-Project/ODIM/svc-systems/sresponse" ) type fabricFactory struct { collection *sresponse.Collection chassisMap map[string]bool wg *sync.WaitGroup mu ...
} } // 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("Insid...
{ 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
abric.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 + ", got " + err.Error()) return } links, err := collec...
is2xx
identifier_name
fabric.go
" "github.com/ODIM-Project/ODIM/lib-utilities/response" "github.com/ODIM-Project/ODIM/svc-systems/smodel" "github.com/ODIM-Project/ODIM/svc-systems/sresponse" ) type fabricFactory struct { collection *sresponse.Collection chassisMap map[string]bool wg *sync.WaitGroup mu ...
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
/logs" "github.com/ODIM-Project/ODIM/lib-utilities/response" "github.com/ODIM-Project/ODIM/svc-systems/smodel" "github.com/ODIM-Project/ODIM/svc-systems/sresponse" ) type fabricFactory struct { collection *sresponse.Collection chassisMap map[string]bool wg *sync.WaitGroup mu ...
} 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
=offset" json:"offset,omitempty"` Length int32 `protobuf:"varint,4,opt,name=length" json:"length,omitempty"` } func (m *PieceRequestMessage) Reset() { *m = PieceRequestMessage{} } func (m *PieceRequestMessage) String() string { return proto.CompactTextString(m) } func (*PieceRequestMessa...
() { *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
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
=offset" json:"offset,omitempty"` Length int32 `protobuf:"varint,4,opt,name=length" json:"length,omitempty"` } func (m *PieceRequestMessage) Reset() { *m = PieceRequestMessage{} } func (m *PieceRequestMessage) String() string { return proto.CompactTextString(m) } func (*PieceRequestMessa...
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
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
// .spec.parent field. return nil } ns, ok := f.namespaces[nm] if ok { return ns } ns = &Namespace{ forest: f, name: nm, children: namedNamespaces{}, conditions: conditions{}, originalObjects: objects{}, } f.namespaces[nm] = ns return ns } // GetNamespaceNames r...
// 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
// .spec.parent field. return nil } ns, ok := f.namespaces[nm] if ok { return ns } ns = &Namespace{ forest: f, name: nm, children: namedNamespaces{}, conditions: conditions{}, originalObjects: objects{}, } f.namespaces[nm] = ns return ns } // GetNamespaceNames r...
(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
data structure return changed } // clean garbage collects this namespace if it has a zero value. func (ns *Namespace) clean() { // Don't clean up something that either exists or is otherwise referenced. if ns.exists || len(ns.children) > 0 { return } // Remove from the forest. delete(ns.forest.namespaces, ns...
// Otherwise, return nil. func (ns *Namespace) GetSource(gvk schema.GroupVersionKind, name string) *unstructured.Unstructured {
random_line_split
forest.go
// .spec.parent field. return nil } ns, ok := f.namespaces[nm] if ok { return ns } ns = &Namespace{ forest: f, name: nm, children: namedNamespaces{}, conditions: conditions{}, originalObjects: objects{}, } f.namespaces[nm] = ns return ns } // GetNamespaceNames r...
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
){ //当不是编辑模式时,提供一个viewClick函数回调,在非编辑模式中提供单击事件扩展。 $wrap.click(function(){ if(p.viewClick){ p.viewClick.call(this,$wrap,mark); } }); }else{ //...
identifier_body
marker.js
wrap = g.addMarker(x,y,$pic); if(!p.isEdit){ //当不是编辑模式时,提供一个viewClick函数回调,在非编辑模式中提供单击事件扩展。 $wrap.click(function(){ if(p.viewClick){ p.viewClick.call(this,$wrap,mark); }...
random_line_split
marker.js
ajax({ type:"post", url: p.markerUrl, dataType:"json", success:function(data){ var marks=data.marks; //读取数据后根据获取的数据直接构造标记 for(var i= 0;i<marks.length;i++){ var ...
style.le
identifier_name
marker.js
g.selectedMarker = wrapper; //单击选中 }) ; wrapper.css({left: x,top: y}); picObj.appendTo(wrapper); $modal.append(wrapper); if(p.isEdit){ //编辑状态下包装成可dd的dom new Dragdrop({ target : w...
evt : function(e){
conditional_block
pools.rs
of the stake pool. pub description: Option<String>, /// Home page of the stake pool. pub homepage: Option<String>, } /// Created by [`pools_relays`](BlockFrostApi::pools_relays) method. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct PoolRelay { /// IPv4 address of the relay. pub ipv4: ...
"ipv6": "https://stakenuts.com/mainnet.json", "dns": "relay1.stakenuts.com", "dns_srv": "_relays._tcp.relays.stakenuts.com", "port": 3001 }
random_line_split
pools.rs
}~1updates/get"), } } /// Created by [`pools_retired`](BlockFrostApi::pools_retired) method. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RetiredPool { /// Bech32 encoded pool ID. pub pool_id: String, /// Retirement epoch number. pub epoch: Integer, } /// Created by [`pools_retiring`...
{ /// 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
no need for weird counting in parsing the BSoup Problems it causes: - need to figure out how to determine what type data is as it is read in ''' def get_coursepage(code): """Given a course code, requests the correspnding course page""" url = 'http://gla.ac.uk/coursecatalogue/course/?code=' + code pri...
(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
+ no need for weird counting in parsing the BSoup Problems it causes: - need to figure out how to determine what type data is as it is read in ''' def get_coursepage(code): """Given a course code, requests the correspnding course page""" url = 'http://gla.ac.uk/coursecatalogue/course/?code=' + code p...
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
no need for weird counting in parsing the BSoup Problems it causes: - need to figure out how to determine what type data is as it is read in ''' def get_coursepage(code): """Given a course code, requests the correspnding course page""" url = 'http://gla.ac.uk/coursecatalogue/course/?code=' + code pri...
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
+ no need for weird counting in parsing the BSoup Problems it causes: - need to figure out how to determine what type data is as it is read in ''' def get_coursepage(code): """Given a course code, requests the correspnding course page""" url = 'http://gla.ac.uk/coursecatalogue/course/?code=' + code p...
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
// -------------------- 가게 별점 -------------------- // -------------------- 리뷰탭 그래프 -------------------- 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
/* ---------------------- 옵션 선택 --------------------- */ /* ---------------------수량 증가 감소--------------------- */ const amountBox = $("#amount"); let amount = 1; $(".amount_box button").click(function() { if ($(this).hasClass("minus")) { amountBox.val() == 1 ? amountBox.val(amountBox.val()) : amountBox....
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
removeClass("far"); $(this).addClass("fas"); dibsCheck = 1; if (userId != "guest") { const count = Number($(".count").html()); $(".count").html(count + 1); } } else { // 찜 되있을대 $(this).removeClass("fas"); $(this).addClass("far"); dibsCheck = 0; if (userId != "guest") { const...
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
removeClass("far"); $(this).addClass("fas"); dibsCheck = 1; if (userId != "guest") { const count = Number($(".count").html()); $(".count").html(count + 1); } } else { // 찜 되있을대 $(this).removeClass("fas"); $(this).addClass("far"); dibsCheck = 0; if (userId != "guest") { const...
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
"test/e2e/memcached_test.go.tmpl", "test/e2e/memcached_test.go").CombinedOutput() if err != nil { t.Fatalf("Could not rename test/e2e/memcached_test.go.tmpl: %v\nCommand Output:\n%v", err, string(cmdOut)) } t.Log("Pulling new dependencies with dep ensure") cmdOut, err = exec.Command("dep", "ensure").CombinedOut...
random_line_split
memcached_test.go
not find sha of PR") } } cmdOut, err = exec.Command("dep", "ensure").CombinedOutput() if err != nil { t.Fatalf("Error after modifying Gopkg.toml: %v\nCommand Output: %s\n", err, string(cmdOut)) } // Set replicas to 2 to test leader election. In production, this should // almost always be set to 1, because t...
{ // 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
old memcached_type.go file: (%v)", err) } err = ioutil.WriteFile("pkg/apis/cache/v1alpha1/memcached_types.go", bytes.Join(memcachedTypesFileLines, []byte("\n")), fileutil.DefaultFileMode) if err != nil { t.Fatal(err) } t.Log("Generating k8s") cmdOut, err = exec.Command("operator-sdk", "generate", "k8s").Combi...
MemcachedLocal
identifier_name
memcached_test.go
!= nil { t.Fatalf("Failed to symlink local operator-sdk project to vendor dir: (%v)", err) } } } file, err := yamlutil.GenerateCombinedGlobalManifest(scaffold.CRDsDir) if err != nil { t.Fatal(err) } // hacky way to use createFromYAML without exposing the method // create crd filename := file.Name() ...
{ t.Fatalf("Failed to write deploy/operator.yaml: %v", err) }
conditional_block
utpgo.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
utpgo.go
.encounteredError c.stateLock.Unlock() if willClose { return 0, c.makeOpError("write", net.ErrClosed) } if remoteIsDone { return 0, c.makeOpError("write", encounteredError) } if ok := c.writeBuffer.TryAppend(buf); ok { // make sure µTP knows about the new bytes. this might be a bit // confusing...
essIncomingPacket(dat
identifier_name