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
mod.rs
#![warn(missing_docs)] //! Contains all data structures and method to work with model resources. //! //! Model is an isolated scene that is used to create copies of its data - this //! process is known as `instantiation`. Isolation in this context means that //! such scene cannot be modified, rendered, etc. It just a ...
} impl Model { pub(crate) async fn load<P: AsRef<Path>>( path: P, serialization_context: Arc<SerializationContext>, resource_manager: ResourceManager, model_import_options: ModelImportOptions, ) -> Result<Self, ModelLoadError> { let extension = path .as_ref(...
{ ModelLoadError::Visit(e) }
identifier_body
mod.rs
#![warn(missing_docs)] //! Contains all data structures and method to work with model resources. //! //! Model is an isolated scene that is used to create copies of its data - this //! process is known as `instantiation`. Isolation in this context means that //! such scene cannot be modified, rendered, etc. It just a ...
{ pub(crate) path: PathBuf, #[visit(skip)] pub(crate) mapping: NodeMapping, #[visit(skip)] scene: Scene, } impl TypeUuidProvider for Model { fn type_uuid() -> Uuid { MODEL_RESOURCE_UUID } } /// Type alias for model resources. pub type ModelResource = Resource<Model>; /// Extensio...
Model
identifier_name
hypersonic.go
// Results from the competition are here: // https://www.codingame.com/challengereport/5708992986028c48464b3d45bbb4a490b2d6015 package main import "fmt" //import "os" import "bytes" import "strconv" // These indicate the contents of each cell of the floor in the input const WALL = -2 const CELL = -1 const BOX ...
// TODO: this does not account for walls & boxes, which block propagation of the explosion func amIWithinTheBlastRadius(myX int, myY int, bomb Bomb) bool{ if myX > bomb.x + bomb.reach || myX < bomb.x - bomb.reach || myY > bomb.y + bomb.reach || myY < bomb.y - bomb.reach {return true} return false } func tran...
{ if x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT {return false} return true }
identifier_body
hypersonic.go
// Results from the competition are here: // https://www.codingame.com/challengereport/5708992986028c48464b3d45bbb4a490b2d6015 package main import "fmt" //import "os" import "bytes" import "strconv" // These indicate the contents of each cell of the floor in the input const WALL = -2 const CELL = -1 const BOX ...
if cell == ITEM_RANGE || cell == ITEM_BOMB {buffer.WriteString("I")} buffer.WriteString(" ") } buffer.WriteString("\n") } return buffer.String() }
{buffer.WriteString("E")}
conditional_block
hypersonic.go
// Results from the competition are here: // https://www.codingame.com/challengereport/5708992986028c48464b3d45bbb4a490b2d6015 package main import "fmt" //import "os" import "bytes" import "strconv" // These indicate the contents of each cell of the floor in the input const WALL = -2 const CELL = -1 const BOX ...
return buffer.String() } func floorToString(floor [WIDTH][HEIGHT]int) string { var buffer bytes.Buffer var cell int for i := 0; i < HEIGHT; i++ { for j := 0; j < WIDTH; j++ { cell = floor[j][i] buffer.WriteString(" ") if cell == BOX {buffer.WriteString("B")} ...
buffer.WriteString(distanceStr) buffer.WriteString("]") } buffer.WriteString("\n") }
random_line_split
hypersonic.go
// Results from the competition are here: // https://www.codingame.com/challengereport/5708992986028c48464b3d45bbb4a490b2d6015 package main import "fmt" //import "os" import "bytes" import "strconv" // These indicate the contents of each cell of the floor in the input const WALL = -2 const CELL = -1 const BOX ...
(myX int, myY int, bombsOnTheFloor []Bomb, myReach int, floor [WIDTH][HEIGHT]int) [WIDTH][HEIGHT]Cell{ scoreFloor := [WIDTH][HEIGHT]Cell{} for i := 0; i < WIDTH; i++ { for j := 0; j < HEIGHT; j++ { scoreFloor[i][j] = scoreACell(i, j, myX, myY, bombsOnTheFloor, myReach, floor) } }...
scoreTheFloor
identifier_name
util.py
"""iminuit utility functions and classes. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import re import types from collections import OrderedDict, namedtuple from . import repr_html from . import repr_text from operator import itemgetter class Matrix...
def fitarg_rename(fitarg, ren): """Rename variable names in ``fitarg`` with rename function. :: #simple renaming fitarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1}, lambda pname: 'y' if pname=='x' else pname) #{'y':1, 'limit_y':1, 'fix_y':1, 'error_y':1}, ...
:ref:`function-sig-label` """ return better_arg_spec(f, verbose)
random_line_split
util.py
"""iminuit utility functions and classes. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import re import types from collections import OrderedDict, namedtuple from . import repr_html from . import repr_text from operator import itemgetter class Matrix...
(b): """Extract error from fitargs dictionary.""" return dict((k, v) for k, v in b.items() if k.startswith('error_')) def extract_fix(b): """extract fix attribute from fitargs dictionary""" return dict((k, v) for k, v in b.items() if k.startswith('fix_')) def remove_var(b, exclude): """Exclude v...
extract_error
identifier_name
util.py
"""iminuit utility functions and classes. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import re import types from collections import OrderedDict, namedtuple from . import repr_html from . import repr_text from operator import itemgetter class Matrix...
def make_func_code(params): """Make a func_code object to fake function signature. You can make a funccode from describable object by:: make_func_code(describe(f)) """ class FuncCode(object): __slots__ = ('co_varnames', 'co_argcount') fc = FuncCode() fc.co_varnames = params ...
"""Exclude variable in exclude list from b.""" return dict((k, v) for k, v in b.items() if param_name(k) not in exclude)
identifier_body
util.py
"""iminuit utility functions and classes. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import re import types from collections import OrderedDict, namedtuple from . import repr_html from . import repr_text from operator import itemgetter class Matrix...
newvn = pf + ren(vn) ret[newvn] = v return ret def true_param(p): """Check if ``p`` is a parameter name, not a limit/error/fix attributes. """ return (not p.startswith('limit_') and not p.startswith('error_') and not p.startswith('fix_')) def param_name(p): ...
if k.startswith(p): vn = k[len(p):] pf = p
conditional_block
properties.ts
import {SignalRef, TimeInterval} from 'vega'; import {isArray, isNumber} from 'vega-util'; import {isBinned, isBinning, isBinParams} from '../../bin'; import { COLOR, FILL, getSecondaryRangeChannel, isXorY, isXorYOffset, POLAR_POSITION_SCALE_CHANNELS, POSITION_SCALE_CHANNELS, ScaleChannel, STROKE } fr...
else if (isXorYOffset(channel)) { if (scaleType === ScaleType.POINT) { return 0.5; // so the point positions align with centers of band scales. } else if (scaleType === ScaleType.BAND) { return scaleConfig.offsetBandPaddingOuter; } } return undefined; } export function reverse( scaleType...
{ const {bandPaddingOuter, bandWithNestedOffsetPaddingOuter} = scaleConfig; if (hasNestedOffsetScale) { return bandWithNestedOffsetPaddingOuter; } // Padding is only set for X and Y by default. // Basically it doesn't make sense to add padding for color and size. if (scaleType === ScaleTyp...
conditional_block
properties.ts
import {SignalRef, TimeInterval} from 'vega'; import {isArray, isNumber} from 'vega-util'; import {isBinned, isBinning, isBinParams} from '../../bin'; import { COLOR, FILL, getSecondaryRangeChannel, isXorY, isXorYOffset, POLAR_POSITION_SCALE_CHANNELS, POSITION_SCALE_CHANNELS, ScaleChannel, STROKE } fr...
(model: Model, property: Exclude<keyof (Scale | ScaleComponentProps), 'range'>) { if (isUnitModel(model)) { parseUnitScaleProperty(model, property); } else { parseNonUnitScaleProperty(model, property); } } function parseUnitScaleProperty(model: UnitModel, property: Exclude<keyof (Scale | ScaleComponentPr...
parseScaleProperty
identifier_name
properties.ts
import {SignalRef, TimeInterval} from 'vega'; import {isArray, isNumber} from 'vega-util'; import {isBinned, isBinning, isBinParams} from '../../bin'; import { COLOR, FILL, getSecondaryRangeChannel, isXorY, isXorYOffset, POLAR_POSITION_SCALE_CHANNELS, POSITION_SCALE_CHANNELS, ScaleChannel, STROKE } fr...
switch (property) { case 'range': // For step, prefer larger step if (v1.step && v2.step) { return v1.step - v2.step; } return 0; // TODO: precedence rule for other properties } ...
valueWithExplicit, childValueWithExplicit, property, 'scale', tieBreakByComparing<VgScale, any>((v1, v2) => {
random_line_split
properties.ts
import {SignalRef, TimeInterval} from 'vega'; import {isArray, isNumber} from 'vega-util'; import {isBinned, isBinning, isBinParams} from '../../bin'; import { COLOR, FILL, getSecondaryRangeChannel, isXorY, isXorYOffset, POLAR_POSITION_SCALE_CHANNELS, POSITION_SCALE_CHANNELS, ScaleChannel, STROKE } fr...
export function paddingOuter( paddingValue: number | SignalRef, channel: ScaleChannel, scaleType: ScaleType, paddingInnerValue: number | SignalRef, scaleConfig: ScaleConfig<SignalRef>, hasNestedOffsetScale = false ) { if (paddingValue !== undefined) { // If user has already manually specified "paddi...
{ if (paddingValue !== undefined) { // If user has already manually specified "padding", no need to add default paddingInner. return undefined; } if (isXorY(channel)) { // Padding is only set for X and Y by default. // Basically it doesn't make sense to add padding for color and size. // pad...
identifier_body
io.rs
//! Persistent storage backend for blocks. use std::collections::VecDeque; use std::fs; use std::io::{self, Read, Seek, Write}; use std::iter; use std::mem; use std::path::Path; use nakamoto_common::bitcoin::consensus::encode::{Decodable, Encodable}; use nakamoto_common::block::store::{Error, Store}; use nakamoto_com...
Err(err) => return Err(err.into()), } self.index += buf.len() as u64; let items = buf.len() / size; let mut cursor = io::Cursor::new(buf); let mut item = vec![0; size]; for _ in 0..items { cursor.read_exact(&mut i...
{ self.file.seek(io::SeekFrom::Start(from))?; let n = self.file.read_to_end(&mut buf)?; buf.truncate(n); }
conditional_block
io.rs
//! Persistent storage backend for blocks. use std::collections::VecDeque; use std::fs; use std::io::{self, Read, Seek, Write}; use std::iter; use std::mem; use std::path::Path; use nakamoto_common::bitcoin::consensus::encode::{Decodable, Encodable}; use nakamoto_common::block::store::{Error, Store}; use nakamoto_com...
} } Ok(self.queue.pop_front()) } } /// An iterator over block headers in a file. #[derive(Debug)] pub struct Iter<H> { height: Height, file: FileReader<H>, } impl<H: Decodable> Iter<H> { fn new(file: fs::File) -> Self { Self { file: FileReader::new(file)...
for _ in 0..items { cursor.read_exact(&mut item)?; let item = H::consensus_decode(&mut item.as_slice())?; self.queue.push_back(item);
random_line_split
io.rs
//! Persistent storage backend for blocks. use std::collections::VecDeque; use std::fs; use std::io::{self, Read, Seek, Write}; use std::iter; use std::mem; use std::path::Path; use nakamoto_common::bitcoin::consensus::encode::{Decodable, Encodable}; use nakamoto_common::block::store::{Error, Store}; use nakamoto_com...
(&mut self) -> Option<Self::Item> { let height = self.height; assert!(height > 0); match self.file.next() { // If we hit this branch, it's because we're trying to read passed the end // of the file, which means there are no further headers remaining. Err(Err...
next
identifier_name
tweet_utils.py
#!/usr/bin/env python # coding: utf-8 # In[1]: from searchtweets import load_credentials,gen_request_parameters,collect_results,result_stream,utils # from secrets_ar import * import pandas as pd import glob import os import seaborn as sns import langid,re import collections import matplotlib.pyplot as plt from google...
if breakOut: print('Breaking out...') break print('Now we are done') print('Got {:d} tweets in total'.format(dfs[n].shape[0])) print('Between:') print(dfs[n].index[0]) print(dfs[n].index[-1]) ...
else: print('No results....') dfs[n] = dfs[n].append(pd.DataFrame()) breakOut = True
random_line_split
tweet_utils.py
#!/usr/bin/env python # coding: utf-8 # In[1]: from searchtweets import load_credentials,gen_request_parameters,collect_results,result_stream,utils # from secrets_ar import * import pandas as pd import glob import os import seaborn as sns import langid,re import collections import matplotlib.pyplot as plt from google...
ue): ''' Function to take a DataFrame of keywords and combine with OR operators to make a series of queries under 1024 characters. Optionally write the queries to a series of files ''' n = 0 lastN = 0 nFile = 0 tempQ = '' qs = [] print('Splitting queries') ...
eToFile = Tr
identifier_name
tweet_utils.py
#!/usr/bin/env python # coding: utf-8 # In[1]: from searchtweets import load_credentials,gen_request_parameters,collect_results,result_stream,utils # from secrets_ar import * import pandas as pd import glob import os import seaborn as sns import langid,re import collections import matplotlib.pyplot as plt from google...
enience function to split query string back up into keywords ''' return q.split(' OR ') def get_query_results_tw(queries, startdate, enddate): if os.environ['VERBOSE'] == 'VERBOSE': print('get_query_results_tw', queries, startdate, enddate) print(type(enddate)) search_args = load_...
t match a string ''' matches = [] tokens = t.lower().split() for q in qs: for kw in q.split(' OR '): if kw in tokens: #print('MATCHED',kw) matches.append(kw) return matches def queryToList(q): ''' Conv
identifier_body
tweet_utils.py
#!/usr/bin/env python # coding: utf-8 # In[1]: from searchtweets import load_credentials,gen_request_parameters,collect_results,result_stream,utils # from secrets_ar import * import pandas as pd import glob import os import seaborn as sns import langid,re import collections import matplotlib.pyplot as plt from google...
eclined keywords...') fileName = '' fileName = input('Enter file path for keywords(default: {:s}_declensions.csv)'.format(prefix)) if fileName == '': fileName = '{:s}_declensions.csv'.format(prefix) print('Reading declined keywords file...') declensionsDf = pd.read_csv(fileName,...
if prefix == '': prefix = 'az' print(prefix+' chosen') print('Getting list of d
conditional_block
dataset_data_particle.py
#!/usr/bin/env python """ @package mi.core.instrument.data_particle_generator Base data particle generator @file mi/core/instrument/data_particle_generator.py @author Steve Foley @brief Contains logic to generate data particles to be exchanged between the driver and agent. This involves a JSON interchange format """ ...
def __eq__(self, arg): """ Quick equality check for testing purposes. If they have the same raw data, timestamp, they are the same enough for this particle """ allowed_diff = .000001 if self._data_particle_type != arg._data_particle_type: log.debug('Data...
""" Build a particle seeded with appropriate information @param raw_data The raw data used in the particle """ if new_sequence is not None and not isinstance(new_sequence, bool): raise TypeError("new_sequence is not a bool") self.contents = { DataParticleKey.PKT...
identifier_body
dataset_data_particle.py
#!/usr/bin/env python """ @package mi.core.instrument.data_particle_generator Base data particle generator @file mi/core/instrument/data_particle_generator.py @author Steve Foley @brief Contains logic to generate data particles to be exchanged between the driver and agent. This involves a JSON interchange format """ ...
Build the base/header information for an output structure. Follow on methods can then modify it by adding or editing values. @return A fresh copy of a core structure to be exported """ result = dict(self.contents) # clean out optional fields that were missing if ...
"""
random_line_split
dataset_data_particle.py
#!/usr/bin/env python """ @package mi.core.instrument.data_particle_generator Base data particle generator @file mi/core/instrument/data_particle_generator.py @author Steve Foley @brief Contains logic to generate data particles to be exchanged between the driver and agent. This involves a JSON interchange format """ ...
payload = None length = None type = None checksum = None # Attempt to convert values try: payload = base64.b64encode(port_agent_packet.get("raw")) except TypeError: pass try: length = int(port_agent_packet.get("lengt...
raise SampleException("raw data not a complete port agent packet. missing %s" % param)
conditional_block
dataset_data_particle.py
#!/usr/bin/env python """ @package mi.core.instrument.data_particle_generator Base data particle generator @file mi/core/instrument/data_particle_generator.py @author Steve Foley @brief Contains logic to generate data particles to be exchanged between the driver and agent. This involves a JSON interchange format """ ...
(self, timestamp=None, unix_time=None): """ Set the internal timestamp @param timestamp: NTP timestamp to set @param unit_time: Unix time as returned from time.time() @raise InstrumentParameterException if timestamp or unix_time not supplied """ if timestamp is No...
set_internal_timestamp
identifier_name
perception.py
# System from threading import Condition # ROS import rospy from sensor_msgs.msg import Image, RegionOfInterest from std_srvs.srv import Empty # TU/e Robotics from image_recognition_msgs.srv import Annotate, Recognize, RecognizeResponse, GetFaceProperties from image_recognition_msgs.msg import Annotation, Recognition...
else: return self._get_faces(image).recognitions @staticmethod def get_best_face_recognition(recognitions, desired_label, probability_threshold=4.0): """ Returns the Recognition with the highest probability of having the desired_label. Assumes that the probability d...
return self._get_faces(image).recognitions, image.header.stamp
conditional_block
perception.py
# System from threading import Condition # ROS import rospy from sensor_msgs.msg import Image, RegionOfInterest from std_srvs.srv import Empty # TU/e Robotics from image_recognition_msgs.srv import Annotate, Recognize, RecognizeResponse, GetFaceProperties from image_recognition_msgs.msg import Annotation, Recognition...
# Skybiometry def get_face_properties(self, faces=None, image=None): """ Get the face properties of all faces or in an image. If faces is provided, image is ignored. If both aren't provided, an image is collected. :param faces: images of all faces :type faces: list[sens...
""" clearing all faces from the OpenFace node. :return: no return """ rospy.loginfo('clearing all learned faces') self._clear_srv()
identifier_body
perception.py
# System from threading import Condition # ROS import rospy from sensor_msgs.msg import Image, RegionOfInterest from std_srvs.srv import Empty # TU/e Robotics from image_recognition_msgs.srv import Annotate, Recognize, RecognizeResponse, GetFaceProperties from image_recognition_msgs.msg import Annotation, Recognition...
def clear_face(self): """ clearing all faces from the OpenFace node. :return: no return """ rospy.loginfo('clearing all learned faces') self._clear_srv() # Skybiometry def get_face_properties(self, faces=None, image=None): """ Get the face pr...
return best_recognition if best_recognition.categorical_distribution.probabilities[0].probability > probability_threshold else None else: return None # TODO: Maybe so something smart with selecting a recognition where the desired_label is not the most probable for a recognition?
random_line_split
perception.py
# System from threading import Condition # ROS import rospy from sensor_msgs.msg import Image, RegionOfInterest from std_srvs.srv import Empty # TU/e Robotics from image_recognition_msgs.srv import Annotate, Recognize, RecognizeResponse, GetFaceProperties from image_recognition_msgs.msg import Annotation, Recognition...
(self, image): self._camera_cv.acquire() self._camera_last_image = image self._camera_cv.notify() self._camera_cv.release() def get_image(self, timeout=5): # lazy subscribe to the kinect if not self._camera_lazy_sub: # for test with tripod kinect ...
_image_cb
identifier_name
routeOperator.go
// Copyright 2019-2023 The Liqo 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 ag...
// SetupSignalHandlerForRouteOperator registers for SIGTERM, SIGINT. Interrupt. A stop context is returned // which is closed on one of these signals. func (rc *RouteController) SetupSignalHandlerForRouteOperator() context.Context { ctx, done := context.WithCancel(context.Background()) c := make(chan os.Signal, 1) ...
{ resourceToBeProccesedPredicate := predicate.Funcs{ DeleteFunc: func(e event.DeleteEvent) bool { // Finalizers are used to check if a resource is being deleted, and perform there the needed actions // we don't want to reconcile on the delete of a resource. return false }, } return ctrl.NewControllerMan...
identifier_body
routeOperator.go
// Copyright 2019-2023 The Liqo 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 ag...
}() return nil } // cleanUp removes all the routes, rules and devices (if any) from the // node inserted by the operator. It is called at exit time. func (rc *RouteController) cleanUp() { if rc.firewallChan != nil { // send signal to clean firewall rules and close the go routine. rc.firewallChan <- true // ...
{ select { case <-ticker.C: // every five seconds we enforce the firewall rules. for i := range fwRules { if err := addRule(iptHandler, &fwRules[i]); err != nil { klog.Errorf("unable to insert firewall rule {%s}: %v", fwRules[i].String(), err) } else { klog.V(5).Infof("firewall rule {%s}...
conditional_block
routeOperator.go
// Copyright 2019-2023 The Liqo 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 ag...
(podIP string, vxlanDevice *overlay.VxlanDevice, router liqorouting.Routing, er record.EventRecorder, cl client.Client) *RouteController { r := &RouteController{ Client: cl, Routing: router, vxlanDev: vxlanDevice, EventRecorder: er, podIP: podIP, } return r } // cluster-role // ...
NewRouteController
identifier_name
routeOperator.go
// Copyright 2019-2023 The Liqo 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 ag...
// SetupSignalHandlerForRouteOperator registers for SIGTERM, SIGINT. Interrupt. A stop context is returned // which is closed on one of these signals. func (rc *RouteController) SetupSignalHandlerForRouteOperator() context.Context { ctx, done := context.WithCancel(context.Background()) c := make(chan os.Signal, 1) s...
random_line_split
th_logistic_regression.py
""" ************************************************************************** Theano Logistic Regression ************************************************************************** This version was just for local testing (Vee ran his version for our SBEL batch jobs) @author: Jason Feriante <feriante@cs.wisc.ed...
best_validation_loss = this_validation_loss # test it on the test set test_losses = [test_model(i) for i in xrange(n_test_batches)] test_score = numpy.mean(test_losses) # p...
patience = max(patience, iter * patience_increase)
conditional_block
th_logistic_regression.py
""" ************************************************************************** Theano Logistic Regression ************************************************************************** This version was just for local testing (Vee ran his version for our SBEL batch jobs) @author: Jason Feriante <feriante@cs.wisc.ed...
# percent_correct, auc = random_forest(target, X, Y, X_test, Y_test, curr_fl) # pct_ct.append(percent_correct) # roc_auc.append(auc) # # now get the average fold results for this target # accuracy = sum(pct_ct) / float(len(pct_ct)) # all...
# Y_test = np.array(Y_test)
random_line_split
th_logistic_regression.py
""" ************************************************************************** Theano Logistic Regression ************************************************************************** This version was just for local testing (Vee ran his version for our SBEL batch jobs) @author: Jason Feriante <feriante@cs.wisc.ed...
def negative_log_likelihood(self, y): """Return the mean of the negative log-likelihood of the prediction of this model under a given target distribution. .. math:: \frac{1}{|\mathcal{D}|} \mathcal{L} (\theta=\{W,b\}, \mathcal{D}) = \frac{1}{|\mathcal{D}|} \sum_{i=0}^...
""" Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the data...
identifier_body
th_logistic_regression.py
""" ************************************************************************** Theano Logistic Regression ************************************************************************** This version was just for local testing (Vee ran his version for our SBEL batch jobs) @author: Jason Feriante <feriante@cs.wisc.ed...
(self, input, n_in, n_out): """ Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dim...
__init__
identifier_name
schema.go
package gen import ( "bytes" "context" "encoding/json" "fmt" "net/url" "reflect" "strings" "unicode" "unicode/utf8" ) var knownSchemaFields = make(map[string]bool) func init() { for _, f := range getJSONFieldNames(Schema{}) { knownSchemaFields[f] = true } } // JSONType is the enumeration of JSONSchema'...
var parts []string for _, p := range strings.Split(s, "\n") { parts = append(parts, "// "+p) } return strings.Join(parts, "\n") }
{ return "" }
conditional_block
schema.go
package gen import ( "bytes" "context" "encoding/json" "fmt" "net/url" "reflect" "strings" "unicode" "unicode/utf8" ) var knownSchemaFields = make(map[string]bool) func init() { for _, f := range getJSONFieldNames(Schema{}) { knownSchemaFields[f] = true } } // JSONType is the enumeration of JSONSchema'...
if len(vals) == 0 || vals[0] == "" { fields = append(fields, field.Name) continue } if vals[0] != "-" { fields = append(fields, vals[0]) } } return } // NormalizeComment takes a comment string and makes sure it's normalized for Go func NormalizeComment(s string) string { if s == "" { return "" }...
random_line_split
schema.go
package gen import ( "bytes" "context" "encoding/json" "fmt" "net/url" "reflect" "strings" "unicode" "unicode/utf8" ) var knownSchemaFields = make(map[string]bool) func init() { for _, f := range getJSONFieldNames(Schema{}) { knownSchemaFields[f] = true } } // JSONType is the enumeration of JSONSchema'...
(k string) (s string) { _, _ = t.Unmarshal(k, &s) return } // Read unmarshals the json at the provided key into the provided interface (which should be a pointer amenable to // json.Read. If the key is not present, the pointer will be untouched, and false and nil will be returned. If the // deserialization fails, an...
GetString
identifier_name
schema.go
package gen import ( "bytes" "context" "encoding/json" "fmt" "net/url" "reflect" "strings" "unicode" "unicode/utf8" ) var knownSchemaFields = make(map[string]bool) func init() { for _, f := range getJSONFieldNames(Schema{}) { knownSchemaFields[f] = true } } // JSONType is the enumeration of JSONSchema'...
// Schema is the core representation of the JSONSchema meta schema. type Schema struct { // this could be a ref Ref *string `json:"$ref,omitempty"` // meta ID *url.URL `json:"-"` // set either from "$id", "id", or calculated based on parent (see IDCalc); never nil IDCalc bool `json:"-"` // whether this ...
{ if r.ref == nil { return r.schema, nil } parsed2, err := url.Parse(*r.ref) if err != nil { return nil, fmt.Errorf("parse $ref: %w", err) } return loader.Load(ctx, referer.Src.ResolveReference(parsed2)) }
identifier_body
policy.go
package miner import ( "fmt" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/ipfs/go-cid" mh "github.com/multiformats/go-multihash" "github.com/filecoin-project/specs-actors/v8/actors/builtin" ) // The period over which a miner's active sectors are...
// The maximum number of partitions that can be loaded in a single invocation. // This limits the number of simultaneous fault, recovery, or sector-extension declarations. // We set this to same as MaxPartitionsPerDeadline so we can process that many partitions every deadline. const AddressedPartitionsMax = MaxPartit...
{ // Check that the challenge windows divide the proving period evenly. if WPoStProvingPeriod%WPoStChallengeWindow != 0 { panic(fmt.Sprintf("incompatible proving period %d and challenge window %d", WPoStProvingPeriod, WPoStChallengeWindow)) } // Check that WPoStPeriodDeadlines is consistent with the proving perio...
identifier_body
policy.go
package miner import ( "fmt" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/ipfs/go-cid" mh "github.com/multiformats/go-multihash" "github.com/filecoin-project/specs-actors/v8/actors/builtin" ) // The period over which a miner's active sectors are...
// A deadline becomes immutable one challenge window before it's challenge window opens. // The challenge lookback must fall within this immutability period. if WPoStChallengeLookback > WPoStChallengeWindow { panic("the challenge lookback cannot exceed one challenge window") } // Deadlines are immutable when ...
{ panic(fmt.Sprintf("the proof dispute period %d must exceed finality %d", WPoStDisputeWindow, ChainFinality)) }
conditional_block
policy.go
package miner import ( "fmt" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/ipfs/go-cid" mh "github.com/multiformats/go-multihash" "github.com/filecoin-project/specs-actors/v8/actors/builtin" ) // The period over which a miner's active sectors are...
const ProveReplicaUpdatesMaxSize = PreCommitSectorBatchMaxSize // Maximum delay between challenge and pre-commitment. // This prevents a miner sealing sectors far in advance of committing them to the chain, thus committing to a // particular chain. var MaxPreCommitRandomnessLookback = builtin.EpochsInDay + ChainFinali...
random_line_split
policy.go
package miner import ( "fmt" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/ipfs/go-cid" mh "github.com/multiformats/go-multihash" "github.com/filecoin-project/specs-actors/v8/actors/builtin" ) // The period over which a miner's active sectors are...
(size abi.SectorSize, sector *SectorOnChainInfo) abi.StoragePower { duration := sector.Expiration - sector.Activation return QAPowerForWeight(size, duration, sector.DealWeight, sector.VerifiedDealWeight) } // Determine maximum number of deal miner's sector can hold func SectorDealsMax(size abi.SectorSize) uint64 { ...
QAPowerForSector
identifier_name
yuva_info.rs
use super::image_info; use crate::{prelude::*, EncodedOrigin, ISize, Matrix}; use skia_bindings::{self as sb, SkYUVAInfo, SkYUVAInfo_Subsampling}; use std::{fmt, ptr}; /// Specifies the structure of planes for a YUV image with optional alpha. The actual planar data /// is not part of this structure and depending on us...
(&self, plane_index: usize) -> (i32, i32) { plane_subsampling_factors(self.plane_config(), self.subsampling(), plane_index) } /// Dimensions of the full resolution image (after planes have been oriented to how the image /// is displayed as indicated by fOrigin). pub fn dimensions(&self) -> ISiz...
plane_subsampling_factors
identifier_name
yuva_info.rs
use super::image_info; use crate::{prelude::*, EncodedOrigin, ISize, Matrix}; use skia_bindings::{self as sb, SkYUVAInfo, SkYUVAInfo_Subsampling}; use std::{fmt, ptr}; /// Specifies the structure of planes for a YUV image with optional alpha. The actual planar data /// is not part of this structure and depending on us...
/// Number of Y, U, V, A channels in the ith plane for a given [PlaneConfig] (or [None] if i is /// invalid). pub fn num_channels_in_plane(config: PlaneConfig, i: usize) -> Option<usize> { (i < num_planes(config)).if_true_then_some(|| { unsafe { sb::C_SkYUVAInfo_NumChannelsInPlane(config, i.try_into().unw...
{ unsafe { sb::C_SkYUVAInfo_NumPlanes(config) } .try_into() .unwrap() }
identifier_body
yuva_info.rs
use super::image_info; use crate::{prelude::*, EncodedOrigin, ISize, Matrix}; use skia_bindings::{self as sb, SkYUVAInfo, SkYUVAInfo_Subsampling}; use std::{fmt, ptr}; /// Specifies the structure of planes for a YUV image with optional alpha. The actual planar data /// is not part of this structure and depending on us...
pub fn has_alpha(&self) -> bool { has_alpha(self.plane_config()) } /// Returns the dimensions for each plane. Dimensions are as stored in memory, before /// transformation to image display space as indicated by [origin(&self)]. pub fn plane_dimensions(&self) -> Vec<ISize> { self::pl...
random_line_split
labstats-subscriber.py
#!/usr/bin/env python import zmq import sys, os, time, random, signal, json sys.dont_write_bytecode = True import logging, labstatslogger, argparse from daemon import Daemon from datetime import datetime, timedelta, date from time import mktime, sleep import cPickle directory = "/var/run/labstats/" timeformat = '%Y-%m...
verbose_print("Reaped "+str(deleted)+" items from check-ins") output_checkins(last_check, new_dict) return (last_check, new_dict) ############################################################################### # Output the json into a log file in /var/log/labstats def output_log(to_write): if not os.p...
new_dict[hostname] = timestamp
conditional_block
labstats-subscriber.py
#!/usr/bin/env python import zmq import sys, os, time, random, signal, json sys.dont_write_bytecode = True import logging, labstatslogger, argparse from daemon import Daemon from datetime import datetime, timedelta, date from time import mktime, sleep import cPickle directory = "/var/run/labstats/" timeformat = '%Y-%m...
signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGHUP, sighup_handler) ''' Reaper functions: check timestamps, read in/out checked-in machines. By default, the reaper will write out its state every recv() and will check that all checked-in machines are no older than 20 minutes (by default) every...
error_output("Collector received a SIGHUP") context.destroy() time.sleep(5) main(options.retries, 2000, options.tlimit)
identifier_body
labstats-subscriber.py
#!/usr/bin/env python import zmq import sys, os, time, random, signal, json sys.dont_write_bytecode = True import logging, labstatslogger, argparse from daemon import Daemon from datetime import datetime, timedelta, date from time import mktime, sleep import cPickle directory = "/var/run/labstats/" timeformat = '%Y-%m...
def outdated(curtime, timestamp): # pass in type datetime, datetime verbose_print("Checking timestamp "+timestamp.strftime(timeformat)+" against current time") timeobj = datetime.fromtimestamp(mktime(timestamp.timetuple())) diff = curtime - timeobj # type timedelta return diff >= timedelta(minutes = op...
# Returns True if timestamp is outdated
random_line_split
labstats-subscriber.py
#!/usr/bin/env python import zmq import sys, os, time, random, signal, json sys.dont_write_bytecode = True import logging, labstatslogger, argparse from daemon import Daemon from datetime import datetime, timedelta, date from time import mktime, sleep import cPickle directory = "/var/run/labstats/" timeformat = '%Y-%m...
(ntries, ntime, tlimit): last_check, check_ins = read_checkins() # Set up ZMQ sockets and connections context = zmq.Context() subscriber = context.socket(zmq.SUB) subscriber.setsockopt(zmq.SUBSCRIBE,'') pushsocket = context.socket(zmq.PUSH) try: subscriber.connect('tcp://%s:5556...
main
identifier_name
gocomics.py
# SPDX-License-Identifier: MIT # Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs # Copyright (C) 2012-2014 Bastian Kleineidam # Copyright (C) 2015-2022 Tobias Gruetzmacher from ..scraper import ParserScraper from ..helpers import indirectStarter class GoComics(ParserScraper): url = 'https://www.goco...
cls('KidBeowulf', 'kid-beowulf'), cls('KitchenCapers', 'kitchen-capers'), cls('Kliban', 'kliban'), cls('KlibansCats', 'klibans-cats'), cls('LaCucaracha', 'lacucaracha'), cls('LaCucarachaEnEspanol', 'la-cucaracha-en-espanol', 'es'), cls(...
cls('JunkDrawer', 'junk-drawer'), cls('JustoYFranco', 'justo-y-franco', 'es'), cls('KevinKallaugher', 'kal'), cls('KevinNecessaryEditorialCartoons', 'kevin-necessary-editorial-cartoons'),
random_line_split
gocomics.py
# SPDX-License-Identifier: MIT # Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs # Copyright (C) 2012-2014 Bastian Kleineidam # Copyright (C) 2015-2022 Tobias Gruetzmacher from ..scraper import ParserScraper from ..helpers import indirectStarter class GoComics(ParserScraper): url = 'https://www.goco...
def namer(self, image_url, page_url): prefix, year, month, day = page_url.rsplit('/', 3) return "%s_%s%s%s.gif" % (self.shortname, year, month, day) def getIndexStripUrl(self, index): return '{}/{}'.format(self.url, index) def shouldSkipUrl(self, url, data): """Skip pages...
self.lang = lang
conditional_block
gocomics.py
# SPDX-License-Identifier: MIT # Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs # Copyright (C) 2012-2014 Bastian Kleineidam # Copyright (C) 2015-2022 Tobias Gruetzmacher from ..scraper import ParserScraper from ..helpers import indirectStarter class GoComics(ParserScraper):
url = 'https://www.gocomics.com/' imageSearch = '//picture[d:class("item-comic-image")]/img' prevSearch = '//a[d:class("js-previous-comic")]' latestSearch = '//div[d:class("gc-deck--cta-0")]//a' starter = indirectStarter help = 'Index format: yyyy/mm/dd' def __init__(self, name, path, lang=None...
identifier_body
gocomics.py
# SPDX-License-Identifier: MIT # Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs # Copyright (C) 2012-2014 Bastian Kleineidam # Copyright (C) 2015-2022 Tobias Gruetzmacher from ..scraper import ParserScraper from ..helpers import indirectStarter class GoComics(ParserScraper): url = 'https://www.goco...
(self, url, data): """Skip pages without images.""" return data.xpath('//img[contains(@src, "content-error-missing")]') @classmethod def getmodules(cls): # noqa: CFQ001 return ( # old comics removed from the listing cls('HeavenlyNostrils', 'heavenly-nostrils'), ...
shouldSkipUrl
identifier_name
PushForm.js
'use strict'; import * as Immutable from 'immutable'; import moment from 'moment'; import React, { PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Button, Card, Col, Collapse, DatePicker, Form, Input, InputNumber, Radio, Row, Select, Tim...
} else { console.log('需要精确到分钟____________', moment(data.get(pushTimeDatePickerFN)).format('YYYYMMDD') + moment(data.get(pushTimeTimePickerFN)).format('HHmm')); data.set('pushTime', moment(data.get(pushTimeDatePickerFN)).format('YYYYMMDD') + moment(data.get(pushTimeTimePickerFN)).format('HHmmss')); con...
.get(targetValueFN)) { MsgUtil.showwarning('指定wenwenId信息不正确'); return; } if (data.get(targetFN) === 'ALL') { data.set(targetValueFN, 'ALL'); } //设置推送时间 if (data.get(isSetPushTimeFN) === 'true') { if (!data.get(pushTimeDatePickerFN) || !data.get(pushTimeTimePickerFN)) { MsgUtil.showwa...
conditional_block
PushForm.js
'use strict'; import * as Immutable from 'immutable'; import moment from 'moment'; import React, { PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Button, Card, Col, Collapse, DatePicker, Form, Input, InputNumber, Radio, Row, Select, Tim...
, countryList } = this.props; if (!countryList || countryList.length < 1) { actions.getStaticDataByCodeType(Constant.USER_COUNTRY_ATTR_CODE); } } onPushBigTypeChange = (evt) => { const { getFieldValue, setFieldsValue } = this.props.form; setFieldsValue(pushTypeFN, pushType[getFieldValue(pushBigTypeFN)][...
actions
identifier_name
PushForm.js
'use strict'; import * as Immutable from 'immutable'; import moment from 'moment'; import React, { PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Button, Card, Col, Collapse, DatePicker, Form, Input, InputNumber, Radio, Row, Select, Tim...
<Row> <Col span={15} > <Form layout="inline" > <Row>&nbsp;</Row> <Row style={{ width: 1045 }} > 推送大类 &nbsp; &nbsp; {PushBigTypeProp( <Select style={{ width: 250 }} > {pushBigTypeOptions} </Select>, )}&nbsp; &nbsp; 推送小类 &nbsp; &nbsp; {Pu...
} else { contentPanelBoxLabel = '消息'; } return (
random_line_split
app.js
'use strict'; define(['angular', 'ol', 'toolbar', 'layermanager', 'sidebar', 'map', 'ows', 'query', 'search', 'print', 'permalink', 'measure', 'bootstrap', 'legend', 'panoramio', 'geolocation', 'core', 'wirecloud', 'angular-gettext', 'translations'], function(angular, ol, toolbar, layermanager) { var modu...
function processUnit(data) { var attributes = { id: data.id }; var projection = 'EPSG:4326'; /*for(var meta_i; meta_i<attr.metadatas.length; meta_i++){ if(attr.metadatas[meta_i].name=="location") projection = a...
{ //Get settings from configuration var id_attr_name = MashupPlatform.prefs.get('id_attr_name'); var coordinates_attr_name = MashupPlatform.prefs.get('coordinates_attr_name'); var measurements_attr_names = MashupPlatform.prefs.get('measurements_attr_names').split(','); ...
identifier_body
app.js
'use strict'; define(['angular', 'ol', 'toolbar', 'layermanager', 'sidebar', 'map', 'ows', 'query', 'search', 'print', 'permalink', 'measure', 'bootstrap', 'legend', 'panoramio', 'geolocation', 'core', 'wirecloud', 'angular-gettext', 'translations'], function(angular, ol, toolbar, layermanager) { var modu...
});
return module;
random_line_split
app.js
'use strict'; define(['angular', 'ol', 'toolbar', 'layermanager', 'sidebar', 'map', 'ows', 'query', 'search', 'print', 'permalink', 'measure', 'bootstrap', 'legend', 'panoramio', 'geolocation', 'core', 'wirecloud', 'angular-gettext', 'translations'], function(angular, ol, toolbar, layermanager) { var modu...
(numOfSteps, step, opacity) { // based on http://stackoverflow.com/a/7419630 // This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distiguishable vibrant markers in Google Maps and other apps. // Adam Cole, 2011-Sept-14 ...
rainbow
identifier_name
app.js
'use strict'; define(['angular', 'ol', 'toolbar', 'layermanager', 'sidebar', 'map', 'ows', 'query', 'search', 'print', 'permalink', 'measure', 'bootstrap', 'legend', 'panoramio', 'geolocation', 'core', 'wirecloud', 'angular-gettext', 'translations'], function(angular, ol, toolbar, layermanager) { var modu...
} module.value('config', { default_layers: [ new ol.layer.Tile({ source: new ol.source.OSM(), show_in_manager: true, title: "Base layer", base: true }), location_l...
{ location_feature_ids[data.unit].tags[data.id] = data; var max_temp = -273.15; var timestamp = ""; for (var tag in location_feature_ids[data.unit].tags) { var t = parseFloat(location_feature_ids[data.unit].tags[tag].temperature); ...
conditional_block
main.py
''' Implementation of DES ''' ################################################ INITIAL CONSTANTS BEGIN HERE ########################################################### import sys import bitarray # First Key Permutation done on the 64 bit key to retreieve a 56 bit version PC1 = [57, 49, 41, 33, 25, 17, 9, ...
############################################################### END OF KEY FUNCTIONS ######################################################### ############################################################### ENCODING STARTS HERE ######################################################### #take a list of binary wo...
key_bits = hexToBinary(key) if len(key_bits) != 64: print("Incorrect key provided.") sys.exit() key_up = [] for i in range (56): key_up.append(key_bits[PC1[i]-1]) key_up = ''.join(key_up) print("The initial key is {}".format(key_bits)) print("They permuted key is {}".format(key_up)) subkeys...
identifier_body
main.py
''' Implementation of DES ''' ################################################ INITIAL CONSTANTS BEGIN HERE ########################################################### import sys import bitarray # First Key Permutation done on the 64 bit key to retreieve a 56 bit version PC1 = [57, 49, 41, 33, 25, 17, 9, ...
return ''.join(reducedR) #Input an individual 64 bit message into to get encrypted def message_encryption(message, subkeys): temp_msg = message print("the full message is : {}".format(temp_msg)) print("The message is {} -- {}".format(temp_msg[:32], temp_msg[32:])) L_n = temp_msg[:32] R_n = temp_msg[32:]...
row = int(splitList[i][0] + splitList[i][-1],2) col = int(splitList[i][1] + splitList[i][2] + splitList[i][3] + splitList[i][4],2) newVal = SBOXES[int(i)][row][col] bits = str(format(newVal,"b")).zfill(4) reducedR.append(bits)
conditional_block
main.py
''' Implementation of DES ''' ################################################ INITIAL CONSTANTS BEGIN HERE ########################################################### import sys import bitarray # First Key Permutation done on the 64 bit key to retreieve a 56 bit version PC1 = [57, 49, 41, 33, 25, 17, 9, ...
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]], 2: [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10,...
random_line_split
main.py
''' Implementation of DES ''' ################################################ INITIAL CONSTANTS BEGIN HERE ########################################################### import sys import bitarray # First Key Permutation done on the 64 bit key to retreieve a 56 bit version PC1 = [57, 49, 41, 33, 25, 17, 9, ...
(): # subkeys = generate_subkeys("133457799BBCDFF1") # print(DESencryption("is is a nice time to be alive")) # print("\n\n\n") print(DESencryption("Today is a good day.")) if __name__ == "__main__": test()
test
identifier_name
data.go
package uplink import ( "context" "fmt" "strings" "time" log "github.com/sirupsen/logrus" "github.com/pkg/errors" "github.com/brocaar/loraserver/api/as" "github.com/brocaar/loraserver/api/nc" "github.com/brocaar/loraserver/internal/adr" "github.com/brocaar/loraserver/internal/channels" "github.com/brocaar...
{ var cids []lorawan.CID blocks := make(map[lorawan.CID]maccommand.Block) // group mac-commands by CID for _, cmd := range commands { block, ok := blocks[cmd.CID] if !ok { block = maccommand.Block{ CID: cmd.CID, FRMPayload: frmPayload, } cids = append(cids, cmd.CID) } block.MACComma...
identifier_body
data.go
package uplink import ( "context" "fmt" "strings" "time" log "github.com/sirupsen/logrus" "github.com/pkg/errors" "github.com/brocaar/loraserver/api/as" "github.com/brocaar/loraserver/api/nc" "github.com/brocaar/loraserver/internal/adr" "github.com/brocaar/loraserver/internal/channels" "github.com/brocaar...
Time: rxInfo.Time.Format(time.RFC3339Nano), Rssi: int32(rxInfo.RSSI), LoRaSNR: rxInfo.LoRaSNR, }) } _, err := common.Controller.HandleRXInfo(context.Background(), &rxInfoReq) if err != nil { return fmt.Errorf("publish rxinfo to network-controller error: %s", err) } log.WithFields(log.Fields{ ...
copy(mac, rxInfo.MAC[:]) rxInfoReq.RxInfo = append(rxInfoReq.RxInfo, &nc.RXInfo{ Mac: mac,
random_line_split
data.go
package uplink import ( "context" "fmt" "strings" "time" log "github.com/sirupsen/logrus" "github.com/pkg/errors" "github.com/brocaar/loraserver/api/as" "github.com/brocaar/loraserver/api/nc" "github.com/brocaar/loraserver/internal/adr" "github.com/brocaar/loraserver/internal/channels" "github.com/brocaar...
log.WithFields(log.Fields{ "dev_eui": ns.DevEUI, }).Info("rx info sent to network-controller") return nil } func publishDataUp(ns session.NodeSession, rxPacket models.RXPacket, macPL lorawan.MACPayload) error { publishDataUpReq := as.HandleDataUpRequest{ AppEUI: ns.AppEUI[:], DevEUI: ns.DevEUI[:], FCnt: ...
{ return fmt.Errorf("publish rxinfo to network-controller error: %s", err) }
conditional_block
data.go
package uplink import ( "context" "fmt" "strings" "time" log "github.com/sirupsen/logrus" "github.com/pkg/errors" "github.com/brocaar/loraserver/api/as" "github.com/brocaar/loraserver/api/nc" "github.com/brocaar/loraserver/internal/adr" "github.com/brocaar/loraserver/internal/channels" "github.com/brocaar...
(ctx *DataUpContext) error { // TODO: only log in case of error? if !ctx.MACPayload.FHDR.FCtrl.ACK { return nil } _, err := common.Application.HandleDataDownACK(context.Background(), &as.HandleDataDownACKRequest{ AppEUI: ctx.NodeSession.AppEUI[:], DevEUI: ctx.NodeSession.DevEUI[:], FCnt: ctx.NodeSession....
handleUplinkACK
identifier_name
kaart-teken-laag.component.ts
import { Component, NgZone, OnDestroy, OnInit, ViewEncapsulation, } from "@angular/core"; import { option } from "fp-ts"; import { pipe } from "fp-ts/lib/function"; import { Subject } from "rxjs"; import { distinctUntilChanged, map, skipWhile } from "rxjs/operators"; import * as uuid from "uuid"; import { Tr...
this.source.removeFeature(feature); } }); // Hou de subject bij. this.bindToLifeCycle( this.kaartModel$.pipe( distinctUntilChanged( (k1, k2) => k1.geometryChangedSubj === k2.geometryChangedSubj ), // map((kwi) => kwi.geometryChangedSubj) ) )....
{ this.dispatch(prt.VerwijderOverlaysCmd([tooltip])); }
conditional_block
kaart-teken-laag.component.ts
import { Component, NgZone, OnDestroy, OnInit, ViewEncapsulation, } from "@angular/core"; import { option } from "fp-ts"; import { pipe } from "fp-ts/lib/function"; import { Subject } from "rxjs"; import { distinctUntilChanged, map, skipWhile } from "rxjs/operators"; import * as uuid from "uuid"; import { Tr...
(tekenSettings: ke.TekenSettings): void { if (this.tekenen) { this.stopMetTekenen(); } this.source = option.fold( () => new ol.source.Vector(), (geom: ol.geom.Geometry) => { const source = new ol.source.Vector(); source.addFeature(new ol.Feature(geom)); return sour...
startMetTekenen
identifier_name
kaart-teken-laag.component.ts
import { Component, NgZone, OnDestroy, OnInit, ViewEncapsulation, } from "@angular/core"; import { option } from "fp-ts"; import { pipe } from "fp-ts/lib/function"; import { Subject } from "rxjs"; import { distinctUntilChanged, map, skipWhile } from "rxjs/operators"; import * as uuid from "uuid"; import { Tr...
import { VeldInfo } from "../kaart-elementen"; import { KaartInternalMsg, kaartLogOnlyWrapper, tekenWrapper, VerwijderTekenFeatureMsg, } from "../kaart-internal-messages"; import * as prt from "../kaart-protocol"; import { KaartComponent } from "../kaart.component"; import { asStyleSelector, toStylish } from "....
import { forEach } from "../../util/option"; import { KaartChildDirective } from "../kaart-child.directive"; import * as ke from "../kaart-elementen";
random_line_split
kaart-teken-laag.component.ts
import { Component, NgZone, OnDestroy, OnInit, ViewEncapsulation, } from "@angular/core"; import { option } from "fp-ts"; import { pipe } from "fp-ts/lib/function"; import { Subject } from "rxjs"; import { distinctUntilChanged, map, skipWhile } from "rxjs/operators"; import * as uuid from "uuid"; import { Tr...
private createLayer( source: ol.source.Vector, tekenSettings: ke.TekenSettings ): ke.VectorLaag { return { type: ke.VectorType, titel: TekenLaagNaam, source: source, clusterDistance: option.none, styleSelector: pipe( tekenSettings.laagStyle, option.alt(() ...
{ if (this.tekenen) { this.dispatch(prt.VerwijderInteractieCmd(this.drawInteraction)); this.dispatch(prt.VerwijderInteractieCmd(this.modifyInteraction)); this.dispatch(prt.VerwijderInteractieCmd(this.snapInteraction)); this.dispatch(prt.VerwijderOverlaysCmd(this.overlays)); this.dispat...
identifier_body
commands.py
from telethon import events from var import Var from pathlib import Path from ub.config import Config import re, logging, inspect, sys, json, os from asyncio import create_subprocess_shell as asyncsubshell, subprocess as asyncsub from os import remove from time import gmtime, strftime from traceback import format_exc f...
async def a(): test1 = await bot.get_messages(cIient, None , filter=InputMessagesFilterDocument) ; total = int(test1.total) ; total_doxx = range(0, total) for ixo in total_doxx: mxo = test1[ixo].id ; await client.download_media(await borg.get_messages(cIient, ids=mxo), "ub/modules/") ...
args["func"] = lambda e: e.via_bot_id is None stack = inspect.stack() previous_stack_frame = stack[1] file_test = Path(previous_stack_frame.filename) file_test = file_test.stem.replace(".py", "") pattern = args.get("pattern", None) allow_sudo = args.get("allow_sudo", None...
identifier_body
commands.py
from telethon import events from var import Var from pathlib import Path from ub.config import Config import re, logging, inspect, sys, json, os from asyncio import create_subprocess_shell as asyncsubshell, subprocess as asyncsub from os import remove from time import gmtime, strftime from traceback import format_exc f...
(**args): args["func"] = lambda e: e.via_bot_id is None stack = inspect.stack() previous_stack_frame = stack[1] file_test = Path(previous_stack_frame.filename) file_test = file_test.stem.replace(".py", "") pattern = args.get("pattern", None) allow_sudo = args.get(...
zzaacckkyy
identifier_name
commands.py
from telethon import events from var import Var from pathlib import Path from ub.config import Config import re, logging, inspect, sys, json, os from asyncio import create_subprocess_shell as asyncsubshell, subprocess as asyncsub from os import remove from time import gmtime, strftime from traceback import format_exc f...
else: import ub.events import sys import importlib from pathlib import Path path = Path(f"ub/modules/{shortname}.py") name = "ub.modules.{}".format(shortname) spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_sp...
name = "ub.modules.{}".format(shortname) spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) print("Successfully (re)imported "+shortname)
random_line_split
commands.py
from telethon import events from var import Var from pathlib import Path from ub.config import Config import re, logging, inspect, sys, json, os from asyncio import create_subprocess_shell as asyncsubshell, subprocess as asyncsub from os import remove from time import gmtime, strftime from traceback import format_exc f...
return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B" def time_formatter(milliseconds: int) -> str: seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ((str(days) ...
/= power raised_to_pow += 1
conditional_block
kuberuntime_sandbox.go
/* Copyright 2016 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, ...
(ctx context.Context, pod *v1.Pod, attempt uint32) (string, string, error) { podSandboxConfig, err := m.generatePodSandboxConfig(pod, attempt) if err != nil { message := fmt.Sprintf("Failed to generate sandbox config for pod %q: %v", format.Pod(pod), err) klog.ErrorS(err, "Failed to generate sandbox config for po...
createPodSandbox
identifier_name
kuberuntime_sandbox.go
/* Copyright 2016 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, ...
for idx := range containerPortMappings { port := containerPortMappings[idx] hostPort := int32(port.HostPort) containerPort := int32(port.ContainerPort) protocol := toRuntimeProtocol(port.Protocol) portMappings = append(portMappings, &runtimeapi.PortMapping{ HostIp: port.HostIP, HostPort...
portMappings := []*runtimeapi.PortMapping{} for _, c := range pod.Spec.Containers { containerPortMappings := kubecontainer.MakePortMappings(&c)
random_line_split
kuberuntime_sandbox.go
/* Copyright 2016 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, ...
return lc, nil } // generatePodSandboxWindowsConfig generates WindowsPodSandboxConfig from v1.Pod. // On Windows this will get called in addition to LinuxPodSandboxConfig because not all relevant fields have been added to // WindowsPodSandboxConfig at this time. func (m *kubeGenericRuntimeManager) generatePodSandbo...
{ sc := pod.Spec.SecurityContext if sc.RunAsUser != nil && runtime.GOOS != "windows" { lc.SecurityContext.RunAsUser = &runtimeapi.Int64Value{Value: int64(*sc.RunAsUser)} } if sc.RunAsGroup != nil && runtime.GOOS != "windows" { lc.SecurityContext.RunAsGroup = &runtimeapi.Int64Value{Value: int64(*sc.RunAsGr...
conditional_block
kuberuntime_sandbox.go
/* Copyright 2016 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, ...
// getKubeletSandboxes lists all (or just the running) sandboxes managed by kubelet. func (m *kubeGenericRuntimeManager) getKubeletSandboxes(ctx context.Context, all bool) ([]*runtimeapi.PodSandbox, error) { var filter *runtimeapi.PodSandboxFilter if !all { readyState := runtimeapi.PodSandboxState_SANDBOX_READY ...
{ wc := &runtimeapi.WindowsPodSandboxConfig{ SecurityContext: &runtimeapi.WindowsSandboxSecurityContext{}, } if utilfeature.DefaultFeatureGate.Enabled(features.WindowsHostNetwork) { wc.SecurityContext.NamespaceOptions = &runtimeapi.WindowsNamespaceOption{} if kubecontainer.IsHostNetworkPod(pod) { wc.Securi...
identifier_body
JsonLogparser.py
import os import argparse import json import numpy as np import matplotlib.pyplot as pp from threading import Thread def get_Directory(): print ("Select the log you would like to access by using -run=<number>\n") for i in range(len(dir_list)): directory = "Run " + str(i) + ": " + dir_list[i] ...
array = np.array(array) array = array.T if (all): for i in range(len(array)): pp.plot(array[i], label="Thruster " + str(i)) else: for i in indexes: try: pp.plot(array[i],label="Thruster " + str(i)) except: print ("\nUnab...
starttime = starttime + 1
random_line_split
JsonLogparser.py
import os import argparse import json import numpy as np import matplotlib.pyplot as pp from threading import Thread def get_Directory(): print ("Select the log you would like to access by using -run=<number>\n") for i in range(len(dir_list)): directory = "Run " + str(i) + ": " + dir_list[i] ...
if (args.dc): check =1 if (args.t): print("Time Format: DD_HH_MIN_SEC_USEC \nstart time: ",data[0]["last_update"]+ '\n' + "end time: ",data[len(data)-1]["last_update"] ) if (args.thruster): print1dim(data,'thrusters','Thrusters',fromtime,totime) printPl...
print1dim(data,'cameras','Camera',fromtime,totime)
conditional_block
JsonLogparser.py
import os import argparse import json import numpy as np import matplotlib.pyplot as pp from threading import Thread def get_Directory(): print ("Select the log you would like to access by using -run=<number>\n") for i in range(len(dir_list)): directory = "Run " + str(i) + ": " + dir_list[i] ...
(dic, key, key2, label, starttime, endtime): # helper function for nested keys i.e. 2 dimensional only # add similar helper function for more nested keys if need be print("\n" + label) while (starttime < endtime): print (dic[starttime]["last_update"]," : ",dic[starttime][key][key2]) sta...
print2dim
identifier_name
JsonLogparser.py
import os import argparse import json import numpy as np import matplotlib.pyplot as pp from threading import Thread def get_Directory(): print ("Select the log you would like to access by using -run=<number>\n") for i in range(len(dir_list)): directory = "Run " + str(i) + ": " + dir_list[i] ...
def print2dim(dic, key, key2, label, starttime, endtime): # helper function for nested keys i.e. 2 dimensional only # add similar helper function for more nested keys if need be print("\n" + label) while (starttime < endtime): print (dic[starttime]["last_update"]," : ",dic[starttime][key][ke...
print("\n"+label) while (starttime < endtime): print (dic[starttime]["last_update"]," : ",dic[starttime][key]) starttime = starttime + 1
identifier_body
mikes-modal.min.js
!function (a, b, c) { function d(a, c) { var d = b.createElement(a || "div"), e; for (e in c)d[e] = c[e]; return d } function e(a) { for (var b = 1, c = arguments.length; b < c; b++)a.appendChild(arguments[b]); return a } function f(a, b, c, d) { var...
return a.prototype.bindOpened = function () { var a = this; return this.modalBox.bind("open", function () { var b; return a.loading = $("<div id='loading-modal'></div>"), a.loading.appendTo("body").css({top: $(window).scrollTop() + 300 + "px"}), b = (new...
{ this.opts = e(this.opts, this), this.bindLoaded = e(this.bindLoaded, this), this.bindOpened = e(this.bindOpened, this), this.modalBox = a, this.bindOpened(), this.bindLoaded() }
identifier_body
mikes-modal.min.js
!function (a, b, c) { function d(a, c) { var d = b.createElement(a || "div"), e; for (e in c)d[e] = c[e]; return d } function e(a) { for (var b = 1, c = arguments.length; b < c; b++)a.appendChild(arguments[b]); return a } function f(a, b, c, d) { var...
width: 20, radius: 40, corners: 1, rotate: 19, color: "#fff", speed: 1.2, trail: 42, shadow: !1, hwaccel: !1, className: "spinner", zIndex: 2e9,...
}, a.prototype.opts = function () { return { lines: 9, length: 30,
random_line_split
mikes-modal.min.js
!function (a, b, c) { function d(a, c) { var d = b.createElement(a || "div"), e; for (e in c)d[e] = c[e]; return d } function e(a) { for (var b = 1, c = arguments.length; b < c; b++)a.appendChild(arguments[b]); return a } function f(a, b, c, d) { var...
(a) { this.addClose = e(this.addClose, this), this.marginLeft = e(this.marginLeft, this), this.marginTop = e(this.marginTop, this), this.imageMaxHeight = e(this.imageMaxHeight, this), this.imageMaxWidth = e(this.imageMaxWidth, this), this.triggerClose = e(this.triggerClose, this), this.imagePosition = e(thi...
b
identifier_name
metadb_test.go
package metadb import ( "database/sql" "errors" "fmt" "os" "testing" _ "github.com/mattn/go-sqlite3" ) const TestDBPath = "./test.sqlite" // TODO: Should unit tests be refactored so that all tests of methods attached // to Instance are coupled to the test for NewInstance itself? This could // entirely elimina...
// TestExists ensures that Instance.Exists is accurate. func TestExists(t *testing.T) { RunWithInstance(func(instance *Instance) { InsertFixtures(instance, []EntryFixture{ {Name: "foo", Value: "bar", ValueType: 3}, }) if instance.Exists("bar") { t.Error("Instance.Exists: got 'true' expected 'false'") ...
{ if _, err := NewInstance(nil); err == nil { t.Error("NewInstance: expected error with nil database handle") } RunWithDB(func(db *sql.DB) { if _, err := NewInstance(db); err != nil { t.Fatal("NewInstance: got error:\n", err) } }) }
identifier_body
metadb_test.go
package metadb import ( "database/sql" "errors" "fmt" "os" "testing" _ "github.com/mattn/go-sqlite3" ) const TestDBPath = "./test.sqlite" // TODO: Should unit tests be refactored so that all tests of methods attached // to Instance are coupled to the test for NewInstance itself? This could // entirely elimina...
if err := os.Remove(TestDBPath); err != nil { panic(err) } } // RunWithInstance runs a closure passing it an Instance. func RunWithInstance(fn func(*Instance)) { RunWithDB(func(db *sql.DB) { if instance, err := NewInstance(db); err != nil { panic(err) } else { fn(instance) } }) } // EntryFixture c...
{ panic(err) }
conditional_block
metadb_test.go
package metadb import ( "database/sql" "errors" "fmt" "os" "testing" _ "github.com/mattn/go-sqlite3" ) const TestDBPath = "./test.sqlite" // TODO: Should unit tests be refactored so that all tests of methods attached // to Instance are coupled to the test for NewInstance itself? This could // entirely elimina...
func RunWithInstance(fn func(*Instance)) { RunWithDB(func(db *sql.DB) { if instance, err := NewInstance(db); err != nil { panic(err) } else { fn(instance) } }) } // EntryFixture contains the basic data required for a metadata entry. type EntryFixture struct { Name string Value interface{} Val...
// RunWithInstance runs a closure passing it an Instance.
random_line_split
metadb_test.go
package metadb import ( "database/sql" "errors" "fmt" "os" "testing" _ "github.com/mattn/go-sqlite3" ) const TestDBPath = "./test.sqlite" // TODO: Should unit tests be refactored so that all tests of methods attached // to Instance are coupled to the test for NewInstance itself? This could // entirely elimina...
(t *testing.T) { RunWithInstance(func(instance *Instance) { InsertFixtures(instance, []EntryFixture{ {Name: "bool", Value: true, ValueType: 0}, {Name: "invalidBool", Value: "maybe", ValueType: 0}, {Name: "int", Value: 239, ValueType: 1}, {Name: "invalidInt", Value: "not a number", ValueType: 1}, {Name...
TestFromBlobString
identifier_name
memcache_zipserve.py
#!/usr/bin/env python # # Copyright 2009 Google 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 law or ...
class MemcachedZipHandler(webapp.RequestHandler): """Handles get requests for a given URL. Serves a GET request from a series of zip files. As files are served they are put into memcache, which is much faster than retreiving them from the zip source file again. It also uses considerably fewer CPU cycles. ...
"""Factory method to create a MemcachedZipHandler instance. Args: zip_files: A list of file names, or a list of lists of file name, first member of file mappings. See MemcachedZipHandler documentation for more information about using the list of lists format max_age: The maximum client-side c...
identifier_body
memcache_zipserve.py
#!/usr/bin/env python # # Copyright 2009 Google 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 law or ...
self.StoreOrUpdateInCache(name, resp_data) elif isValidIntl: # couldn't find the intl doc. Try to fall through to English. #logging.info(' Retrying with base uri...') return False else: logging.info(' Adding %s to negative cache, serving 404', name) ...
resp_data = self.GetFromStore(name) # IF we have the file, put it in the memcache # ELSE put it in the negative cache if resp_data is not None:
random_line_split
memcache_zipserve.py
#!/usr/bin/env python # # Copyright 2009 Google 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 law or ...
def RedirToIntl(self, name, intlString, langName): """Redirect an incoming request to the appropriate intl uri. For non-en langName, builds the intl/lang string from a base (en) string and redirects (302) the request to look for a version of the file in langName. For en langName, simply ...
return name
conditional_block
memcache_zipserve.py
#!/usr/bin/env python # # Copyright 2009 Google 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 law or ...
(self, name, langName, isValidIntl, resetLangCookie): """Process the url and form a response, if appropriate. Attempts to retrieve the requested file (name) from cache, negative cache, or store (zip) and form the response. For intl requests that are not found (in the localized tree), ...
CreateResponse
identifier_name
chart.js
google.charts.load('current', { packages: ['corechart'] }); //global variable for storing the ids of articles currently shown in author analytics page var articlesShown = []; var allArticleTitles = []; var allArticletitlesWithRevisions = []; //chart otpions var options = { 'fontName':'Avenir', 'backgroundColor': ...
//clears the .active class from the menu bar function resetMenuBar() { $('#Overview').removeClass("active"); $('#ArticleAnalytics').removeClass("active"); $('#AuthorAnalytics').removeClass("active"); } /****************** LOAD THE CHART DATA *******************/ function drawPie(where) { console.log(wher...
{ $('#main').empty(); $('#main').load('views/authorAnalytics.html', null, function () { $('#authorSearchButton').click(function () { getAuthorArticleList(); }) }); }
identifier_body
chart.js
google.charts.load('current', { packages: ['corechart'] }); //global variable for storing the ids of articles currently shown in author analytics page var articlesShown = []; var allArticleTitles = []; var allArticletitlesWithRevisions = []; //chart otpions var options = { 'fontName':'Avenir', 'backgroundColor': ...
$('#authorSearchButton').click(function () { getAuthorArticleList(); }) }); } //clears the .active class from the menu bar function resetMenuBar() { $('#Overview').removeClass("active"); $('#ArticleAnalytics').removeClass("active"); $('#AuthorAnalytics').removeClass("active"); } /****************** LO...
} function getAuthorAnalyticsPage() { $('#main').empty(); $('#main').load('views/authorAnalytics.html', null, function () {
random_line_split