id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
000022114b640a3522af | def evaluate_model(self):
#Implement this method in the inherited class to calculate filter size
raise NotImplementedError | |
00002343309878dab9c6 | def get_shot_changes(diff_list, half_w_size, std_mult):
shot_changes = []
# Counter for frames from last shot change
frames_from_change = 0
# Counter for all frames. It starts at 1 for considering first frame
counter = 1
for diff in diff_list:
# N... | |
00002fa8bb46b4c518c3 | def test_local_backends_exist(self):
QP_program = QuantumProgram(specs=self.QPS_SPECS)
local_backends = qiskit.backends.local_backends()
self.assertTrue(local_backends) | |
000051b9adcfe981b52f | def interpolate(x_pints, y_points, deggree):
return np.polyfit(x_pints, y_points, deggree) | |
00005a8d0e283c3b630c | def _prefered_order(self):
return ['text',
'sentnum', 'strpos', 'span', 'gorn',
'semclass', 'connective', 'connective1', 'connective2',
'attribution',
'arg1', 'arg2'] | |
0000713032901257859a | def accel_x(self, accel_x):
self._accel_x = accel_x | |
00007ad5d97b33c23ad5 | def build_model(self):
# instantiate model
self.model = STDN(config=self.config,
channels=self.input_channels,
class_count=self.class_count,
num_features=self.num_features,
compress_factor=self.compr... | |
000091965a93fdc8e4d5 | def Hx(x, landmarks):
hx = []
for lmark in landmarks:
px, py = lmark
dist = np.sqrt((px - x[0])**2 + (py - x[1])**2)
angle = np.arctan2(py - x[1], px - x[0])
hx.extend([dist, normalize_angle(angle - x[2])])
return np.array(hx) | |
00009e995add2acf121c | def set_server(self, server):
try:
self.address, self.port = server.split(':')
except ValueError:
raise ValueError('Server address format must be: "address:port"')
self.port = int(self.port)
self.sock.connect((self.address, self.port)) | |
00009f3dfeca3d773dd2 | def app():
# create a temporary file to isolate the database for each test
db_fd, db_path = tempfile.mkstemp() | |
0000b8f80a16e5745cc7 | def plot_contour_matrix(
history,
m: int = 0,
t: int = None,
limits: dict = None,
height: float = 2.5,
numx: int = 50,
numy: int = 50,
refval: dict = None,
refval_color='C1',
kde=None,
names: dict = None,
show_clabel: bool = False,
show_legend: bool = False,
clabe... | |
0000bbf5888d92fd0ff8 | def get_all_links(content):
links = []
start = 0
while True:
current_link,start = get_next_link(content,start)
if current_link:
links.append(current_link)
else:
break
return links | |
0000dd0be88ce92cc171 | def dataset(variables):
return Dataset(*variables, X_names=["my_covariate"]) | |
0000e466861a8937a5ae | def get_model():
vgg = vgg19.VGG19(include_top=False, weights='imagenet')
vgg.trainable = False
style_outputs = [vgg.get_layer(name).output for name in style_layers]
content_outputs = [vgg.get_layer(name).output for name in content_layers]
model_outputs = style_outputs + content_outputs
return models.Mo... | |
0000fc03d6b420bd5dab | def _featurize_one(self, system: ProteinLigandComplex) -> Union[Universe, None]:
from ..modeling.MDAnalysisModeling import read_molecule, write_molecule
from ..utils import LocalFileStorage
logger.debug("Generating system name ...")
system_name = self._system_to_name(system)
lo... | |
0000fe7d98486ac2de54 | def get_file_path(self):
return self.file_path | |
00011d4325a0d2332e61 | def color_theme(): | |
00014a2746fe7db972f7 | def search_binary(xs, target):
lb = 0
ub = len(xs)
while True:
if lb == ub: # If region of interest (ROI) becomes empty
return -1
# Next probe should be in the middle of the ROI
mid_index = (lb + ub) // 2
# Fetch the item at that position
item_at_mid = ... | |
00015c1c4ddf5b00f46b | def getSignature(self) -> int:
... | |
000172082aa9ec26d18d | def iam_client(aws_credentials):
with mock_iam():
yield boto3.client("iam", region_name=AWS_REGION) | |
00017dea3196e219efae | def main():
parser = argparse.ArgumentParser(
prog='Slim down a Python program for lambda packaging')
parser.add_argument('--wd', type=str, required=True,
help='the working directory for the lambda function code')
parser.add_argument('--clean-up', type=bool, default=False,
... | |
0001c35a040daf4f3a1a | def save_document_from_form(document, request):
file_name = request.FILES['file'].name
file = document.cleaned_data['file']
description = document.cleaned_data['description']
# Never trust a user. They could change the hidden input values.
# Ex: user, document_type, storage_duration, etc.
storag... | |
0001cae80851e2240bdb | def start_server(self): | |
0001d0a386c3188c1e35 | def get_variance(X):
(m, n ) = X.shape
var = np.empty((X.shape[1], X.shape[1]))
for i in range(m):
var = var + X[i,:].T @ X[i,:]
var = np.cov(X.T)
return var | |
000227cb1dbb72376f56 | def plot(self, dfh, dfp):
self.clear_axes()
# plot HTU data
for _, rw in dfh.iterrows():
self.ax_log.plot([rw[2], rw[2]], [rw[1], rw[1]+1.7], 'm', lw=3.,
alpha=(0.3 if rw[3] == 0 else 1.))
# plot PFL data
self.ax_log.scatter(dfp.trans, ... | |
00024c2125344b594c57 | def fetch_weather(self, city, only_temp=False):
if not isinstance(city, str):
return "City Must Be A String"
if self.unit is not None:
if self.unit.lower() not in self._avialable_units:
return 'Please Select Correct Temperature Unit'
city = city
BA... | |
000292ffd94695cf7cfe | def print_table_to_csv(data_list, filename):
with open(filename, "w", newline="") as file:
writer = csv.writer(file, delimiter=",")
for iter in range(len(data_list[0])):
writer.writerow([x[iter] for x in data_list]) | |
0002c12f261193d31993 | def factory(cls, **kwargs):
db = cls(**kwargs)
if kwargs.get('create'):
db.create()
return db | |
0002d859b9f04bb9aba3 | def provideService(name, component): | |
0002db2bfac2ed8802ad | def parse(self, args):
if len(args) == 0:
raise ValueError("Specify at least an action.")
action = self._parse_actions(args[0])
self._parse_arguments(args[1:])
return action, self.options.dictify() | |
0002e845a2239a20cdfc | def __init__(__self__, *,
destination: pulumi.Input['ExportDeliveryDestinationArgs']):
pulumi.set(__self__, "destination", destination) | |
0002f48ef488b352d607 | def assert_response(self, response, data: bytes, status_code: int):
self.assertEqual(response.data, data)
self.assertEqual(response.status_code, status_code) | |
000326fdc76d04aca6c2 | def delete_poll(session: scoped_session, context: CallbackContext, poll: Poll) -> str:
poll.delete = PollDeletionMode.DB_ONLY.name
session.commit()
return i18n.t("callback.deleted", locale=context.user.locale) | |
00033cf5c7589012f70b | def get_network():
G = nx.Graph()
G.add_nodes_from(VOCAB)
with shelve.open('edges') as db:
for e, w in db.items():
u, v = e.split(',')
G.add_edge(u, v, weight=w)
G.remove_nodes_from(list(nx.isolates(G)))
return G | |
000354a0e960759fa0bd | def test_for_single_point(self):
func=Rosenbrock()
self.assertAlmostEqual(func.evaluate([[0.5, 0.5]]), 0, delta=1e-3) | |
00036ee7c1df8d8b4cb6 | def get_swagger():
try:
return _make_response(response=validator.get_swagger_spec())
except Exception as e:
return _make_error(500, e.message) | |
000373c08b87616b98ed | def test_send_command(self):
# "command" kwarg is not in allowed keys
cl = AMICommand(command=command)
self.assertFalse(cl.get_command() == command)
# allowed key
cl = AMICommand(command_txt=command)
self.assertTrue(cl.get_command() == command)
# allowed kwarg to... | |
00037cad98c9c645d501 | def GetLength(self) -> float:
... | |
0003921a26942246f3b9 | def valid(self):
return bool(self.values) | |
0003978a9d361a97f4ed | def load_json(name):
pass | |
0003bcc3461c58b59a5a | def filter_order_data(self, entity, conditions=None, order_by=None, page=None, per_page=None, embed=None):
params = {
'page': page,
'perPage': per_page,
'embed': embed
}
data = {
"filter": {}
}
if conditions:
data["filte... | |
0003f7938c0ce07d6997 | def __post_init__(self) -> None:
if not len(self.value):
raise ValueError(f'Invalid value for {self.__class__.__name__} - {self.value}') | |
0004071d00cfc0574ddd | def __len__(self) -> int:
return len(self._valid_keys) | |
00040d126960d93240f9 | def commit(
self, confirmed=False, confirm_timeout=None, persist=None, persist_id=None
):
rpc_xml = commit(
confirmed=confirmed,
confirm_timeout=confirm_timeout,
persist=persist,
persist_id=persist_id,
)
self._send_rpc(rpc_xml) | |
00040d2246923b824d47 | def accuracy(predictions, targets):
########################
# PUT YOUR CODE HERE #
batch_size = np.shape(predictions)[0]
predictions = (predictions == predictions.max(axis=1)[:, None]).astype(int)
correct_predictions = predictions * targets
accuracy = np.mean(np.sum(correct_predictions, ax... | |
000423b8d7d16bd0c9e7 | def build_cert_options(self):
if self._cert:
if isinstance(self._cert, six.string_types):
cert_path = self._cert
return {pycurl.SSLCERT: cert_path}
else:
cert_path, key_path = self._cert
return {
pycurl.... | |
00046debdadfa70cc54f | def get_n_days(date: datetime, n: int) -> Iterator[Day]:
next_date_gen = get_next_date(date)
yield from itertools.islice(next_date_gen, n) | |
000477cff4d5e9bb7c48 | def test_confluence_cloud_content_search_command_when_valid_response_is_returned(requests_mock):
from AtlassianConfluenceCloud import confluence_cloud_content_search_command, DEFAULT_EXPANDED_FIELD_CONTENT
expected_response = util_load_json(os.path.join("test_data", "content_search/content_search_command_respo... | |
00047c9da6d948892dc0 | def start():
ip = get_local_ip()
app.run(debug=True, host=ip) | |
00048ea680433af951d9 | def start_ball(self):
self.ball_starting() | |
00049621469914943b26 | def __threshold(self, ymx_i):
return ymx_i - (self.S * np.diff(self.xsn).mean()) | |
000497740bf260085237 | def get_list_of_images(self):
chosen_endpoint = \
self._get_random_endpoint_from_list_by_substring('/images')
self.client.get(chosen_endpoint) | |
00049f5f044575df78c0 | def _get_feed_dict(self, iteration, batch):
batch_flat = flatten(batch)
placeholders_flat = flatten(self._placeholders)
orig_feed_dict = {
placeholders_flat[key]: batch_flat[key]
for key in placeholders_flat.keys()
if key in batch_flat.keys()
}
... | |
0004c547ef7f6ea12bc6 | def printResult(_total):
print(_total) | |
0004d993a71d424015a5 | def __call__(self, use_local: bool = True, **kwargs) -> pd.DataFrame:
datasource = BytesIO(self.raw(use_local=use_local))
kwds = self._pd_read_kwds.copy()
kwds.update(kwargs)
if self.format == "json":
return pd.read_json(datasource, **kwds)
elif self.format == "csv"... | |
0004f0502127db94c464 | def __rect2polar(self,z):
return polar(z) | |
0004fefe385ba15f17da | async def on_ready():
await bot.change_presence(activity=discord.Game(name="just updated!"))
print(f"Serving {sum(guild.member_count for guild in bot.guilds)} users in {len(bot.guilds)} servers!")
while 1:
try:
await sleep(20)
await bot.change_presence(activity=di... | |
0005490dd5eb67d19e51 | def setup(self, **kwargs):
self.build_base_modules()
self.build_builder_helper()
self.build_project_init()
self.build_components_init()
self.build_main()
self.create_main_gui_template(**kwargs) | |
0005527928de62181e7f | async def fetch_ticker(self, symbol: str, params={}):
if symbol != 'BTC/JPY':
raise BadSymbol(self.id + ' fetchTicker() supports BTC/JPY only')
await self.load_markets()
market = self.market(symbol)
request = {
'pair': market['id'],
}
ticker = awai... | |
00055d3bcde9d2f047e9 | def _storage_init(self):
if not self._storage.initialized:
self._storage.init(self._module._py3_wrapper) | |
000590a469a5db5ccfd4 | def new_entry():
clear_screen()
entry = {}
entry['id'] = get_next_id()
entry['name'] = input_name()
print("How many minutes did you spend on {}?".format(entry['name']))
print("Or you may specify a format after the time, seperated by a comma")
entry['time_spent'] = input_time_spent()
add_... | |
00059ad375835a876929 | def i_encode_point(P):
return ((P[1] & ((1 << 255) - 1)) + ((P[0] & 1) << 255)).to_bytes(32, 'little') | |
0005b0b3b808f1b3472b | def line(x,w):
return -(w[1]/w[2])*x - (w[0]/w[2]) | |
0005ec3266c54acb3824 | def print_maze_img(self, type):
img = Image.new( 'RGB', (self.width, self.height))
pixels = img.load()
for i in range(self.height):
for j in range(self.width):
if self.board[i][j] == 1:
pixels[i,j] = (0, 0, 0)
if self.board[i][j] ==... | |
0005eeb01a04e5e175cf | def rotate(v, a, b):
a = np.radians(a)
b = np.radians(b)
ca = np.cos(a)
sa = np.sin(a)
cb = np.cos(b)
sb = np.sin(b)
M2 = np.array([
[+cb, 0, +sb],
[ 0, 1, 0],
[-sb, 0, +cb],
])
M3 = np.array([
[ 1, 0, 0],
[ 0, +ca, -sa],
[ 0... | |
000610dbaf34d2ec81d0 | def layer_normalize(input_features, output_shape = (1,1,-1)):
# Initialize layernorm object
layer_norm = LayerNorm(input_features.squeeze().shape).to(DEVICE)
# Normalize features and reshape
normalized_features = layer_norm(input_features.squeeze().float())
normalized_features = normalize... | |
000652b44e198e06856a | def deletePlayers():
DB = connect()
cursor = DB.cursor()
cursor.execute("DELETE FROM players;")
DB.commit()
DB.close() | |
000652cf5edff6f5ebee | def title(self, obj):
return _('Entries for the category %s') % obj.title | |
00068cd379936049a809 | def download_reference_from_s3(bucket,obj):
object_name = obj.split('/')[-1]
local_reference = os.path.join('/tmp',object_name)
s3.Object(bucket, obj).download_file(local_reference)
for j in ['.nhr','.nin','.nog','.nsd','.nsi','.nsq']:
s3.Object(bucket, obj+j).download_file(local_reference+j)
... | |
00068e9e860f833b7db4 | def description(self):
return None | |
0006a66c410f5b3bda8a | def speed(self, speed):
self.__speed= speed | |
0006b33920d94b6c2b98 | def walk(self):
self.__print_nodes(self.tree.root, 0) | |
0006c53d07b751692c1f | def sea_level_temperature(self):
temperature = self.fdmexec.GetAtmosphere().GetTemperatureSL()
return convert_jsbsim_temperature(temperature) | |
0006c7d0313c7daa1dd2 | def check_args(args, remainder):
if len(remainder) > 0:
usage("Unknown option(s) specified: <%s>" % remainder[0])
for arg in args:
if args[arg] is None:
usage("Mandatory argument --{arg} not specified".format(arg=arg)) | |
00071d41f2b3062c0d54 | def describe_schema_versions(self):
pass | |
000722687d4e8ca28e0e | def get_bands(self):
return len(self.coeff) - 1 | |
0007239171c9e8cee9b0 | def build(self):
self.title = "Box Layout Demo"
self.root = Builder.load_file('box_layout.kv')
return self.root | |
000728b5329ae7f2d210 | def test_execution(self):
self.execute("casapy_3c129_tutorial") | |
000749a0f1e1a06668ff | def example(): | |
000766f46c79757e041f | def password(self):
if self._password is None or self._password == u'':
self._get(self._user_name)
return self._password | |
00076a79829dd81be20f | def get_single_dataset(integrated_dataset, source_name):
return integrated_dataset.loc[integrated_dataset['source']==source_name] | |
00078be081d388b03ea5 | def constant_wrong_testing_setting_2pg():
inputbs = InputBoxRuleScorable(input_classes=[0, 1],
# positions=[0.1, 0.2], # of the center of the box
# sizes=[0.001, 0.002],
positions=[0.1, 0.0], # of the center o... | |
0007ad1aed489b72e501 | def listen_for_data():
sockett = socket.socket()
host = "100.65.251.47"
port = 9996
# sockett.connect((host, port))
sockett.bind((host, port))
sockett.listen(5)
conn, addr = sockett.accept()
with conn:
print("YA WE CONNNECTED BITCH: {}".format(addr[0]))
while True:
... | |
0007c02f794bf0d90c8f | def _update_iter(self, num):
self.iteration.set_text("Current Iteration: " + str(num)) | |
0007c20402b9995326a6 | def count(seq):
return sum(bool(x) for x in seq) | |
0007c76ae93ec618c619 | def test_build_url(self):
result = utils.build_url(self.base_url, {'b': 20})
# Note param ordering and correct new value for b
self.assertEquals(
result,
'https://www.grapheffect.com/some/path;hello?a=10&c=30&b=20') | |
0007d288d09171af4079 | def match_sources(wcs, onFilter):
def src_mtch(catalogPair):
"""
Match objects in a catalog pair.
Parameters
----------
catalogPair : a list or a tuple of (scienceCat, referenceCat).
"""
scienceCat, referenceCat = catalogPair
sciSrcSelTask = sourceSe... | |
0007dea5b9a6eb49e3ef | def FormatExpand(expand):
result=_FormatExpandList(expand)
result.sort()
return string.join(result,',') | |
00080a79b2af2d08232c | def collect_free_space():
temp_file = "/tmp/freespace.log"
os.system('df -h / > %s' % temp_file)
file_desc = open(temp_file, 'r')
free = file_desc.readlines()
file_desc.close()
free = ''.join(free)
return free[:-1].replace("\n", "<br/>") | |
000837940d6eb21093b8 | def getcount(arr, hits, shots = 10):
assert arr.shape==(batch_size, (seq_size +1)), \
"array input shape does not match expected shape: (%d,%d)"%(batch_size, (seq_size +1))
current_count = np.zeros((batch_size, seq_size+1, num_classes))
success_count = np.zeros_like(current_count)
shot_count = np.ze... | |
00083b4ae4705b4dbfc7 | def test_cant_submit_twice(self):
competition = Competition(games_to_run=100)
competition.add("ai1", AI)
self.assertEquals(competition.entries["ai1"].total_games, 0)
competition.add("ai2", AI)
competition.add("ai2", AI)
time.sleep(0.1)
self.assertEqual(competition... | |
00083d3e86975b4cefca | def main(model_dir,pickles,start_date='1980-10-01',end_date='2020-09-30',huc_col = 'huc8', **kwargs):
print(f'The huc col being processed is: {huc_col}')
################################################################
#first do the UA swe data - this is now (9/20/2021) in two different files, one from UA SWE and... | |
000841f548f3efbc1393 | def isAsciiChar(c: int) -> bool:
... | |
00085caf62599a9daac0 | def area(self) -> float:
return 2*(self.side1*self.side2+self.side1*self.side3+self.side2*self.side3) | |
000867b9b8ad3dc26025 | def _read_file(filename):
with open(filename, 'r') as f:
lines = f.readlines()
return [line.split() for line in lines] | |
000868770ac338de6735 | def test_title():
writer = Writer()
parts = publish_parts(source=test_title.__doc__,
writer=writer,
writer_name='html')
for k, v in parts.items():
print("%s\t:(%d)\t%s" % (k, len(v), str(v)[:80].replace('\n', ' ')))
assert len(parts['html_title... | |
00087af1a2980f0ba2d7 | def __init__(self,seq):
self.head = None
for item in seq:
node = ListNode(item)
node.next = self.head
self.head = node | |
000910889415aa6efdcb | def plot_bar(self):
plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n])
plt.xlabel('Value')
plt.ylabel('Number of Occurrences')
plt.title('Summary of Value Counts in Data List')
plt.show() | |
0009463ef6f88241b3b7 | def to_netcdf(self, filename: str) -> None: # type: ignore
super().to_netcdf(filename) | |
0009679b15d3b670f636 | def matmul(mat, vec):
c11 = mat[..., 0, 0:1] * vec[..., 0:1]
c12 = mat[..., 0, 1:2] * vec[..., 1:2]
c13 = mat[..., 0, 2:3] * vec[..., 2:3]
c21 = mat[..., 1, 0:1] * vec[..., 0:1]
c22 = mat[..., 1, 1:2] * vec[..., 1:2]
c23 = mat[..., 1, 2:3] * vec[..., 2:3]
c31 = mat[..., 2, 0:1] * v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.