anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
def ultratio(chrlength, uniqueratio, chrtotalreads, frcount):
ultratio = chrlength * uniqueratio / (chrtotalreads - frcount)
return ultratio | ultraio = chrlength uniqueratio / chr_total_reads |
def setPlotTitle(self):
plot_title = self.input_plot_title.text()
if plot_title:
self.plot_title = self.input_plot_title.text()
# Redraw the plot with given title
if not self.plot_inverted:
self.drawPlot(self.data_x_axis, self.data_y_axis, self.label_x... | Sets the plot title when the button is clicked with the value present in the title input box |
def __init__(self, router, uri=None, host='', port=8082, simplex=False):
super(EventRelayHTTPC, self).__init__(uri)
self._router = router
self._queue = Queue()
self._event = threading.Event()
self._closing = False
self._queueEvent = threading.Event()
self._si... | Initialize a new HTTP client event passing object An HTTP client is associated with an existing event router, and sends all messages received from that router to the HTTP connection, and forwards all messages received from the HTTP connection to the router. Interaction with the indicated EventRouter object takes place ... |
def reduce2lat_seasonal( mv, seasons=seasonsyr, vid=None ):
if vid==None:
vid = 'reduced_'+mv.id
# Note that the averager function returns a variable with meaningless id.
# The climatology function returns the same id as mv, which we also don't want.
# The slicers in time.py require getBounds()... | as reduce2lat, but data is used only for time restricted to the specified season. The season is specified as an object of type cdutil.ties.Seasons, and defaults to the whole year. The returned variable will still have a time axis, with one value per season specified. |
def test_process_packet(self):
packet = {'a': 7}
self.assertEqual(self.foo.a, 4)
self.handler.process_packet(packet)
self.assertEqual(self.foo.a, 7)
packet = {'b': 9, 'a': 20}
self.handler.process_packet(packet)
self.assertEqual(self.foo.a, 20)
self.assert... | A test to see if the packets get processed correctly. |
def href(self, request) -> str:
raise NotImplementedError() | Compute and return the link. |
def donor_participant(self, donor_participant: Object):
self._donor_participant = donor_participant | Sets the donor_participant of this AllOfCreateClaimResponseClaim. |
def test_private(self):
content = self.unique()
self.assertViewBehavior(
{"cache_control_public": False, "get": content},
status_code=200,
content=content,
headers_exact={"Cache-Control": "private"}) | Check that the private cache control header is set on the resopnse. |
def to_dict(self, exclusions=[]) -> dict:
dump = {}
for (name, value) in self.__dict__.items():
if name == "data" and isinstance(value, pd.DataFrame):
df_dict = value.to_dict(orient="split")
dump[encoder(name)] = encoder(df_dict)
else:
... | Exports the data for storage in a json file. The encoding to a json serialisable form has to be defined, it is not applied as an encoder to the json funciton. Returns |
def make_move(self, move, player, board):
#nBoard = board.copy()
board[move] = player
for d in core.DIRECTIONS:
if self.find_bracket(move, player, board, d)!=None:
self.make_flips(move, player, board, d)
return board | Update the board to reflect the move by the specified player. |
def describe_sharding_network_address_with_options(
self,
request: dds_20151201_models.DescribeShardingNetworkAddressRequest,
runtime: util_models.RuntimeOptions,
) -> dds_20151201_models.DescribeShardingNetworkAddressResponse:
UtilClient.validate_model(request)
query = {}
... | This operation supports sharded cluster instances only. |
def get_subcommand_query(query_str: str) -> Optional[SubcommandQuery]:
if not query_str:
return None
# spilt:
# "subcommand_name rest of query" -> ["subcommand_name", "rest of query""]
query_parts = query_str.strip().split(None, maxsplit=1)
if len(query_parts) < 2:
query_str = ""
... | Determine whether current query is of a subcommand. If so first returned the corresponding SubcommandQeury object. |
def serialize(self) -> bytes:
headers = "\r\n".join(
f"{header}: {value}" for header, value in self.headers.items()
)
return (
f"HTTP/1.0 {self.status} {STATUS_CODES[self.status]}\r\n"
f"{headers}\r\n"
"\r\n"
).encode("utf-8") | Returns HTTP response as raw bytes |
def generate_dataset(
datasets, networks, parents, mode='train', mean=None,
verbose=1, **params):
# Parameters
classes = params.setdefault('classes', [-1,0,1])
data_type = params.setdefault('data_type', 'spikes')
thres = params.setdefault('thres', 150.0)
target = params.setdefault('target',... | Generates a balanced set of training examples from one or more datasets. |
def filter_string(self):
logger.info("Information Gathering Finished!")
pattern_street = re.compile(r'[A-Za-z]+\s?\w+(?=\s[Nn]o\s\d+$) |'
r' [A-Za-z]+\s?\w+\s?[A-Za-z]+\s?[A-Za-z]+',
re.X) # street pattern
match_street = p... | Given the input string, tries to separate them into "street" & "house number" variables |
def makeinputstring(variabel):
if type(variabel) == int:
return str(variabel)
elif type(variabel) == float:
return str(int(float(variabel)))
else:
return str(variabel) | takes input and returns a string |
def UpdateVariable(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Updates an existing variable with a new value. |
def test_calculate_deuces(self):
board = ['4h', '5h', '8h', '7h', '9c']
hand = ['2s', '3s']
deuces = calculate_deuces(board, hand)
self.assertEqual(deuces[0], 7414)
self.assertEqual(deuces[1], 'High Card') | Method for getting the deuces score |
def optimizermt(self,server_,port_):
if isinstance(server_,unicode):
server_ = server_.encode("utf-8",errors="replace")
if isinstance(port_,unicode):
port_ = port_.encode("utf-8",errors="replace")
trmcode_ = ctypes.c_int32()
res = __library__.MSK_XX_optimizermt(self.__nativep,server_,port_,c... | Offload the optimization task to a solver server. optimizermt(self,server_,port_) |
def main(url, ip):
doc = {'url' : url}
#get the whois and domain info
print('[*] Getting whois')
doc = get_whois(doc)
#only continue checking stuff if we can actually resolve the address
if doc['ip'] != '':
#get ssl information if available
print('[*] Get certificate informatio... | this function will just combine all of the logic to create our doc and post to elasticsearch |
def test_sample_is_attached_to_patient(self):
self.assertEqual(self.test_patient.sample_set.all()[0], self.test_sample) | test that the many_to_one relationship is in place |
def has_finished(): | Return True if this request is considered finished, which is, when |
def calculate_ddct(self, baseline_time=0):
if baseline_time == 0:
baseline = self.baseline_data['dct'][0]
elif baseline_time == 96:
baseline = self.baseline_data['dct'][96]
elif baseline_time == 'average':
baseline = (self.baseline_data['dct'][0] + self.bas... | For the time being this is TGF/baseline and control/baseline The choice of 0 or 96 will make a difference |
def set_params2D(ima, p, xform = "xform.align2d"):
t = Transform({"type":"2D","alpha":p[0],"tx":p[1],"ty":p[2],"mirror":p[3],"scale":p[4]})
ima.set_attr(xform, t) | set 2D alignment parameters in the header alpha tx ty mirror scale |
def test_get_sets_by_category():
group_categories = get_sets_by_category(mb, "Group")
assert len(group_categories) == 5 | Ensure this function returns the correct number of entities with the specified tag. |
def create_timestamp(self):
return self._create_ts | the integer timestamp when this task is created. |
def _ensure_es_index(self, index):
if not self.elasticsearch.indices.exists(index):
try:
self.elasticsearch.indices.create(index=index)
except TransportError as error_msg:
self.logger.error(str(error_msg.error))
return False
sel... | Used internally when writing to elasticsearch to ensure a given index exists. |
def test_fk_id_in_filter(query):
john_doe = Reporter.objects.create(
first_name="John", last_name="Doe", email="john@doe.com"
)
jean_bon = Reporter.objects.create(
first_name="Jean", last_name="Bon", email="jean@bon.com"
)
sara_croche = Reporter.objects.create(
first_name="Sa... | Test in filter on an foreign key relationship. |
def __init__(self, parent=None):
super(ProgressDlg, self).__init__(parent)
self.setupUi(self) | Constructor parent reference to the parent widget QWidget |
def test_grdfilter_file_in_file_out():
with GMTTempFile(suffix=".nc") as tmpfile:
result = grdfilter(
"@earth_relief_01d",
outgrid=tmpfile.name,
region=[0, 180, 0, 90],
filter="g600",
distance="4",
)
assert result is None # return ... | grdfilter an input grid file, and output to a grid file. |
def insert(self, key, data):
debug.printMsg('Insert for "' + key + '" With data: ' + str(data) )
# if there is no root node
if not self.root:
debug.printMsg("No root was found, create one")
self.root = Node(key, data)
else:
debug.printMsg("Root was fou... | This function will insert data into the BST using a log_2(n) algorithm |
def generate_test_settings(tmpdir, dataset):
# When `tmpdir` is a path convert it to a string
if isinstance(tmpdir, py._path.local.LocalPath):
tmpdir = str(tmpdir)
test_settings = {
'datasets': {
'mnist': {
'train': {
'images... | Temporarily overwrite the settings with test settings. This allows to use test datasets for testing. |
def __repr__(self):
return str(self.data) | Convert Node to string |
def test_badyvaluewithtuple(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, 2, (1, 2), 3)
self.assertEqual(str(e.exception), 'y must be an integer') | This function tests for bad y value with tuple |
def greedy_initial(self):
sol = [] # [[0;2;5;0;4;6;0],[],...]
sol_veh_type = [] # corresponding vehicle type for the solution
route_way_time = []
to_vist = [i+1 for i in range(store_num - 1)] # [1,5,8,...]
itr = 0
while len(to_vist) > 0 and itr < 500:
... | Generate an initial solution based on the Timeoriented Nearestneighbor heuristic proposed by Solomon. |
def __init__(
self,
feature_map: FeatureMap,
weight: Union[Parameter, Tensor],
bias_module: Optional[Module] = None,
input_transform: Optional[TInputTransform] = None,
output_transform: Optional[TOutputTransform] = None,
):
super().__init__()
self.feat... | r"""Initializes a GeneralizedLinearPath instance. |
def update(self, current, values=None):
values = values or []
for k, v in values:
if k not in self._values_order:
self._values_order.append(k)
if k not in self.stateful_metrics:
if k not in self._values:
self._values[k] = [
... | Updates the progress bar. |
def test_create_data_lookup_error(self):
with self.assertRaises(LookupError):
_ = create_data({"name": "fake_data"}) | Checks if create date raises lookup error when name is incorrect. |
def check_user_credentials(token, auth_url='https://accounts.okeanos.grnet.gr'
'/identity/v2.0'):
logging.info(' Test the credentials')
try:
auth = AstakosClient(auth_url, token)
auth.authenticate()
logging.info(' Authentication verified')
return AUTHENTICAT... | Identity,Account/Astakos. Test ~okeanos authentication credentials |
async def process_prune(
channel, amount, user_id: int, ctx=None, inter=None, allowed_mentions=None
):
user = await User.get(user_id)
if amount not in range(PRUNE_MIN, PRUNE_MAX):
return await send_message(
PRUNE_MIN,
PRUNE_MAX,
key="not_in_range",
use... | Process the prune/clear command. |
def on_mouse_press(self, x, y, button, modifiers):
menu: Menu = self.get_menu_for_display()
menu_click_x, menu_click_y = self.get_menu_click(menu, x, y)
if button == arcade.MOUSE_BUTTON_LEFT:
if menu:
menu.button_list.check_mouse_press_for_buttons(
... | Called when the user presses a mouse button. |
def reffile(self):
return os.path.join(self.__folder, self.__name + '.ref') | Returns complete path to reference file. |
def __init__(self, trainer, logger_dir, experiment_name):
if not os.path.isdir(logger_dir):
raise IOError("{} is not a valid directory".format(logger_dir))
super().__init__(trainer)
experiment_dir = os.path.join(logger_dir, experiment_name)
os.mkdir(experiment_dir)
s... | Initializes the Tensorboard writer |
def get_data(file_name):
csv_file = open(file_name, 'rb')
train_content = csv.reader(csv_file)
# ignore header
train_content.next()
# preprocessing functions for each column index
# Several preprocessing can be defined for each column.
# A new variable is associated to EACH preprocessing f... | Get the data from the dataset and apply preprocessing to extract hours. |
def render(self, mode: str = 'human', steps_per_sec: int = 2,
debug_text: Optional[str] = None):
if mode not in BombermanEnv.metadata['render.modes']:
raise ValueError('Invalid render mode')
self.renderer.render(mode, steps_per_sec, debug_text) | Renders or prints the step. |
def expand_paths(__file__, paths_with_globs):
if isinstance(paths_with_globs, str):
return expand_path(__file__, paths_with_globs)
else:
expanded_globs = [
expand_path(__file__, path) for path in paths_with_globs
]
# Flatten
return list(itertools.chain.from_it... | Returns full paths for a series relative paths with globs |
def envs(self) -> Optional[Sequence['outputs.CSIPowerStoreSpecDriverSideCarsEnvs']]:
return pulumi.get(self, "envs") | Envs is the set of environment variables for the container |
def compute_min_refills(distance: int, tank: int, stops: List[int]):
location: int = 0
n_stops = 0
last_stop = 0
max_drive = location + tank
while max_drive < distance:
counter = 0
# Handle the case that stops are depleted before we reach distance
if len(stops) == 0:
... | Calculate the min number of refills to reach 'distance'. You start with a full tank. |
def _find_unused_static_warnings(filename, lines, ast_list):
static_declarations = {
node.name: node
for node in ast_list
if (isinstance(node, ast.VariableDeclaration) and
'static' in node.type.modifiers)
}
def find_variables_use(body):
for child in body:
... | Warn about unused static variables. |
def test_code009(self, *test_code_args, **test_code_kwargs):
print("This is test_code009 from TestDefinition #", self.ID, ", test case #", self.test_case_ID, sep='') | Test case code number 009. |
def common():
full_song = ""
albums = simple_album_list()
for album in albums:
songs = simple_songs_list(album)
for song in songs:
full_song += str(song_lyrics(song))
split_lyrics = full_song.lower().split()
counter = collections.Counter(split_lyrics)
most_wo... | This function makes list of the top 50 commonest words of all songs |
def assertNoRepeatGuids(context, posts):
guids = [p['guid'] for p in posts]
context.assertTrue(len(set(guids)) == len(posts), "Some guids repeated") | Takes response.data and confirms no repeated guids (No repeated posts) |
def apply_style(self, app):
darkPalette = QPalette()
# base
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Light, QColor(180, 180, 180))
darkPalette.setColor(QPalet... | Apply Dark Theme to the Qt application instance. |
def main():
browser = initialize()
process_directory(browser, "data")
browser.close() | Run the main functionality of this script. |
def parse_pbobject(source, pb_class):
if isinstance(source, str):
return open_pbobject(source, pb_class)
elif isinstance(source, bytes):
pb_object = pb_class()
pb_object.ParseFromString(source)
return pb_object
else:
logging.error(f'cannot parse type {type(source)}') | Like open_pboject but source can be a path or a bytestring |
def init_timeparams(options):
params = OrderedDict()
# for time prediction
'''
W_t = np.zeros(options['dim_proj'])
params['W_t'] = W_t.astype(config.floatX)
b_t = np.zeros(1)
params['b_t'] = b_t.astype(config.floatX)
'''
W_t = init_params_weight(options['dim_proj'], 1)
params['W_... | Initializes values of shared variables. |
def __duplicate_m2o_fields(self, duplicate):
fields = set()
for f in self._meta.concrete_fields:
if f.many_to_one:
if any(
[
f.name in self._clone_m2o_or_o2m_fields,
self._clone_excluded_m2o_or_o2m_fields
... | Duplicate many to one fields. |
def init(starting_position, steering_noise, distance_noise, sonar_noise,
measurement_noise, speed, turning_speed, gps_delay, execution_cpu_time_limit):
raise NotImplementedError() | starting_position (x,y) tuple representing current_position |
async def on_building_construction_started(self, unit: Unit): | Override this in your bot class. This function is called when a building construction has started. |
def rec_freq(markers):
keys = list(markers.keys())
rf_pairs = {}
for i in range(len(markers)):
for j in range(i + 1, len(markers)):
m1 = markers[keys[i]][0]
m2 = markers[keys[j]][0]
tot_len = 0
score = 0
if len(m1) != len(m2):
... | Calculates recombination frequency between all combinations of two markers. |
async def link(self, ctx):
if not is_linked(ctx.author.id):
token = str(uuid.uuid4())
valid_until = int((datetime.utcnow() + timedelta(days=1)).timestamp())
add_token(ctx.author.display_name, ctx.author.id, token, valid_until, str(ctx.author.avatar_url))
web_base_... | Link a spotify account to the bot. |
def run_animation(self, clip_name, fragment, zoom=True, pad=3, interval=100):
preprocessor = self.process_data(clip_name)
period_person_division = preprocessor.period_person_division
running_person_identifiers = preprocessor.get_running_person_identifiers()
running_fragments = preproce... | Complete pipeline to process and plot data. |
def _evalContext(self):
def xor(*args):
return sum(args) == 1
def neg(result):
return not result
context = {
'xor': xor,
'neg': neg
}
return context | Supported functions for the user in boolean equations. |
def getUserName(self, response):
sel = response.selector
blackTr = sel.xpath(u"//table[contains(@class,'black_table')]/tr[position()>1]//p[contains(text(),'真实姓名')]/a/@href").extract()
url = 'http://www.ppdai.com'
urls = [url+i for i in blackTr]
redis_key = 'ppai_blacklist_redis_s... | get user name from xtml |
def __init__(self, **kwargs):
kwc=kwargs.copy()
AbstractComplexParameterType.__init__(self, value_class='ArrayValue', **kwc)
self._gen_template_attrs() | kwargs Additional keyword arguments are copied and the copy is passed up to AbstractComplexParameterType; see documentation for that class for details |
def get_all_emails_it(auth, user_id, folder_id='AllItems', pages_limit=None, pages_size=50, **kwargs):
i = 0
args_dict = dict(kwargs, top=pages_size, skip=pages_size * i)
curr_emails = get_emails(auth, user_id, folder_id, **args_dict)
while len(curr_emails) != 0:
yield curr_emails
... | iterator which goes through all the pages to find all the emails |
def get_controller(equipment, accessmethod, logfile=None):
path = _CONTROLLERMAP[accessmethod]
constructor = module.get_object(path)
return constructor(equipment, logfile) | Return controller instance that is based on the equipment role. |
def getServiceIdsForDate(self, dt, exclude0000=True):
dayDict = {1:"monday", 2:"tuesday", 3:"wednesday", 4:"thursday",
5:"friday", 6:"saturday", 7:"sunday"}
sqlQuery = "select service_id from calendar" \
+ " where {} = 1".format(dayDict[dt.isoweekday()]) \
+ " and... | Return list of service_ids that match a given datetime |
def xd_element(name):
try:
name = name[:2]
except:
pass
try:
covalence_radius[name]
except:
name = name[0]
return name | Return the element of an atom as defined in it's label. |
def test_edit_profile(self):
LOGGER.debug("Test GET /rango/edit/ for anon user")
anon_edit_response = self.client.get('/rango/edit/')
# redirected to login page
self.assertEquals(302, anon_edit_response.status_code)
self.assertRedirects(anon_edit_response, "http://testse... | Test to see if profile for user1 can be edited anon and logged in |
def _get_bios_hash_password(self, bios_password):
request_headers = {}
if bios_password:
bios_password_hash = hashlib.sha256((bios_password.encode()).
hexdigest().upper())
request_headers['X-HPRESTFULAPI-AuthToken'] = bios_password_... | Get the hashed BIOS password. |
def collect_attachments(self, paths_or_urls: Iterable[str]) -> List[Tuple[str, str, str, bytes]]:
attachments = []
same_content = [] # type: List[bytes]
for src in paths_or_urls:
try:
content = self.load_file(src)
except ImageNotFound as err:
... | Collect attachment contents from paths or urls. |
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False | Returns True if value can be converted to float, otherwise returns False.\n |
def parser_weight(cls, data_dict):
# get user's answer
context = {}
actual_weight = data_dict.get("actual_weight")
goal_weight = data_dict.get("weight_goal")
# if not valid
# create an error message
if float(goal_weight) >= float(actual_weight):
text ... | check if the user's answer is valid |
def backward(self,distance):
assert (type(distance) in [int, float]), "parameter distance:%s is not a valid number" % `distance`
self._turtle.backward(distance) | Moves the turtle backward by the given amount. |
def runtime_error(self, error: 'LoxRuntimeError'):
output = f'{error.get_message()}{os.linesep}[line {error.token.line}]'
print(output, file=sys.stderr)
self.had_runtime_error = False | report a runtime error |
def linearFit(title, threadCounts, bestTimes, independentVar, unit):
outputHtml("<h1>" + title + "</h1>")
results = {}
impls = sorted(list(bestTimes.keys()), key=cmp_to_key(compareFn))
outputHtml('<table border="1">')
if independentVar[-1] == "s":
independentVar = independentVar[:-1]
out... | Print info on a linear fit |
def cosine_decay_with_warmup(global_step,
learning_rate_base,
total_steps,
warmup_learning_rate=0.0,
warmup_steps=0,
hold_base_rate_steps=0):
if total_steps < warmup_steps... | Cosine decay schedule with warm up period. |
def start(self, wait_for_port=False):
for c in self.openstack_endpoints.values():
c.compute = self.compute
c.manage = self.manage
c.server_thread = threading.Thread(target=c._start_flask, args=())
c.server_thread.daemon = True
c.server_thread.name = c.... | Start all connected OpenStack endpoints that are connected to this API endpoint. |
async def no_sleep_coro():
pass | Creates a coroutine that does nothing for when no sleep is needed. |
def process_time_string(timestr):
timestr = timestr.strip()
toks = timestr.split('+')
timeslices = []
for t in toks:
tm = t.strip()
mobj = re.search('\\*', tm)
if mobj == None:
timeslices += [int(tm)]
else:
tms = tm.split('*')
timeslice... | This function processes the timestring from PSMC and converts this to list of time slice lengths |
def main(*args):
#
# Use argparse to handle parsing the command line arguments.
# https://docs.python.org/3/library/argparse.html
#
parser = argparse.ArgumentParser(description='Animate an epidemic')
parser.add_argument('--size', metavar='N', type=int, default=50,
help=... | Command line entry point. $ python runsim.py show animation on screen $ python runsim.py file=video.mp4 save animation to video $ python runsim.py plot show plot on screen $ python runsim.py plot file=plot.pdf save plot to pdf |
def handle(self, message: Message) -> None:
self.handled_message = message
envelope = Envelope(
to=message.counterparty,
sender=self.context.agent_address,
protocol_id=TwoPartyNegotiationMessage.protocol_id,
message=self.encoded_message_2_in_bytes,
... | Implement the reaction to a message. |
def entrench_word(self, cloud, paradigms, informativity, categorization,
unique_base):
# Entrench within the WordForm's own cloud. Iterate over positions in
# the WordForm (up to three Segments).
for pos, seg in enumerate(self.segments):
if pos < 3:
... | Entrench at the level of the WordForm. |
def putsnxslice(self,whichsol_,first_,last_,snx_):
_snx_minlength = ((last_) - (first_))
if ((last_) - (first_)) > 0 and snx_ is not None and len(snx_) != ((last_) - (first_)):
raise ValueError("Array argument snx is not long enough: Is %d, expected %d" % (len(snx_),((last_) - (first_))))
if snx_ is N... | Sets a slice of the snx vector for a solution. putsnxslice(self,whichsol_,first_,last_,snx_) |
def message():
if request.method == 'POST':
db.log_msg(request.form['text'], request.cookies.get('username'))
return db.get_all_messages() | Route for posting messages or getting the prerendered html |
def forward_backward(self, data_batch):
total_feature, total_label = self.forward(data_batch, is_train=True)
self.backward_all(total_feature, total_label) | A convenient function that calls both ``forward`` and ``backward``. |
def view():
# retrieve child and dorm parents records from database
children = Child.query.filter_by().all()
parents = Parent.query.filter_by().all()
return render_template('view.html', children=children, parents=parents) | Render the website's add page. |
def main(sys_argv: List[str] = None, should_setup_logging: bool = True) -> int:
if sys_argv is None:
sys_argv = sys.argv[1:]
args = parse_args(sys_argv)
if args is not None and args.command == 'gui':
gui_args = [arg for arg in sys_argv if arg != 'gui']
import stm32pio.gui.app as g... | Entry point to the CLI edition of application. Since this is a highestorder wrapper, it can be used to |
def isLastPage(page_num, count_of_combos, per_page):
if count_of_combos <= (page_num * per_page):
return True
return False | Return True if this is the last page in the pagination |
def flow(self, batch_size=32, output='both', crops=0):
while True:
for dataset in self.input_sets:
X = self.training_set['input/'+dataset]
y = self.training_set['target/'+dataset]
y_seg = self.training_set['seg_map/'+dataset]
for i in ... | Generate outputs from a noncompact TrainingSet to use with Keras' 'fit_generator' function. If 'n_crops' is nonzero, the Iterator crops n_crops 20x20 regions from each image before feeding them. |
def __init__(self, ego_name: str, ego_id: int = None, last_time: int = 0,
min_pub_date: int = None):
self.ego_name = ego_name
self.publications = {}
self.min_pub_date = min_pub_date
super(CoauthorshipNamedEgoNetwork, self).__init__(ego_id, last_time) | Create a new CoauthorshipEgoNetwork by specifying the id and the name of the ego. |
def registration_allowed(self, request):
return getattr(settings, 'REGISTRATION_OPEN', True) | Indicate whether account registration is currently permitted, based on the value of the setting ``REGISTRATION_OPEN``. This |
def like(
self, other: Any, escape: Optional[str] = None
) -> ColumnOperators:
return self.operate(like_op, other, escape=escape) | r"""Implement the ``like`` operator. |
def to_m3u_track(record: Dict[str, str]) -> str:
location = normalize(unquote(record.get("Location")))
# m3u duration in seconds, not ms
duration = int(record.get("Total Time")) // 1000
name = normalize(unquote(record.get("Name")))
artist = normalize(unquote(
record.get("Artist") or
... | Converts a single track record into m3u format. Need the normalization to fix the way Apple handles e.g. combining diacriticals. |
def load(extended=False):
_fetch_large()
if extended:
return _load(cache_experiment_extended, _parse_experiment)
else:
return _load(cache_experiment, _parse_experiment) | Load the EEG data, which is a particular split of the first trial of subject 337 in the large training data. |
def load_vectors(vec_file, info_file, buckets):
vectors = np.load(vec_file)
with open(info_file, 'r') as f:
info = json.load(f)
if len(info['sequence_id_list']) != len(info['instance_id_list']):
raise ValueError('Invalid info file: len(info[''sequence_id_list'']) should be equal to len(info... | load data into buckets. |
def save_msg(self, msg: TrafficSigns):
if msg.sub_messages:
tf = self.get_transformation(
"sim_world",
msg.header.frame_id,
msg.sub_messages[0].header.stamp,
timeout=rospy.Duration(0.1),
)
if tf is not None:
... | Add a message to the signs. |
def same_type(one, two):
return isinstance(one, type(two)) | Check if two things have the same type. |
def nfvi_cold_migrate_confirm_instance(instance_uuid, callback, context=None):
if context is None:
cmd_id = _compute_plugin.invoke_plugin_expediate(
'cold_migrate_confirm_instance', instance_uuid, context,
callback=callback)
else:
cmd_id = _compute_plugin.invoke_plugin(
... | Cold migrate confirm an instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.