content
stringlengths
27
928k
path
stringlengths
4
230
size
int64
27
928k
nl_text
stringlengths
21
396k
nl_size
int64
21
396k
nl_language
stringlengths
2
3
nl_language_score
float64
0.04
1
INPUTPATH = "input.txt" #INPUTPATH = "input-test.txt" with open(INPUTPATH) as ifile: raw = ifile.read() from typing import Tuple def line_to_pos(line: str) -> Tuple[int, ...]: filtered = "".join(c for c in line if c.isdigit() or c in {"-", ","}) return tuple(map(int, filtered.split(","))) starts = tuple(zip(*map(lin...
day12/main.py
1,554
INPUTPATH = "input-test.txt" Get some rest, buddy. :3 Up for a run? >:3c
72
en
0.866252
#!/usr/bin/env python # -*- coding: utf-8 -*- import cplotting as cplot S={2+2j, 3+2j, 1.75+1j, 2+1j, 2.25+1j, 2.5+1j, 2.75+1j, 3+1j, 3.25+1j} cplot.plot({1+2j+z for z in S},4) cplot.show()
python/chap_1/1.4.3.py
193
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=10) evaluation = dict(interval=100, metric='mAP') optimizer = dict( type='Adam', lr=0.0015, ) optimizer_config = dict(grad_clip=None) # learning policy lr_config...
configs/bottom_up/hrnet/coco/hrnet_w32_coco_512x512.py
5,290
learning policy dict(type='TensorboardLoggerHook') model settings
65
en
0.658911
import streamlit as st import warnings try: from streamlit_terran_timeline import terran_timeline, generate_timeline except ImportError: warnings.warn( "Failed to load terran_timeline from streamlit_terran_timeline. " "Please run 'pip install streamlit_terran_timeline' or " "'pip insta...
streamlit_terran_timeline/examples/youtube.py
1,795
Ask the user to input a video link or path and show the video below Show the actual faces timeline chart
104
en
0.554019
# from blazingsql import BlazingContext from Configuration import ExecutionMode from Configuration import Settings as Settings # from dask.distributed import Client from DataBase import createSchema as createSchema # from EndToEndTests import countDistincTest from EndToEndTests import ( GroupByWitoutAggregations,...
tests/BlazingSQLTest/EndToEndTests/allE2ETest.py
11,669
from blazingsql import BlazingContext from dask.distributed import Client from EndToEndTests import countDistincTest loadDataTest, timestampdiffTest, Create Table Drill ----------------------------------------- Create Table Spark ------------------------------------------------- Create Context For BlazingSQL if targetT...
1,189
en
0.668666
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: geometry.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protob...
pygazebo/msg/geometry_pb2.py
10,559
Generated protocol buffer code. -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: geometry.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:gazebo.msgs.Geometry) @@protoc_insertion_point(module_scope)
267
en
0.539253
from aws_cdk import ( core, aws_iam as iam, aws_kinesis as kinesis, aws_kinesisfirehose as kinesisfirehose ) class Lab07Stack(core.Stack): def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your st...
Lab07/lab07/lab07_stack.py
5,425
The code that defines your stack goes here s3桶信息 压缩设置,老方案:gzip,新方案待定 格式转换,是否转换为orc,parquet,默认无 是否加密:默认无 错误输出前缀
110
zh
0.696952
"""Main app/routing file for TwitOff""" from os import getenv from flask import Flask, render_template, request from twitoff.twitter import add_or_update_user from twitoff.models import DB, User, MIGRATE from twitoff.predict import predict_user def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_D...
twitoff/app.py
2,581
Main app/routing file for TwitOff TODO - make rest of application SQL equivalent = "SELECT * FROM user;" conditinoal that prevents same user comparison prediction return zero or one depending upon user returns rendered template with dynamic message
250
en
0.684052
#------------------------------------------------------------------------- # Copyright (c) Microsoft. All rights reserved. # # 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.apa...
prototype/api/FlaskApp/FlaskApp/azure_components/azure/mgmt/common/filters.py
4,199
------------------------------------------------------------------------- Copyright (c) Microsoft. All rights reserved. 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/licens...
714
en
0.765323
import os import sys from pathlib import Path from typing import List, Optional, Tuple import i18n import requests import yaml from . import config, frozen_utils, os_utils, print_utils # The URL to the docker-compose.yml BRAINFRAME_DOCKER_COMPOSE_URL = "https://{subdomain}aotu.ai/releases/brainframe/{version}/docker...
brainframe/cli/docker_compose.py
4,916
Fails if the user does not have permissions to interact with Docker Fails if the user does not have write access to the given path. :return: The latest available version in the format "vX.Y.Z" The URL to the docker-compose.yml The URL to the latest tag, which is just a file containing the latest version as a string R...
866
en
0.907978
#!/usr/bin/env python3 def main(): pass if __name__ == '__main__': main()
.vim/template/python/base-atcoder.py
86
!/usr/bin/env python3
21
fr
0.448822
# author : 陈熙 # encoding:utf-8 from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib class SendEmail: sender = 'atomuser@139.com'#'ccu_queryresul@139.com' msg = MIMEMultipart('alternative') msg['Subject'] = Header("长春大...
ccuemail.py
1,100
author : 陈熙 encoding:utf-8'ccu_queryresul@139.com'
50
en
0.439844
# This file is part of datacube-ows, part of the Open Data Cube project. # See https://opendatacube.org for more information. # # Copyright (c) 2017-2021 OWS Contributors # SPDX-License-Identifier: Apache-2.0 """Test update ranges on DB using Click testing https://click.palletsprojects.com/en/7.x/testing/ """ from data...
integration_tests/test_update_ranges.py
2,111
Test update ranges on DB using Click testing https://click.palletsprojects.com/en/7.x/testing/ This file is part of datacube-ows, part of the Open Data Cube project. See https://opendatacube.org for more information. Copyright (c) 2017-2021 OWS Contributors SPDX-License-Identifier: Apache-2.0
295
en
0.575564
# # Copyright (c) 2021 Software AG, Darmstadt, Germany and/or its licensors # # SPDX-License-Identifier: Apache-2.0 # # 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.apach...
c8ylp/cli/core.py
21,548
CLI Logger Exit codes Local proxy context Remote access connection data Configure logger Args: path (pathlib.Path): Path where the persistent logger should write to. verbose (bool, optional): Use verbose logging. Defaults to False. Returns: logging.Logger: Created logger Create Cumulocity client and promp...
4,785
en
0.75027
import pandas as pd import numpy as np from numpy.linalg import inv def get_ffme_returns(): """ Load the Fama-French Dataset for the returns of the Top and Bottom Deciles by MarketCap """ me_m = pd.read_csv("data/Portfolios_Formed_on_ME_monthly_EW.csv", header=0, index_col=0, na_...
kit.py
30,248
Annualizes a set of returns We should infer the periods per year but that is currently left as an exercise to the reader :-) Annualizes the vol of a set of returns We should infer the periods per year but that is currently left as an exercise to the reader :-) Backtests a given weighting scheme, given some parameters: ...
9,703
en
0.778277
""" _SubscriptionList_ Module with data structures to handle PhEDEx subscriptions in bulk. """ import logging from WMCore.WMException import WMException PhEDEx_VALID_SUBSCRIPTION_PRIORITIES = ['low', 'normal', 'high', 'reserved'] class PhEDExSubscriptionException(WMException): """ _PhEDExSubscriptionExcept...
src/python/WMCore/Services/PhEDEx/DataStructs/SubscriptionList.py
11,724
_PhEDExSubscription_ Data structure which contains PHEDEx fields for PhEDEx subscription data service _PhEDExSubscriptionException_ Exception class for the phedex subscription _SubscriptionList_ Class represents collection of subscription. This organizes the subscriptions in a way to minimize their number. Initializ...
1,842
en
0.73789
""" Functions for signals and positions created within this package. Copyright 2021 InferStat Ltd 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 Un...
infertrade/algos/community/__init__.py
1,105
Functions for signals and positions created within this package. Copyright 2021 InferStat Ltd 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...
698
en
0.865362
import urllib.request,json from .models import Sources, Articles from datetime import datetime #Getting api key api_key = None #Getting the news base url # NEWS_API_KEY = None # NEWS_API_BASE_URL = None ARTICLE = None def configure_request(app): global api_key,NEWS_API_BASE_URL,NEWS_API_KEY,ARTICLE api_key = ...
app/requests.py
3,138
Function that processes the articles and returns a list of articles objects function that gets the json response to our url request function that checks the articles and processes them into instances Function that checks the news results and turn them into objects Args: sources_list: A list of dictionaries that co...
428
en
0.794258
class Const: """ 常量 """ class ConstError(TypeError):pass def __setattr__(self, name, value): if name in self.__dict__: raise self.ConstError("Can't rebind const (%s)" %name) self.__dict__[name]=value LAYOUT = Const() """ 布局 """ LAYOUT.SCREEN_WIDTH = 500 LAYOUT.SCREEN_HEIGHT = 600 LAYOUT.SIZE = ...
src/const.py
1,502
常量 地砖 战争迷雾 英雄 怪物 陷阱 黄金 微风 臭气 游戏结束 游戏通关 怪兽死亡 英雄走动 英雄攻击 遭遇危险 怪物 坑洞 黄金 行走 胜利 失败 攻击
81
zh
0.999097
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from pedrec.models.constants.skeleton_pedrec import SKELETON_PEDREC, SKELETON_PEDREC_JOINT_COLORS, SKELETON_PEDREC_LIMB_COLORS from pedrec.visualizers.visualization_helper_3d import draw_origin_3d, draw_grid_3d def add_skeleto...
pedrec/visualizers/skeleton_3d_visualizer.py
1,441
Joints score Limbs Preparation
30
en
0.787089
from ctypes import ( Structure, Union, c_char, c_double, c_int, c_long, c_short, c_ubyte, c_uint, c_ulong, c_ushort, ) from . import timespec class c_gsfSeaBeamSpecific(Structure): _fields_ = [("EclipseTime", c_ushort)] class c_gsfEM100Specific(Structure): _field...
gsfpy3_09/gsfSensorSpecific.py
28,127
168 bytes 42 bytes 72 bytes 1440 bytes 1792 bytes (1746 + 23 * 2) 80 bytes 1520 bytes 1536 bytes 1704 bytes 1746 bytes Sensor specific data structures for the Kongsberg 2040 / SIS 5.0 */ used for EM120, EM300, EM1002, EM3000, EM3002, and EM121A_SIS used for EM120, EM300, EM1002, EM3000, EM3002, and EM121A_SIS with raw ...
484
en
0.649473
# -*- coding: utf-8 -*- # Copyright (c) 2019, Aptitude technologie and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest class TestPriceConfigurator(unittest.TestCase): pass
shei/shei/doctype/price_configurator/test_price_configurator.py
228
-*- coding: utf-8 -*- Copyright (c) 2019, Aptitude technologie and Contributors See license.txt
95
en
0.721956
# 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, software # distributed under the Li...
tests/unit/admin/views/test_journals.py
5,072
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, software distributed under the License is distrib...
517
en
0.872906
# Copyright (c) 2020 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality ...
src/dev/arm/css/Scmi.py
6,142
This is a Agent to Platform channel (The agent is the initiator) Unidirectional channel The SCMI Communication class models a bidirectional communication between the SCMI platform and the agent. As such it has a ScmiAgentChannel and a ScmiPlatformChannel object as members. This is a Platform to Agent channel (The platf...
2,433
en
0.895042
# # Copyright 2015 Hewlett Packard Development Company, LP # Copyright 2015 Universidade Federal de Campina Grande # # 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://...
ironic/drivers/modules/oneview/management.py
6,510
Get the current boot device for the task's node. Provides the current boot device of the node. :param task: a task from TaskManager. :returns: a dictionary containing: :boot_device: the boot device, one of :mod:`ironic.common.boot_devices` [PXE, DISK, CDROM] :persistent: Whether the boot device will p...
2,814
en
0.749098
################################################# # Retrieve robust classifier from: # https://github.com/MadryLab/robustness ################################################# from robustness.datasets import CIFAR, RestrictedImageNet, ImageNet from robustness.model_utils import make_and_restore_model def get_robust_c...
classifiers/robust_classifier.py
2,186
Retrieve robust classifier from: https://github.com/MadryLab/robustness, transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
159
en
0.611126
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
ooobuild/dyn/configuration/backend/multi_layer_stratum.py
889
coding: utf-8 Copyright 2022 :Barry-Thomas-Paul: Moss 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...
713
en
0.829902
#!/usr/bin/python3 import sys import json import getopt import os import jsonschema import subprocess if os.geteuid() != 0: print('You must be a root user') sys.exit(72) json_file = '' nginx_conf = '/etc/nginx/nginx.conf' schema_file = '' test = False #------Parse command-line options------ def usage(): prin...
nginx_conf_gen.py
5,982
!/usr/bin/python3------Parse command-line options------------Get json and schema data------------Nginx functions------------Test 'location /'------------Make Nginx config file------ noindex 'location = /robots.txt'
214
en
0.196998
# This file is automatically generated by the rmf-codegen project. # # The Python code generator is maintained by Lab Digital. If you want to # contribute to this project then please do not edit this file directly # but send a pull request to the Lab Digital fork of rmf-codegen at # https://github.com/labd/rmf-codegen ...
src/commercetools/platform/client/login/by_project_key_login_request_builder.py
2,363
Authenticate Customer (Sign In). Retrieves the authenticated customer (a customer that matches the given email/password pair). If used with an access token for Anonymous Sessions, all orders and carts belonging to the anonymousId will be assigned to the newly created customer. If a cart is is returned as part of the Cu...
772
en
0.881798
# Copyright The OpenTelemetry 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 ...
instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py
17,528
Copyright The OpenTelemetry 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, software ...
962
en
0.8262
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
jdcloud_sdk/services/es/models/InstanceSpec.py
2,298
:param vpcId: 私有网络vpcId :param subnetId: 子网subnetId :param instanceVersion: es版本,当前支持5.6.9和6.5.4 :param instanceName: es集群名称,不可为空,只支持大小写字母、数字、英文下划线或者中划线,以字母开头且不能超过32位 :param azId: 可用区,各可用区编码请参考:https://docs.jdcloud.com/cn/jcs-for-elasticsearch/restrictions :param instanceClass: 规格配置,规格代码请参考:https://docs.jdcloud.c...
1,239
en
0.499441
# coding=utf-8 """Tokenization classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six import tensorflow as tf import re import warnings warnings.filterwarnings('ignore') def validate_case_matches_checkp...
preliminary_contest/nezha_pretrain/tokenization.py
12,970
Runs basic tokenization (punctuation splitting, lower casing, etc.). Runs end-to-end tokenziation. Runs WordPiece tokenziation. Constructs a BasicTokenizer. Args: do_lower_case: Whether to lower case the input. Performs invalid character removal and whitespace cleanup on text. Checks whether CP is the codepoint of a...
3,082
en
0.904254
import io from electrum.lnmsg import (read_bigsize_int, write_bigsize_int, FieldEncodingNotMinimal, UnexpectedEndOfStream, LNSerializer, UnknownMandatoryTLVRecordType, MalformedMsg, MsgTrailingGarbage, MsgInvalidFieldOrder, encode_msg, ...
electrum/tests/test_lnmsg.py
33,626
from https://github.com/lightningnetwork/lightning-rfc/blob/452a0eb916fedf4c954137b4fd0b61b5002b34ad/01-messaging.mdtlv-decoding-failures check if ECC point is valid?... skip for now.with self.assertRaises(Exception): lnser.read_tlv_stream(fd=io.BytesIO(bfh("0331043da092f6980e58d2c037173180e9a465476026ee50f96695963e...
1,111
en
0.601119
#fake database to get the pygame running import random questions = ["Question 1?", "Question 2?", "Question 3?", "Question 4?"] answers = ["Answer 1", "Answer 2", "Answer 3", "Answer 4"] def get_question(): return(random.choice(questions)) def get_answer(): return(random.choice(answers))
quiz/fake_db.py
299
fake database to get the pygame running
39
en
0.747899
#!/usr/bin/env python """ An example of image registration via the DTCWT. This script demonstrates some methods for image registration using the DTCWT. """ from __future__ import division, print_function import itertools import logging import os from matplotlib.pyplot import * import numpy as np import dtcwt from...
docs/image-registration.py
2,186
An example of image registration via the DTCWT. This script demonstrates some methods for image registration using the DTCWT. !/usr/bin/env python Load test images Take the DTCWT of both frames. Solve for transform savefig(os.path.splitext(os.path.basename(filename))[0] + '-registration.png')
295
en
0.578089
"""Azure Devops Server metric collector.""" from typing import List import requests from ..collector import Collector from ..type import Entities, URL, Value class AzureDevopsBase(Collector): """Base class for Azure DevOps collectors.""" def api_url(self) -> URL: url = super().api_url() re...
components/collector/src/collectors/azure_devops.py
2,815
Base class for Azure DevOps collectors. Collector to get issues from Azure Devops Server. Collector to get ready user story points from Azure Devops Server. Override because we need to do a post request and need to separately get the entities. Azure Devops Server metric collector. We didn't get a response with work i...
384
en
0.89627
import json import pytest try: from urllib import urlencode except ImportError: from urllib.parse import urlencode def url_string(string="/graphql", **url_params): if url_params: string += "?" + urlencode(url_params) return string def batch_url_string(**url_params): return url_string("...
graphene_django/tests/test_views.py
24,067
returns just json as __dict__ directly compare all key,value for __dict__ returns just json as __dict__ directly compare all key,value for __dict__ directly compare all key,value for __dict__ directly compare all key,value for __dict__ directly compare all key,value for __dict__ directly compare all key,value for __dic...
2,797
en
0.635859
import RPi.GPIO as GPIO from time import sleep import sys #Set warnings off (optional) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) #Set Button and LED pins JOYSTICK_BUTTON = 12 MAIN_SWITCH = 22 LED = 6 class button(): ''' A simple Push-Button class ''' def __init__(self, pin, pud_up_down): ...
pet_mk_viii/UnitTest/push_button.py
1,535
A simple Push-Button class Set warnings off (optional)Set Button and LED pins GPIO.add_event_detect(pin, GPIO.FALLING, callback=self.release_button_callback, bouncetime=300) Need ´import sys´ Time to clean up stuff!
223
en
0.447001
import pickle import sys import platform import gc import copy import warnings import tempfile from StringIO import StringIO from os import path import numpy as np from numpy.testing import ( run_module_suite, TestCase, assert_, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_...
numpy/core/tests/test_regression.py
59,333
Longfloat support is not consistent enough across platforms for this test to be meaningful. def test_longfloat_repr(self,level=rlevel): """Ticket 112""" if np.longfloat(0).itemsize > 8: a = np.exp(np.array([1000],dtype=np.longfloat)) assert_(str(a)[1:9] == str(a[0])[:8]) Creat...
3,628
en
0.853244
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 r""" Class describing simulation configuration object """ import os import shutil import subprocess import sys from collections import OrderedDict import logging as log fr...
util/dvsim/SimCfg.py
25,633
Simulation configuration object A simulation configuration class holds key information required for building a DV regression framework. Use the last regression coverage data to open up the GUI tool to analyze the coverage. Create deploy objects from the build and run lists. Create initial set of directories ...
6,240
en
0.865599
import platform from conans.client.graph.graph import CONTEXT_BUILD from conans.errors import ConanException class _SystemPackageManagerTool(object): mode_check = "check" mode_install = "install" tool_name = None install_command = "" update_command = "" check_command = "" def __init__(se...
conan/tools/system/package_manager.py
9,539
TODO: should we only add the arch if cross-building? TODO: apt? apt-get?
72
en
0.548788
# # Copyright 2014 OpenStack Foundation # All Rights Reserved # # 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 req...
ironic/dhcp/neutron.py
16,025
API for communicating to neutron 2.x API. Utility function to create Neutron client. Get a port's fixed ip address. :param port_uuid: Neutron port id. :param client: Neutron client instance. :returns: Neutron port ip address. :raises: FailedToGetIPAddressOnPort :raises: InvalidIPv4Address Get ip address of ironic port...
4,159
en
0.656961
# Copyright 2013 OpenStack Foundation # # 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...
keystone-moon/keystone/tests/unit/test_associate_project_endpoint_extension.py
59,084
Creates an endpoint associated with service and project. Create a valid endpoint group and project association. Create an invalid endpoint group and project association. HEAD /OS-EP-FILTER/endpoint_groups/{endpoint_group_id} Valid endpoint_group_id test case. Test HEAD with a valid endpoint group and project associati...
10,799
en
0.766947
""" Unittests of asm2cfg's regexes """ import unittest from src.asm2cfg import asm2cfg class FunctionHeaderTestCase(unittest.TestCase): """ Tests of function header regex """ def test_gdb_unstripped(self): line = 'Dump of assembler code for function test_function:' fmt, fun = asm2cf...
test/test_regex.py
6,323
Tests of function header regex Tests of parse_address function Tests of asm2cfg.parse_body function Tests of parse_comment function Tests of parse_address function Unittests of asm2cfg's regexes FIXME: support hex offsets
223
en
0.426712
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Franck Cuny <franck@lumberjaph.net> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the L...
ansible/grab001/lib/python2.7/site-packages/ansible/modules/extras/packaging/language/cpanm.py
6,774
!/usr/bin/python -*- coding: utf-8 -*- (c) 2012, Franck Cuny <franck@lumberjaph.net> This file is part of Ansible Ansible is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at you...
857
en
0.89165
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import QDialog, QApplication, QWidget, QVBoxLayout, QHBoxLayout, QGroupBox from PyQt5 import uic from os.path import join, dirname, abspath from qtpy.QtCore import Slot, QTimer, QThread, Signal, QObject, Qt #from PyQt5 import Qt _ST_DLG = join(...
startdialog.py
1,374
from PyQt5 import Qt Call the inherited classes __init__ methodsuper().__init__(parent)
87
en
0.353805
from jinja2.environment import Environment from jinja2.loaders import FileSystemLoader class _MutatioEnvironmentMeta(type): """Collects the mutatio tags into Mongo for the admin page.""" def __init__(cls, name, bases, dct): super(_MutatioEnvironmentMeta, cls).__init__(name, bases, dct) class Mutatio...
demo/flask_mutatio/environment.py
821
Collects the mutatio tags into Mongo for the admin page. This is too rigid
76
en
0.698156
""" An opportunity to explore how to make an EV3 Robot make sounds. Authors: Dave Fisher, David Mutchler, Vibha Alangar, their colleagues, and Leo Schoch-Spana. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. import simple_rosebotics as rb # ----------------------------------------------------------------...
src/m2_sounds.py
2,429
An opportunity to explore how to make an EV3 Robot make sounds. Authors: Dave Fisher, David Mutchler, Vibha Alangar, their colleagues, and Leo Schoch-Spana. DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. ------------------------------------------------------------------------------ DONE: 2. This is an ** OPTI...
576
en
0.63498
""" This file offers the methods to automatically retrieve the graph Lysinimicrobium luteum. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein...
bindings/python/ensmallen/datasets/string/lysinimicrobiumluteum.py
3,486
Return new instance of the Lysinimicrobium luteum graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = True Whether to preprocess the graph ...
2,693
en
0.709004
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def length(head) -> int: """ The method length, which accepts a linked list (head), and returns the length of the list. :param head: :return: """ i = 0 if head is Non...
kyu_7/fun_with_lists_length/length.py
432
The method length, which accepts a linked list (head), and returns the length of the list. :param head: :return: Created by Egor Kostan. GitHub: https://github.com/ikostan LinkedIn: https://www.linkedin.com/in/egor-kostan/
227
en
0.713314
from os.path import dirname, abspath from datetime import timedelta from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordRequestForm from slowapi import _rate_limit_exceeded_handler from slowapi.errors import RateLimitExceeded from routers.tasks import router_tasks fro...
main.py
2,563
FastAPI app instance Save main app directory Fix Docker dockerfile problems on the app startup Connecting routers to the app Connecting rate limiter to the app
159
en
0.763794
# Copyright Materialize, Inc. All rights reserved. # # Use of this software is governed by the Business Source License # included in the LICENSE file at the root of this repository. # # As of the Change Date specified in that file, in accordance with # the Business Source License, use of this software will be governed ...
misc/python/materialize/cli/mzbench.py
8,125
This program prints the number of CPU counts to benchmark on this machine. We remove some percentage of CPU cores off the top for system / background processing. With the CPUs that remain, we generate a list of evenly spaced worker counts. The list is limited by the number of trials desired. This is meant to help us e...
1,679
en
0.906497
# -*- coding: utf-8 -*- # File generated according to Generator/ClassesRef/Machine/LamSlotWind.csv # WARNING! All changes made in this file will be lost! """Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Machine/LamSlotWind """ from os import linesep from sys import getsizeof f...
pyleecan/Classes/LamSlotWind.py
19,954
Lamination with Slot filled with winding Compare two objects (skip parent) Constructor of the class. Can be use in three ways : - __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values for pyleecan type, -1 will call the default constructor - __init__ (init_dict = d) d must be a dictionnary wit...
3,044
en
0.680798
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
tests/unit/bokeh/application/handlers/test_notebook__handlers.py
3,876
----------------------------------------------------------------------------- Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. All rights reserved. The full license is in the file LICENSE.txt, distributed with this software.------------------------------------------------------------------------------...
1,605
en
0.198437
# Copyright (C) 2020 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Generate rules for snapshoting""" from ggrc.snapshotter.datastructures import Attr class Types(object): """Get default types for snapshotting""" # pylint: disable=too-few-public-methods all = {...
src/ggrc/snapshotter/rules.py
3,235
Returns a dictionary of rules Expected format of rule_list is the following: [ {"master_object_type", ...}, {"first degree object types"}, {"second degree object types"} ] For all master objects of type master_object_type, it will gather all related objects from first degree object types (which can be related ...
1,370
en
0.72911
## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 ## PubNub Real-time Push APIs and Notifications Framework ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ ## ----------------------------------- ## PubNub 3.0 Real-time Push Cloud API ## ----------------------------------- tr...
python/3.2/Pubnub.py
9,165
#** #* Pubnub #* #* Init the Pubnub Client API #* #* @param string publish_key required key to send messages. #* @param string subscribe_key required key to receive messages. #* @param string secret_key optional key to sign messages. #* @param boolean ssl required for 2048 bit encrypted messages. #* @param string origi...
2,957
en
0.355728
# -*- coding: utf-8 -*- """ ======================= Cmap and Custom Bins ======================= Invoke the cmap colour scheme and choose how many bins to use with your data. By default, the cmap colour scheme is used if you have many, many chains. You can enable it before that point if you wish and pass in the cmap ...
examples/customisations/plot_rainbow_serif_bins.py
1,797
======================= Cmap and Custom Bins ======================= Invoke the cmap colour scheme and choose how many bins to use with your data. By default, the cmap colour scheme is used if you have many, many chains. You can enable it before that point if you wish and pass in the cmap you want to use. You can al...
883
en
0.931906
from typing import List from mdrsl.data_structures.rules.generalized_rule_part import GeneralizedAntecedent from mdrsl.data_structures.item import Literal, NEQLiteral, EQLiteral from mdrsl.rule_generation.decision_tree_conversion.attribute_id_to_name_conversion import DecisionTreeFeatureIDConverter class TreeEdge: ...
mdrsl/rule_generation/decision_tree_conversion/tree_edge.py
2,703
find the descriptive attr as used for input for the decision tree
65
en
0.91403
import boto3 import logging import argparse import requests import xmltodict import asyncio import datetime import time import re import json import math from sqlalchemy import func from dateutil.relativedelta import relativedelta from requests.exceptions import ConnectionError, ReadTimeout from urllib3.exceptions ...
dataactcore/scripts/pull_fpds_data.py
89,512
Get values from the awardID level of the xml calculate values that aren't in any feed (or haven't been provided properly) for legal entity calculate values that aren't in any feed (or haven't been provided properly) for place of performance Calculate values that aren't in any feed but can be calculated. Args: o...
15,142
en
0.850632
""" 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, software distri...
app/gwells/models/ScreenIntakeMethodCode.py
1,289
Refers to the type of intake mechanism for a well screen, i.e. Screen, Open Bottom, Uncased Hole. 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 Unle...
621
en
0.885207
from __future__ import with_statement from distutils.version import StrictVersion from itertools import chain from select import select import os import socket import sys import threading import warnings try: import ssl ssl_available = True except ImportError: ssl_available = False from redis._compat impo...
redis/connection.py
37,064
Thread-safe blocking connection pool:: >>> from redis.client import Redis >>> client = Redis(connection_pool=BlockingConnectionPool()) It performs the same function as the default ``:py:class: ~redis.connection.ConnectionPool`` implementation, in that, it maintains a pool of reusable connections that can be s...
8,278
en
0.83408
#!/usr/bin/python # Copyright (c) 2013 The Bitcoin Core developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json from urllib import urlopen import requests import getpass from string import Template im...
qa/pull-tester/pull-tester.py
9,137
!/usr/bin/python Copyright (c) 2013 The Bitcoin Core developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. output to /dev/null by default: Init Merge onto upstream/master Remove old BitcoinPullTester comments (I'm being lazy a...
343
en
0.686894
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
bokeh/models/__init__.py
3,078
Provide Bokeh model "building block" classes. One of the central design principals of Bokeh is that, regardless of how the plot creation code is spelled in Python (or other languages), the result is an object graph that encompasses all the visual and data aspects of the scene. Furthermore, this *scene graph* is to be ...
2,196
en
0.459367
""" Django settings for Django_app project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import...
Django_app/Django_app/settings.py
4,529
Django settings for Django_app project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ Build paths i...
1,558
en
0.494838
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Milan Ondrasovic <milan.ondrasovic@gmail.com> import random from typing import Sequence, Tuple, Dict, cast import cv2 as cv import numpy as np import matplotlib.pyplot as plt from tracking import TrackedDetection ColorT = Tuple[int, int, int] PointT = Tuple[...
vehicle_tracker/visual.py
3,047
!/usr/bin/env python -*- coding: utf-8 -*- Author: Milan Ondrasovic <milan.ondrasovic@gmail.com> TODO Somehow calculate the shift.
130
en
0.388984
""" Parses the `run.dat` input file for MechDriver that specifices all of calculations to run for a given session of the code. Specifcally, looks for and parses several subsections: (1) `input` block: various input (2) `pes' block: idxs denoting what PESs in mech file to run (3) `spc` b...
mechlib/amech_io/parser/run.py
15,601
Loop over all of the tasks, add default keywords and parameters and assesses if all the input is valid Loops over the driver task list and checks if each task is a macro-task that should be expanded into sub-tasks. Right now, it splits all obj tasks into spc and ts :param tsk_lst: list of tasks to run for some dr...
4,246
en
0.778952
import logging import pytest import pydantic import requests from pymarc import Record, Field from airflow.models import Variable from pytest_mock import MockerFixture from plugins.folio.helpers import ( archive_artifacts, move_marc_files_check_tsv, post_to_okapi, process_marc, _move_001_to_035, ...
plugins/tests/test_helpers.py
8,884
Mock xcom messages dict Mock xcom Mock source and target dirs Mock Results and Archive Directories mock tmp dir noqa noqa Create mock Instance JSON file noqa noqa noqa mock sample csv and tsv mock results file Removes handler otherwise fails subsequent tests
258
en
0.719138
# # Copyright (c) 2015 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use...
tests/textcode/test_analysis.py
79,390
Given a sequence or iterable of arbitrary items, return an iterator of item ngrams tuples of length ngram_len. Buffers at most ngram_len iterable items. For example:: >>> list(ngram_processor([1, 2, 3, 4, 5], ngram_len=3)) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] Copyright (c) 2015 nexB Inc. and others. All rights reserve...
1,791
en
0.840768
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..registration import MultiResolutionAffineRegistration def test_MultiResolutionAffineRegistration_inputs(): input_map = dict( args=dict(argstr='%s', ), environ=dict( nohash=True, ...
nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py
1,783
AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
51
en
0.653745
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or module...
docs/conf.py
2,328
Configuration file for the Sphinx documentation builder. This file only contains a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/master/config -- Path setup -------------------------------------------------------------- If extensions (or modules to document wi...
1,518
en
0.69746
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. import json from re import compile def boolean(x): if x in [True, 1, '1', 'true', 'True']: return "true" if x in [False, 0, '0', 'false', 'False']: return "false" raise Value...
troposphere/validators.py
11,014
Method to indicate defering property validation Method to indicate bypassing property validation Copyright (c) 2012-2013, Mark Peek <mark@peek.org> All rights reserved. See LICENSE file for full license. Network ports can be Ref items consecutive periods not allowed IP addresses not allowed noqa Verify it is a valid ...
364
en
0.73504
from . import database_connect from .exceptions import IrodsError, IrodsWarning import logging import re def run_update(irods_config, cursor): l = logging.getLogger(__name__) new_schema_version = database_connect.get_schema_version_in_database(cursor) + 1 l.info('Updating to schema version %d...', new_sch...
scripts/irods/database_upgrade.py
10,790
max oracle varchar2 for sql is 4000, 32767 pl/sql
49
en
0.304903
"""The Simulator class. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np import pybullet from robovat.math.pose import Pose from robovat.simulation import physics from robovat.simulation.body import Body from robovat.si...
robovat/simulation/simulator.py
13,949
The Simulator class. Delete the simulator. Initialize the simulator. Args: assets_dir: The assets directory. physics_backend: Name of the physics engine backend. time_step: Time step of the simulation. gravity: The gravity as a 3-dimensional vector. worker_id: The id of the multi-threaded simulatio...
3,489
en
0.774642
# -*- coding: utf-8 -*- from openprocurement.planning.api.utils import opresource from openprocurement.api.utils import get_now, context_unpack, json_view from openprocurement.planning.api.validation import validate_plan_not_terminated from openprocurement.api.validation import validate_file_update, validate_file_uploa...
src/openprocurement/planning/api/views/plan_milestone_document.py
2,730
-*- coding: utf-8 -*-
21
en
0.767281
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import rospy import cv2 import sensor_msgs import numpy as np from cv_bridge import CvBridge class CameraPublisher(object): """ """ def __init__(self): """Default constructor""" self.rgb_image_topic = rospy.get_param("~rgb_image_topic",...
scripts/camera_publisher_node.py
2,579
Default constructor !/usr/bin/env python -*- coding: UTF-8 -*-
63
en
0.251276
import time import random import os import logging import sys from datetime import datetime from datetime import timedelta from urllib.parse import urlparse from urllib.parse import urljoin import click from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions imp...
main.py
11,363
comment_input.click() comment_input.clear() time.sleep(1) comment_input = driver.find_element_by_xpath('//TEXTAREA[@placeholder="Add a comment…"]') -------------------- An extra space is added here and then deleted. This forces the input box to update the reactJS core -------------------- comment_input.send_keys(text) ...
519
en
0.368244
from datetime import datetime from snuba.clickhouse.query_dsl.accessors import get_time_range from snuba.datasets.factory import get_dataset from snuba.datasets.plans.translator.query import identity_translate from snuba.query.parser import parse_query from snuba.query.processors.timeseries_processor import TimeSeries...
tests/clickhouse/query_dsl/test_time_range.py
1,583
Test finding the time range of a query.
39
en
0.901702
# 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, software # distributed under t...
keystone/models/revoke_model.py
12,797
Check if a token matches a revocation event. Compare a token against every revocation event. If the token matches an event in the `events` list, the token is revoked. If the token is compared against every item in the list without a match, it is not considered revoked from the `revoke_api`. :param events: a list of R...
3,896
en
0.871814
import numpy as np import cv2 # To capture webcam live stream, simply change the following line to: cap = cv2.VideoCapture(0) cap = cv2.VideoCapture('./assets/video.mp4') while (True): # Capture frame by frame _, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # hsv (hue sat value) ...
main.py
1,110
To capture webcam live stream, simply change the following line to: cap = cv2.VideoCapture(0) Capture frame by frame hsv (hue sat value) for the color red mask will be anything between range *lower_color to upper_color (Red)
224
en
0.881706
'''Ensemble some predictions. ''' import argparse import collections import math from scipy.special import logsumexp import sys MODES = ['mean', 'max', 'logsumexp', 'noisy_or', 'log_noisy_or', 'odds_ratio'] def parse_args(args): parser = argparse.ArgumentParser() parser.add_argument('mode', choices...
NAACL/ensemble.py
2,821
Ensemble some predictions. math.log(p / (1.0 - p) * 100000000)
64
en
0.336296
names = ["John", "Bob", "Dell", "python"]; print(names[0]) print(names[-1]) print(names[-2]) names[0] = "Amina" print(names[0]) print(names[0:3]) # List methods numbers = [1, 2, 3, 4, 5] numbers.append(6) numbers.insert(0, -1) numbers.remove(3) is_there = 1 in numbers numbers.count(3) # it will return count of 3 # ...
basic/list.py
525
List methods it will return count of 3 numbers.sort() Ascending order descending order To clone original list
110
en
0.633337
#!/usr/bin/env python3 """Install certificates from AWS S3. This file is a template. It should be processed by Terraform. """ # Third-Party Libraries import boto3 # Inputs from terraform CERT_BUCKET_NAME = "${cert_bucket_name}" CERT_READ_ROLE_ARN = "${cert_read_role_arn}" SERVER_FQDN = "${server_fqdn}" # These fi...
cloudinit/install-certificates.py
1,401
Install certificates from AWS S3. This file is a template. It should be processed by Terraform. !/usr/bin/env python3 Third-Party Libraries Inputs from terraform These files will be copied from the bucket and installed in the specified location. Create STS client Assume the role that can read the certificate Create ...
433
en
0.827739
#!/usr/bin/env python3 #-*- coding: utf-8 -*- from PyQt5.QtGui import QImage, qRgb, QPixmap import numpy as np import numpy as np gray_color_table = [qRgb(i, i, i) for i in range(256)] def toQImage(data, copy=True): if data is None: return QImage() data = data.copy() data[data>255] = 255 da...
python/iviz/Util.py
2,099
!/usr/bin/env python3-*- coding: utf-8 -*-
42
fr
0.319203
# Copyright (c) 2018-2022 Micro Focus or one of its affiliates. # Copyright (c) 2018 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licen...
vertica_python/vertica/connection.py
35,911
Creates a new deque with the primary host first, followed by any backup hosts Read the connection's AUTOCOMMIT setting from cache Change the connection's AUTOCOMMIT setting Cancel the current database operation. This can be called from a different thread than the one currently executing a database operation. Opens a ne...
5,662
en
0.840623
"""Tests for the Timestamp class.""" # # (C) Pywikibot team, 2014-2021 # # Distributed under the terms of the MIT license. # import calendar import datetime import re import unittest from contextlib import suppress from pywikibot import Timestamp from tests.aspects import TestCase class TestTimestamp(TestCase): ...
tests/timestamp_tests.py
5,251
Test Timestamp class comparisons. Test unsupported additions raise NotImplemented. Test addin a timedelta to a Timestamp. Test cloning a Timestamp instance. Test passing instance to factory methods works. Test conversion from and to ISO format. Test iso format properties. Test conversion from and to ISO format with sep...
902
en
0.794291
"""Download an image from the Web App and detect coordinates. download the image corresponding to the ID provided and run plant detection and coordinate conversion """ import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) from plant_detection.PlantDetection import PlantDetection from plant_detect...
priv/farmware/quickscripts/download_and_detect_coordinates.py
720
Download an image from the Web App and detect coordinates. download the image corresponding to the ID provided and run plant detection and coordinate conversion
161
en
0.812332
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack1 = [] self.stack2 = [] def push(self, x): """ :type x: int :rtype: void """ self.stack1.append(x) if len(self.stack2) == 0...
LeetCode/LeetCode_Python-master/LeetCode_Python-master/Algorithm-Easy/155_Min_Stack.py
1,679
initialize your data structure here. :rtype: int :rtype: void :type x: int :rtype: void :rtype: int Your MinStack object will be instantiated and called as such: obj = MinStack() obj.push(x) obj.pop() param_3 = obj.top() param_4 = obj.getMin()
245
en
0.645098
# Lint as: python2, python3 # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # 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 # ...
models/official/detection/modeling/architecture/resnet.py
9,643
Class to build ResNet family model. Returns the ResNet model for a given size and number of output classes. Args: inputs: a `Tesnor` with shape [batch_size, height, width, 3] representing a batch of images. is_training: `bool` if True, the model is in training mode. Returns: a `dict` containing `int` keys f...
3,895
en
0.806828
import datetime from constance import config from django.conf import settings from django.utils import dateparse , timezone import django.db.models as db def today(today=None): if today is not None: return dateparse.parse_date(today) if isinstance(today,basestring) else today elif not getattr(settings,...
utils/utils.py
2,487
Return a short string version of days Return the value for a NullBooleanSelect wigit based on bool_value Return the boolean value based on a NullBooleanSelect form value qargs : list of models.Q objects kwargs : filter_term=value dict return a DjanoORM Expression for the number of seconds/days between start_date and e...
408
en
0.649552
from typing import ClassVar, List, Optional, Tuple, Callable, Union, cast import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributions as D from alphazero.network.distributions import SquashedNormal, GeneralizedBeta from alphazero.network.utils import ( _map_nonli...
alphazero/network/policies.py
35,496
Policy class for learning a factorized GMM. Learns a 1D GMM for each dimension of the action space. The components of the GMM are either Normal or squashed Normal. Parameters ---------- representation_dim : int Dimensions of the input representation. action_dim : int Number of dimensions for the action space....
15,959
en
0.649504
#!/usr/bin/env python # coding: utf-8 # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny -...
scripts/fsmt/fsmt-make-super-tiny-model.py
2,679
!/usr/bin/env python coding: utf-8 This script creates a super tiny model that is useful inside tests, when we just want to test that the machinery works, without needing to the check the quality of the outcomes. This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - all files ~...
710
en
0.882941
from http_prompt.tree import Node class Context(object): def __init__(self, url=None, spec=None): self.url = url self.headers = {} self.querystring_params = {} self.body_params = {} self.body_json_params = {} self.options = {} self.should_exit = False ...
http_prompt/context/__init__.py
3,492
Create a tree for supporting API spec and ls command Path is a trailing slash Path ends with a trailing slash
109
en
0.846393
# Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2014-2017 The CephCoin Core developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Helpful routines for regression testing # # Add python-bitcoinr...
qa/rpc-tests/test_framework/util.py
21,638
Copyright (c) 2014-2015 The Bitcoin Core developers Copyright (c) 2014-2017 The CephCoin Core developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Helpful routines for regression testing Add python-bitcoinrpc to module search...
2,541
en
0.788538
import pandas as pd from Event import Event from Team import Team from Constant import Constant import numpy as np class Game: """A class for keeping info about the games""" def __init__(self, path_to_json): # self.events = None self.home_team = None self.guest_team = None self...
datasets/nba/Game.py
899
A class for keeping info about the games self.events = None (N,15,11,2) print(i,len(trajs))
93
en
0.745761
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class CrawlerNewsItem(scrapy.Item): url = scrapy.Field() # str article_from = scrapy.Field() # str article_type = scrapy.Field() # str ...
crawler_news/items.py
662
-*- coding: utf-8 -*- Define here the models for your scraped items See documentation in: https://docs.scrapy.org/en/latest/topics/items.html str str str str str list json list json list json str list json list json list json
225
en
0.380448
# -*- coding: utf-8 -*- import pytest from pytest_lazyfixture import sorted_by_dependency, lazy_fixture, _sorted_argnames try: import numpy except ImportError: numpy = None def test_fixture_in_parametrize_with_params(testdir): items = testdir.getitems(""" import pytest @pytest.fixture(par...
tests/test_lazyfixture.py
26,353
-*- coding: utf-8 -*- https://github.com/TvoroG/pytest-lazy-fixture/pull/19 https://github.com/TvoroG/pytest-lazy-fixture/issues/39 https://github.com/TvoroG/pytest-lazy-fixture/issues/39 pytest==3.2.5 https://github.com/TvoroG/pytest-lazy-fixture/issues/39 pytest==3.2.5 https://github.com/TvoroG/pytest-lazy-fixture/is...
383
en
0.808437
import pandas as pd import plotly.express as px df = pd.read_csv('data/query_result.csv') max_df = df.groupby(by='topic_id').max().reset_index() df = df[df['topic_id'].isin(max_df[max_df['recall'] > 0]['topic_id'].to_list())] for t in df['topic_id'].unique().tolist(): temp_df = df[df['topic_id'] == t] fig = px...
analyze_results.py
462
or "inclusive", or "linear" by default
38
en
0.844034
#! /usr/bin/env python # -*- coding: utf-8 -* """ Decorators to help manage our custom classes. """ TABLE_LIST = [] def register(cls): """ A decorator to register new table configuration classes. """ TABLE_LIST.append(cls) return cls def downloader(func): """ A decorator to download data...
census_data_downloader/core/decorators.py
956
A decorator to download data inside a table configuration class. A decorator to register new table configuration classes. Decorators to help manage our custom classes. ! /usr/bin/env python -*- coding: utf-8 -* Grab the TableConfig Grab the geotype downloader class by running the metaprogramming function For each year...
423
en
0.585509
from django.db import models import uuid from django.contrib.auth.models import User from article.models import ArticlePost from ckeditor.fields import RichTextField from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Comment(models.Model): # 博文评论 article = models.ForeignKey( ...
comment/models.py
760
Create your models here. 博文评论
29
en
0.732734
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Base class for RPC testing.""" from enum import Enum from io import BytesIO import logging import optp...
test/functional/test_framework/test_framework.py
53,858
Test framework for doing p2p comparison testing Sets up some t_notesd binaries: - 1 binary: test binary - 2 binaries: 1 test binary, 1 ref binary - n>2 binaries: 1 test binary, n-1 ref binaries This exception is raised to skip a test Base class for a t_notes test script. Individual t_notes test scripts should subclas...
10,359
en
0.785993