uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b106f05c6de3061d22af1603 | train | function | def create_single_tf_example(faces, img_name, label_map_dict, base_dir):
img_path = os.path.join(base_dir, img_name)
# print ('">>', img_path, '<<"')
with tf.gfile.GFile(img_path, 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = PIL.Image.open(encoded_j... | def create_single_tf_example(faces, img_name, label_map_dict, base_dir):
| img_path = os.path.join(base_dir, img_name)
# print ('">>', img_path, '<<"')
with tf.gfile.GFile(img_path, 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = PIL.Image.open(encoded_jpg_io)
if not image.format == 'JPEG':
raise ValueError('Image... | import os
import sys
import io
import hashlib
# import logging
import tensorflow as tf
import PIL
import numpy as np
from object_detection.utils import label_map_util
from object_detection.dataset_tools import tf_record_creation_util
from object_detection.utils import dataset_util
import contextlib2
flags = tf.app.fla... | 186 | 194 | 647 | 18 | 168 | vuamitom/models | research/object_detection/dataset_tools/create_widerface_tf_record.py | Python | create_single_tf_example | create_single_tf_example | 24 | 80 | 24 | 24 | f1907f157a9424bcdce2741721c69eb419223948 | bigcode/the-stack | train |
45787a4effe01aeb26eab311 | train | function | def main(_):
data_dir = FLAGS.data_dir
train_output_path = os.path.join(FLAGS.output_dir, 'wider_faces_train.record')
val_output_path = os.path.join(FLAGS.output_dir, 'wider_faces_val.record')
train_image_dir = os.path.join(data_dir, 'WIDER_train', 'images')
val_image_dir = os.path.join(data_di... | def main(_):
| data_dir = FLAGS.data_dir
train_output_path = os.path.join(FLAGS.output_dir, 'wider_faces_train.record')
val_output_path = os.path.join(FLAGS.output_dir, 'wider_faces_val.record')
train_image_dir = os.path.join(data_dir, 'WIDER_train', 'images')
val_image_dir = os.path.join(data_dir, 'WIDER_val... | :
shard_idx = idx % num_shards
output_tfrecords[shard_idx].write(tf_example.SerializeToString())
valid_imgs += 1
except ValueError:
print('Invalid example: %s, ignored', img_path)
print ('no. valid images = ... | 72 | 72 | 243 | 4 | 68 | vuamitom/models | research/object_detection/dataset_tools/create_widerface_tf_record.py | Python | main | main | 128 | 152 | 128 | 128 | 7d280c79dc94dc99dd7c57508fe91be68f06d3c3 | bigcode/the-stack | train |
6c5d739bf3e58d62dccb2119 | train | class | class iFormElementAsync(BaseAsyncKeywords, ABC):
@abstractmethod
async def input_text(self, locator: str, text: str, clear=True):
pass
@abstractmethod
async def input_password(self, locator: str, text: str, clear=True):
pass
@abstractmethod
async def clear_element_text... | class iFormElementAsync(BaseAsyncKeywords, ABC):
@abstractmethod
| async def input_text(self, locator: str, text: str, clear=True):
pass
@abstractmethod
async def input_password(self, locator: str, text: str, clear=True):
pass
@abstractmethod
async def clear_element_text(self, locator: str):
pass
@abstractmethod
async def ... | from abc import ABC, abstractmethod
from PuppeteerLibrary.ikeywords.base_async_keywords import BaseAsyncKeywords
class iFormElementAsync(BaseAsyncKeywords, ABC):
@abstractmethod
| 40 | 64 | 130 | 17 | 22 | qahive/robotframework-puppeteer | PuppeteerLibrary/ikeywords/iformelement_async.py | Python | iFormElementAsync | iFormElementAsync | 5 | 25 | 5 | 7 | 00c236e55992e10702757d6867e696f2fed9d7a8 | bigcode/the-stack | train |
9ebf37fa0b33bdfe1484dacc | train | class | class Profile:
def __init__(self, rocket, motor, init_spin, launch_altit=0, length=0, motor_pos=0, hangle=4, timesteps=50):
# Static constants #
self.rocket = rocket # This should be from the Rocket class
self.motor = motor
self.init_spin = init_spin
self.motor_pos = mo... | class Profile:
| def __init__(self, rocket, motor, init_spin, launch_altit=0, length=0, motor_pos=0, hangle=4, timesteps=50):
# Static constants #
self.rocket = rocket # This should be from the Rocket class
self.motor = motor
self.init_spin = init_spin
self.motor_pos = motor_pos
... | import numpy as np
from scipy import integrate
from .utility import read_csv, atmo_model
import matplotlib.pyplot as mpl
from stabsim.rocket import Rocket
"""
Simulates a spin-stabilized launch profile
"""
class Profile:
| 51 | 256 | 1,424 | 3 | 48 | roguextech/Stanford-SSI-Spaceshot-Dynamics-Aero | stabsim/profile.py | Python | Profile | Profile | 10 | 130 | 10 | 10 | db8c6ab76c35792b4f1c5ce74b1e65f802325ef6 | bigcode/the-stack | train |
04de2d5a0b6e419df45e0174 | train | function | def getEmailContents(email_path):
"""Given a single email this function returns the body of the email as text"""
email_file = open(os.path.join(DATA_DIRECTORY, email_path))
try:
message = email.message_from_file(email_file)
except UnicodeDecodeError:
return "null", "null"
# Get ema... | def getEmailContents(email_path):
| """Given a single email this function returns the body of the email as text"""
email_file = open(os.path.join(DATA_DIRECTORY, email_path))
try:
message = email.message_from_file(email_file)
except UnicodeDecodeError:
return "null", "null"
# Get email subject
with open(os.path.j... | ry
Gets the body from an email text file.
Copyright 2022
"""
import os
import email
from email.parser import BytesParser
from email.policy import default
import numpy as np
from keras_preprocessing.sequence import pad_sequences
from keras_preprocessing.text import Tokenizer
DATA_DIRECTORY = "../data/emails"
def getEma... | 74 | 74 | 248 | 7 | 67 | kylemabry95/FunnelFeatureRequest | src/get_email_contents.py | Python | getEmailContents | getEmailContents | 17 | 46 | 17 | 17 | 87c009584a99752de8d90e9caeb1ee99d1b1a569 | bigcode/the-stack | train |
73960ad2b031f0963e4c1385 | train | function | def get_all_emails():
"""Gets all emails in the DATA_DIRECTORY."""
# Get all email data
all_email_headers = []
all_email_bodies = []
for (root, dirs, files) in os.walk(DATA_DIRECTORY):
for file in files:
header, body = getEmailContents(file)
all_email_headers.append(... | def get_all_emails():
| """Gets all emails in the DATA_DIRECTORY."""
# Get all email data
all_email_headers = []
all_email_bodies = []
for (root, dirs, files) in os.walk(DATA_DIRECTORY):
for file in files:
header, body = getEmailContents(file)
all_email_headers.append(header)
al... | 'text/plain' and 'attachment' not in cdispo:
email_body = part.get_payload(decode=True) # decode
break
# if no attachments (in our case there are likely none and this will run)
else:
# Get email body
email_body = str(b.get_payload(decode=True))
return email... | 85 | 85 | 284 | 6 | 78 | kylemabry95/FunnelFeatureRequest | src/get_email_contents.py | Python | get_all_emails | get_all_emails | 49 | 83 | 49 | 49 | 48468798dba2063fa5f7005567358abe48960d64 | bigcode/the-stack | train |
1bd5ffff18dfbbdf601efe0f | train | function | def main():
# Data
# [START data]
costs = [
[90, 76, 75, 70, 50, 74],
[35, 85, 55, 65, 48, 101],
[125, 95, 90, 105, 59, 120],
[45, 110, 95, 115, 104, 83],
[60, 105, 80, 75, 59, 62],
[45, 65, 110, 95, 47, 31],
[38, 51, 107, 41, 69, 99],
[47, 85,... | def main():
# Data
# [START data]
| costs = [
[90, 76, 75, 70, 50, 74],
[35, 85, 55, 65, 48, 101],
[125, 95, 90, 105, 59, 120],
[45, 110, 95, 115, 104, 83],
[60, 105, 80, 75, 59, 62],
[45, 65, 110, 95, 47, 31],
[38, 51, 107, 41, 69, 99],
[47, 85, 57, 71, 92, 77],
[39, 63, 97, 49,... | #!/usr/bin/env python3
# Copyright 2010-2021 Google LLC
# 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 ... | 185 | 256 | 1,213 | 13 | 172 | jdarlay/or-tools | ortools/sat/samples/assignment_groups_sat.py | Python | main | main | 21 | 135 | 21 | 23 | 0ebe189dc4edb8f313d60daaafa1ca364264e5c9 | bigcode/the-stack | train |
ada532813766a5996ec72610 | train | class | class QLearningAgent(ReinforcementAgent):
"""
Q-Learning Agent
Functions you should fill in:
- computeValueFromQValues
- computeActionFromQValues
- getQValue
- getAction
- update
Instance variables you have access to
- self.epsilon (exploration pro... | class QLearningAgent(ReinforcementAgent):
| """
Q-Learning Agent
Functions you should fill in:
- computeValueFromQValues
- computeActionFromQValues
- getQValue
- getAction
- update
Instance variables you have access to
- self.epsilon (exploration prob)
- self.alpha (learning rate)
... | # qlearningAgents.py
# ------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.be... | 200 | 256 | 914 | 9 | 190 | ManosL/100DaysOfMLCode | Day 10/qlearningAgents.py | Python | QLearningAgent | QLearningAgent | 21 | 147 | 21 | 21 | c525cf0edfae677d5a75add59a44ad61949dd651 | bigcode/the-stack | train |
3fa8c09fac8e2bf4ac9fc7ce | train | class | class PacmanQAgent(QLearningAgent):
"Exactly the same as QLearningAgent, but with different default parameters"
def __init__(self, epsilon=0.05,gamma=0.8,alpha=0.2, numTraining=0, **args):
"""
These default parameters can be changed from the pacman.py command line.
For example, to chang... | class PacmanQAgent(QLearningAgent):
| "Exactly the same as QLearningAgent, but with different default parameters"
def __init__(self, epsilon=0.05,gamma=0.8,alpha=0.2, numTraining=0, **args):
"""
These default parameters can be changed from the pacman.py command line.
For example, to change the exploration rate, try:
... | State)
error = reward + (self.discount * next_q_val) - curr_q_val
self.q_values[(state, action)] += self.alpha * error
def getPolicy(self, state):
return self.computeActionFromQValues(state)
def getValue(self, state):
return self.computeValueFromQValues(state)
c... | 83 | 83 | 279 | 10 | 73 | ManosL/100DaysOfMLCode | Day 10/qlearningAgents.py | Python | PacmanQAgent | PacmanQAgent | 150 | 179 | 150 | 150 | ccde3491af1ea1837053fe201b33a881f63afd47 | bigcode/the-stack | train |
a333be1009095c25373d3275 | train | class | class ApproximateQAgent(PacmanQAgent):
"""
ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is.
"""
def __init__(self, extractor='IdentityExtractor', **args):
self.featExtractor = util.lo... | class ApproximateQAgent(PacmanQAgent):
| """
ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is.
"""
def __init__(self, extractor='IdentityExtractor', **args):
self.featExtractor = util.lookup(extractor, globals())()
Pa... | = alpha
args['numTraining'] = numTraining
self.index = 0 # This is always Pacman
QLearningAgent.__init__(self, **args)
def getAction(self, state):
"""
Simply calls the getAction method of QLearningAgent and then
informs parent of action for Pacman. Do not change o... | 119 | 119 | 399 | 11 | 107 | ManosL/100DaysOfMLCode | Day 10/qlearningAgents.py | Python | ApproximateQAgent | ApproximateQAgent | 182 | 238 | 182 | 182 | 99301e9a1c919ac67780d9a5d1f8d4331d199be9 | bigcode/the-stack | train |
81008293e187bba0b427e9a0 | train | function | def test_suite():
return unittest.makeSuite(ShutdownTest, "check")
| def test_suite():
| return unittest.makeSuite(ShutdownTest, "check")
| conn.close(),
# that calls conn.transaction_manager.unregisterSynch(self),
# but from a different thread, so transaction_manager._synchs
# have different contents.
self._db.close()
def tearDown(self):
ZODB.tests.util.TestCase.tearDown(self)
def test_suite():
| 64 | 64 | 16 | 4 | 60 | vpelletier/ZODB | src/ZODB/tests/testThreadedShutdown.py | Python | test_suite | test_suite | 54 | 55 | 54 | 54 | 1a57a26af19e23d9d52d2ad163465abdf6f33c9b | bigcode/the-stack | train |
eeb44b95be8e2cb6356b6a4f | train | class | class ShutdownTest(ZODB.tests.util.TestCase):
def setUp(self):
# Our default transaction manager is
# transaction._manager.ThreadTransactionManager
# so no need to set it.
ZODB.tests.util.TestCase.setUp(self)
self._storage = ZODB.FileStorage.FileStorage(
'ZODBTes... | class ShutdownTest(ZODB.tests.util.TestCase):
| def setUp(self):
# Our default transaction manager is
# transaction._manager.ThreadTransactionManager
# so no need to set it.
ZODB.tests.util.TestCase.setUp(self)
self._storage = ZODB.FileStorage.FileStorage(
'ZODBTests.fs', create=1)
self._db = ZODB.DB(se... | = threading.Event()
def run(self):
conn = self.db.open()
conn.sync()
self.event.set()
time.sleep(15)
# conn.close calls self.transaction_manager.unregisterSynch(self)
# and this succeeds.
conn.close()
class ShutdownTest(ZODB.tests.util.TestCase):
| 64 | 64 | 189 | 10 | 54 | vpelletier/ZODB | src/ZODB/tests/testThreadedShutdown.py | Python | ShutdownTest | ShutdownTest | 29 | 51 | 29 | 30 | 1275de6f82bdb4c4717d38256b5e9c5401b69c50 | bigcode/the-stack | train |
8373cc4306420ab3bf8b67c3 | train | class | class ZODBClientThread(threading.Thread):
def __init__(self, db, test):
threading.Thread.__init__(self)
self._exc_info = None
self.setDaemon(True)
self.db = db
self.test = test
self.event = threading.Event()
def run(self):
conn = self.db.open()
c... | class ZODBClientThread(threading.Thread):
| def __init__(self, db, test):
threading.Thread.__init__(self)
self._exc_info = None
self.setDaemon(True)
self.db = db
self.test = test
self.event = threading.Event()
def run(self):
conn = self.db.open()
conn.sync()
self.event.set()
... | import threading
import time
import unittest
import ZODB
class ZODBClientThread(threading.Thread):
| 22 | 64 | 111 | 9 | 12 | vpelletier/ZODB | src/ZODB/tests/testThreadedShutdown.py | Python | ZODBClientThread | ZODBClientThread | 8 | 26 | 8 | 9 | b2044c07d19119ddbec8ba677d6dc1c7c6e097aa | bigcode/the-stack | train |
19b7b493f19f64f2cd39fb17 | train | function | @route('/js/<filename>')
def js_static(filename):
return static_file(filename, root='./js')
| @route('/js/<filename>')
def js_static(filename):
| return static_file(filename, root='./js')
| _one_say_sentence(saying)
print(t)
return json.dumps(t)
@route('/')
def index():
return template("template.html")
@route('/css/<filename>')
def css_static(filename):
return static_file(filename, root='./css')
@route('/js/<filename>')
def js_static(filename):
| 64 | 64 | 22 | 12 | 52 | YJY123/News-person-speech-automatic-extraction | view_extraction.py | Python | js_static | js_static | 23 | 25 | 23 | 24 | c13f43c1d3b9b2316ebfa5a95e12b6555c4f9390 | bigcode/the-stack | train |
191b0579b9cd5c3ab858f74f | train | function | @route('/result/<filename>')
def get_json(filename):
return static_file(filename, root='./result')
| @route('/result/<filename>')
def get_json(filename):
| return static_file(filename, root='./result')
| _file(filename, root='./css')
@route('/js/<filename>')
def js_static(filename):
return static_file(filename, root='./js')
@route('/image/<filename>')
def js_static(filename):
return static_file(filename, root='./image')
@route('/result/<filename>')
def get_json(filename):
| 64 | 64 | 22 | 12 | 52 | YJY123/News-person-speech-automatic-extraction | view_extraction.py | Python | get_json | get_json | 31 | 33 | 31 | 32 | c776caff97eec39ee558e6c5e7123fda1ca453f9 | bigcode/the-stack | train |
149181ee49ebd9f03963ddb6 | train | function | @route('/image/<filename>')
def js_static(filename):
return static_file(filename, root='./image')
| @route('/image/<filename>')
def js_static(filename):
| return static_file(filename, root='./image')
| return template("template.html")
@route('/css/<filename>')
def css_static(filename):
return static_file(filename, root='./css')
@route('/js/<filename>')
def js_static(filename):
return static_file(filename, root='./js')
@route('/image/<filename>')
def js_static(filename):
| 63 | 64 | 22 | 12 | 51 | YJY123/News-person-speech-automatic-extraction | view_extraction.py | Python | js_static | js_static | 27 | 29 | 27 | 28 | 0ec3b65b772ded3088ef7591b0a6f9ee542bf57f | bigcode/the-stack | train |
a81ef05b7c7c240bea4fb2f2 | train | function | @route('/get_saying')
def get_saying():
saying = request.query.saying
t = test_5.get_one_say_sentence(saying)
print(t)
return json.dumps(t)
| @route('/get_saying')
def get_saying():
| saying = request.query.saying
t = test_5.get_one_say_sentence(saying)
print(t)
return json.dumps(t)
| # -*- coding:utf-8 -*-
from bottle import route, run, debug, template, request, static_file
import json
import requests, urllib
import test_5
@route('/get_saying')
def get_saying():
| 48 | 64 | 44 | 12 | 35 | YJY123/News-person-speech-automatic-extraction | view_extraction.py | Python | get_saying | get_saying | 8 | 13 | 8 | 9 | e7f94b88f5ffc14d0c8bc1235663f922f14a8163 | bigcode/the-stack | train |
4fc43214642e3da3096554b6 | train | function | @route('/css/<filename>')
def css_static(filename):
return static_file(filename, root='./css')
| @route('/css/<filename>')
def css_static(filename):
| return static_file(filename, root='./css')
| aying')
def get_saying():
saying = request.query.saying
t = test_5.get_one_say_sentence(saying)
print(t)
return json.dumps(t)
@route('/')
def index():
return template("template.html")
@route('/css/<filename>')
def css_static(filename):
| 64 | 64 | 22 | 12 | 52 | YJY123/News-person-speech-automatic-extraction | view_extraction.py | Python | css_static | css_static | 19 | 21 | 19 | 20 | ad284da1cee0bc0604dfb59c316b0e5c7cf8073f | bigcode/the-stack | train |
be0669f799ac2c44bacf396c | train | function | @route('/')
def index():
return template("template.html")
| @route('/')
def index():
| return template("template.html")
|
import json
import requests, urllib
import test_5
@route('/get_saying')
def get_saying():
saying = request.query.saying
t = test_5.get_one_say_sentence(saying)
print(t)
return json.dumps(t)
@route('/')
def index():
| 64 | 64 | 13 | 6 | 58 | YJY123/News-person-speech-automatic-extraction | view_extraction.py | Python | index | index | 15 | 17 | 15 | 16 | fc0938c09cc9d71f93c3d0f65d76dbfb3eef25af | bigcode/the-stack | train |
e8863016bf686bd8e57fb086 | train | function | def miniMaxSum(arr):
print((sum(arr)-(max(arr))),(sum(arr)-(min(arr))))
| def miniMaxSum(arr):
| print((sum(arr)-(max(arr))),(sum(arr)-(min(arr))))
| allenges/one-month-preparation-kit-mini-max-sum/problem
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'miniMaxSum' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def miniMaxSum(arr):
| 64 | 64 | 23 | 7 | 57 | allenalvin333/Hackerrank_Prep | 1M/W1/2.py | Python | miniMaxSum | miniMaxSum | 17 | 18 | 17 | 17 | d9be5a2030d51285cca814373f4cae815dd4377c | bigcode/the-stack | train |
59fef4af9cfbe75105b80320 | train | class | class CNAMEStaticRegTests(TestCase):
def create_domain(self, name, ip_type=None, delegated=False):
if ip_type is None:
ip_type = '4'
if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
pass
else:
name = ip_to_domain_name(name, ip_type=ip_type)
d = Dom... | class CNAMEStaticRegTests(TestCase):
| def create_domain(self, name, ip_type=None, delegated=False):
if ip_type is None:
ip_type = '4'
if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):
pass
else:
name = ip_to_domain_name(name, ip_type=ip_type)
d = Domain(name=name, delegated=delegated)
... | from django.test import TestCase
from django.core.exceptions import ValidationError
from core.registration.static.models import StaticReg
from systems.tests.utils import create_fake_host
from mozdns.domain.models import Domain
from mozdns.cname.models import CNAME
from mozdns.ip.utils import ip_to_domain_name
class C... | 74 | 155 | 518 | 9 | 64 | jlin/inventory | core/registration/static/tests/CNAME_tests.py | Python | CNAMEStaticRegTests | CNAMEStaticRegTests | 12 | 72 | 12 | 12 | 0120c2ef8965fc8c95c6239794ff4f69307691ed | bigcode/the-stack | train |
c8be7f6ae151e60ed928cbbc | train | class | class ConnectionTests(TestFramework):
def test_connection_with_statement(self):
with Connection('127.0.0.1', 'guest', 'guest', lazy=True) as con:
self.assertIsInstance(con, Connection)
def test_connection_with_statement_when_failing(self):
try:
with Connection('127.0.0.1... | class ConnectionTests(TestFramework):
| def test_connection_with_statement(self):
with Connection('127.0.0.1', 'guest', 'guest', lazy=True) as con:
self.assertIsInstance(con, Connection)
def test_connection_with_statement_when_failing(self):
try:
with Connection('127.0.0.1', 'guest', 'guest', lazy=True) as con... | import socket
import threading
from mock import Mock
from pamqp import frame as pamqp_frame
from pamqp import commands as commands
from pamqp.commands import Basic as spec_basic
from amqpstorm import Channel
from amqpstorm import Connection
from amqpstorm import compatibility
from amqpstorm.base import MAX_CHANNELS
f... | 105 | 256 | 4,064 | 6 | 98 | MeggyCal/amqpstorm | amqpstorm/tests/unit/connection/connection_tests.py | Python | ConnectionTests | ConnectionTests | 18 | 534 | 18 | 18 | 8221d1766a1c824d0fd88b29dc554dbefaba6afc | bigcode/the-stack | train |
6967dfe33a62992f3771a087 | train | function | def Serf():
global Serfs
global Hackers
mutex.acquire()
Serfs+=1
if Serfs == 4:
serfs_cola.release()
serfs_cola.release()
serfs_cola.release()
serfs_cola.release()
Serfs-=4
mutex.release()
aborda("ser... | def Serf():
| global Serfs
global Hackers
mutex.acquire()
Serfs+=1
if Serfs == 4:
serfs_cola.release()
serfs_cola.release()
serfs_cola.release()
serfs_cola.release()
Serfs-=4
mutex.release()
aborda("serf")
... |
def aborda(tipo):
global passengers
balsa_mutex.acquire()
passengers+=1
print("Soy "+tipo+" y subo a la balsa\n")
if passengers == 4:
zarpar()
passengers=0
balsa_mutex.release()
def Serf():
| 64 | 64 | 159 | 5 | 59 | FrancisBL5/sistop-2022-2 | tareas/2/EscalonaAxel/rio.py | Python | Serf | Serf | 43 | 81 | 43 | 44 | 8b738154ab647c72d483e69864193801281d9ac2 | bigcode/the-stack | train |
9d5c4a912aa6831b554f5fda | train | function | def Hacker():
global Hackers
global Serfs
mutex.acquire()
Hackers+=1
if Hackers==4:
hackers_cola.release()
hackers_cola.release()
hackers_cola.release()
hackers_cola.release()
Hackers-=4
mute... | def Hacker():
| global Hackers
global Serfs
mutex.acquire()
Hackers+=1
if Hackers==4:
hackers_cola.release()
hackers_cola.release()
hackers_cola.release()
hackers_cola.release()
Hackers-=4
mutex.release()
a... | ()
hackers_cola.release()
serfs_cola.release()
Hackers-=2
Serfs-=2
mutex.release()
aborda("serf")
else:
mutex.release()
serfs_cola.acquire()
aborda("Serf")
def Hacker():
| 63 | 64 | 162 | 5 | 58 | FrancisBL5/sistop-2022-2 | tareas/2/EscalonaAxel/rio.py | Python | Hacker | Hacker | 83 | 119 | 83 | 84 | b094760fc1a4f25dbb3c8e8099c336b94521e444 | bigcode/the-stack | train |
8657a392bbae650891048759 | train | function | def aborda(tipo):
global passengers
balsa_mutex.acquire()
passengers+=1
print("Soy "+tipo+" y subo a la balsa\n")
if passengers == 4:
zarpar()
passengers=0
balsa_mutex.release()
| def aborda(tipo):
| global passengers
balsa_mutex.acquire()
passengers+=1
print("Soy "+tipo+" y subo a la balsa\n")
if passengers == 4:
zarpar()
passengers=0
balsa_mutex.release()
| = 0
Serfs = 0
passengers = 0
#mutexes
mutex = Semaphore(1)
balsa_mutex = Semaphore(1)
#semáforos
serfs_cola = Semaphore(0)
hackers_cola = Semaphore(0)
def aborda(tipo):
| 63 | 64 | 58 | 5 | 58 | FrancisBL5/sistop-2022-2 | tareas/2/EscalonaAxel/rio.py | Python | aborda | aborda | 30 | 41 | 30 | 32 | c9b052b2c2a70fab2d5f87ec6064846ef8f3754a | bigcode/the-stack | train |
14719030673cbf0b4423f89a | train | function | def zarpar():
print("Let´s go\n")
sleep(1)
| def zarpar():
| print("Let´s go\n")
sleep(1)
| fs_cola.release()
serfs_cola.release()
Hackers-=2
Serfs-=2
mutex.release()
aborda("Hacker")
else:
mutex.release()
hackers_cola.acquire()
ab... | 63 | 64 | 17 | 4 | 59 | FrancisBL5/sistop-2022-2 | tareas/2/EscalonaAxel/rio.py | Python | zarpar | zarpar | 122 | 124 | 122 | 122 | ed91ae84c4e3800c822610f2e9e42ff313eb45da | bigcode/the-stack | train |
f8b4d6a467434acd6f1171af | train | function | def _get_arguments():
parser = argparse.ArgumentParser(description="Compile and upload sketch")
parser.add_argument("address", type=str, help="Network address of lamp")
return parser.parse_args()
| def _get_arguments():
| parser = argparse.ArgumentParser(description="Compile and upload sketch")
parser.add_argument("address", type=str, help="Network address of lamp")
return parser.parse_args()
| rb") as fw:
response = requests.post("http://%s/update" % args.address, files={"update": fw})
if "Update Success" not in response.text:
print("Answer was: %r" % response.text)
raise SystemExit("Upload failed")
def _get_arguments():
| 64 | 64 | 41 | 5 | 59 | LarsMichelsen/Super-Simple-RGB-WiFi-Lamp | compile_and_upload.py | Python | _get_arguments | _get_arguments | 36 | 39 | 36 | 36 | f87429de0475e48e9bb7bf198c22e7d754436bc8 | bigcode/the-stack | train |
fdfab1595fd29d826db247a5 | train | function | def main():
"""The magic goes here"""
args = _get_arguments()
git_base = Path(__file__).resolve().parent
build_base = git_base / "build"
firmware_file = build_base / "Super_Simple_RGB_WiFi_Lamp.ino.bin"
sketch_file = git_base / "Super_Simple_RGB_WiFi_Lamp" / "Super_Simple_RGB_WiFi_Lamp.ino"
... | def main():
| """The magic goes here"""
args = _get_arguments()
git_base = Path(__file__).resolve().parent
build_base = git_base / "build"
firmware_file = build_base / "Super_Simple_RGB_WiFi_Lamp.ino.bin"
sketch_file = git_base / "Super_Simple_RGB_WiFi_Lamp" / "Super_Simple_RGB_WiFi_Lamp.ino"
print("+++... | #!/usr/bin/env python3
"""Small helper to update the website, compile the sketch and upload it, all in one"""
import argparse
import subprocess
from pathlib import Path
import requests
def main():
| 43 | 84 | 283 | 3 | 39 | LarsMichelsen/Super-Simple-RGB-WiFi-Lamp | compile_and_upload.py | Python | main | main | 9 | 34 | 9 | 9 | 181c293cce7609ce9d19fa9bac947a6c0a810245 | bigcode/the-stack | train |
87fc3676aa28949d51949b30 | train | class | class patchCertificatesV1alpha1CertificateSigningRequest(K8sClient):
def run(
self,
body,
name,
pretty=None,
config_override=None):
ret = False
args = {}
args['config_override'] = {}
args['params'] = {}
if config... | class patchCertificatesV1alpha1CertificateSigningRequest(K8sClient):
| def run(
self,
body,
name,
pretty=None,
config_override=None):
ret = False
args = {}
args['config_override'] = {}
args['params'] = {}
if config_override is not None:
args['config_override'] = config_ov... | import json
from lib.k8s import K8sClient
class patchCertificatesV1alpha1CertificateSigningRequest(K8sClient):
| 29 | 120 | 402 | 15 | 13 | blinkops/stackstorm-kubernetes | actions/patchCertificatesV1alpha1CertificateSigningRequest.py | Python | patchCertificatesV1alpha1CertificateSigningRequest | patchCertificatesV1alpha1CertificateSigningRequest | 6 | 55 | 6 | 7 | a15cedcd222cbf2812c5316786fe102831dc3a07 | bigcode/the-stack | train |
ccf62a4bdb24bc0905164ecf | train | function | def subsetTerbesar(inputList):
amountList = len(inputList)
result = []
list_index = []
biggest = 0
for i in range(amountList):
sums = 0
list_index = range(i, amountList, 2)
for j in list_index:
sums += inputList[j]
if sums > biggest:
... | def subsetTerbesar(inputList):
| amountList = len(inputList)
result = []
list_index = []
biggest = 0
for i in range(amountList):
sums = 0
list_index = range(i, amountList, 2)
for j in list_index:
sums += inputList[j]
if sums > biggest:
biggest = sums
for k i... | def subsetTerbesar(inputList):
| 7 | 64 | 139 | 7 | 0 | Mhmdaris15/free-python-project | Regular/Subset terbesar.py | Python | subsetTerbesar | subsetTerbesar | 1 | 19 | 1 | 1 | 19a3734cd044944872f58421558b8652395ca05b | bigcode/the-stack | train |
9d312bdf2a225a6c94a8a118 | train | function | @borg.on(admin_cmd(pattern=r"bid ?(.*)"))
async def bid(event):
giveVar = event.text
bid = giveVar[5]
if not bid:
bid = "😂"
await event.edit(
f"{bid}{bid}{bid}{bid}{bid}{bid}{bid}\n{bid}{bid}{bid}{bid}{bid}{bid}{bid}{bid}\n{bid}{bid} {bid}{bid}\n{bid}{bid} ... | @borg.on(admin_cmd(pattern=r"bid ?(.*)"))
async def bid(event):
| giveVar = event.text
bid = giveVar[5]
if not bid:
bid = "😂"
await event.edit(
f"{bid}{bid}{bid}{bid}{bid}{bid}{bid}\n{bid}{bid}{bid}{bid}{bid}{bid}{bid}{bid}\n{bid}{bid} {bid}{bid}\n{bid}{bid} {bid}{bid}\n{bid}{bid}{bid}{bid}{bid}{bid}{bid}{bid}\n... | from userbot.utils import admin_cmd
@borg.on(admin_cmd(pattern=r"bid ?(.*)"))
async def bid(event):
| 27 | 226 | 755 | 19 | 7 | yu9ohde/Marshmellow | userbot/plugins/Binod.py | Python | bid | bid | 3 | 11 | 3 | 4 | 6860a3a76aa0639d03fe3305046765eee48d9a1e | bigcode/the-stack | train |
3fbcafe9b13eb51f57592ce6 | train | class | @adt
class Either(Generic[L, R]):
LEFT: Case[L]
RIGHT: Case[R]
@property
def is_left(self) -> bool:
return self.match(left=lambda _: True, right=lambda _: False)
@property
def is_right(self) -> bool:
return not self.is_left
| @adt
class Either(Generic[L, R]):
| LEFT: Case[L]
RIGHT: Case[R]
@property
def is_left(self) -> bool:
return self.match(left=lambda _: True, right=lambda _: False)
@property
def is_right(self) -> bool:
return not self.is_left
| from typing import Generic, TypeVar
from adt import Case, adt
L = TypeVar("L")
R = TypeVar("R")
@adt
class Either(Generic[L, R]):
| 41 | 64 | 69 | 10 | 31 | tomcur/intervention | intervention/utils/data.py | Python | Either | Either | 9 | 20 | 9 | 10 | f1525db22d1cf251b25ea53a64e968879dc1acac | bigcode/the-stack | train |
7478fc8c9f6bd731aa43806a | train | function | def _dummy_op_logic(gdf, target_columns, _id="dummy", **kwargs):
cont_names = target_columns
if not cont_names:
return gdf
new_gdf = gdf[cont_names]
new_cols = [f"{col}_{_id}" for col in new_gdf.columns]
new_gdf.columns = new_cols
return new_gdf
| def _dummy_op_logic(gdf, target_columns, _id="dummy", **kwargs):
| cont_names = target_columns
if not cont_names:
return gdf
new_gdf = gdf[cont_names]
new_cols = [f"{col}_{_id}" for col in new_gdf.columns]
new_gdf.columns = new_cols
return new_gdf
| .conftest import allcols_csv, mycols_csv, mycols_pq, run_in_context
# Dummy operator logic to test stats
# TODO: Possibly add public API to add
# standalone Stat Ops
def _dummy_op_logic(gdf, target_columns, _id="dummy", **kwargs):
| 64 | 64 | 83 | 19 | 44 | davidxia/NVTabular | tests/unit/test_dask_nvt.py | Python | _dummy_op_logic | _dummy_op_logic | 37 | 44 | 37 | 37 | 6a064997c6a967270868ca026158ad897f027cfa | bigcode/the-stack | train |
f0fe3b5b9fc6f9ca0540ad46 | train | function | @pytest.mark.parametrize("part_mem_fraction", [0.01])
@pytest.mark.parametrize("use_client", [True, False])
def test_cats_and_groupby_stats(client, tmpdir, datasets, part_mem_fraction, use_client):
engine = "parquet"
paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
cat_names = ["name... | @pytest.mark.parametrize("part_mem_fraction", [0.01])
@pytest.mark.parametrize("use_client", [True, False])
def test_cats_and_groupby_stats(client, tmpdir, datasets, part_mem_fraction, use_client):
| engine = "parquet"
paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
cat_names = ["name-cat", "name-string"]
cont_names = ["x", "y", "id"]
cats = ColumnSelector(cat_names)
cat_features = cats >> ops.Categorify(out_path=str(tmpdir), freq_threshold=10, on_host=True)
gro... | _names=False)
assert_eq(df_check["name-cat_x_min"], df_check["min"], check_names=False)
assert_eq(df_check["name-cat_x_std"], df_check["std"], check_names=False)
@pytest.mark.parametrize("part_mem_fraction", [0.01])
@pytest.mark.parametrize("use_client", [True, False])
def test_cats_and_groupby_stats(client, tm... | 90 | 90 | 300 | 47 | 43 | davidxia/NVTabular | tests/unit/test_dask_nvt.py | Python | test_cats_and_groupby_stats | test_cats_and_groupby_stats | 178 | 205 | 178 | 180 | cce7a2351a2181a037e96592aad105e83a1da080 | bigcode/the-stack | train |
9a4657d53b8c84c640843f0c | train | function | @pytest.mark.parametrize("engine", ["parquet", "csv", "csv-no-header"])
@pytest.mark.parametrize("shuffle", [Shuffle.PER_WORKER, None])
@pytest.mark.parametrize("cpu", [None, True])
def test_dask_preproc_cpu(client, tmpdir, datasets, engine, shuffle, cpu):
paths = glob.glob(str(datasets[engine]) + "/*." + engine.sp... | @pytest.mark.parametrize("engine", ["parquet", "csv", "csv-no-header"])
@pytest.mark.parametrize("shuffle", [Shuffle.PER_WORKER, None])
@pytest.mark.parametrize("cpu", [None, True])
def test_dask_preproc_cpu(client, tmpdir, datasets, engine, shuffle, cpu):
| paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
if engine == "parquet":
df1 = cudf.read_parquet(paths[0])[mycols_pq]
df2 = cudf.read_parquet(paths[1])[mycols_pq]
elif engine == "csv":
df1 = cudf.read_csv(paths[0], header=0)[mycols_csv]
df2 = cudf.read_... | .means[name], rel_tol=1e-3)
assert math.isclose(stds[name], normalize.stds[name], rel_tol=1e-3)
# New (normalized) means should all be close to zero
new_means = result[cont_names].mean()
for name in cont_names:
assert new_means[name] < 1e-3
@pytest.mark.parametrize("engine", ["parquet", "cs... | 145 | 145 | 484 | 64 | 80 | davidxia/NVTabular | tests/unit/test_dask_nvt.py | Python | test_dask_preproc_cpu | test_dask_preproc_cpu | 241 | 280 | 241 | 244 | 92a54d1b3c88ab65c25e0cda93d4c02c85370dc3 | bigcode/the-stack | train |
d1001d42f77901d3113bd22a | train | function | @pytest.mark.parametrize("part_mem_fraction", [0.01])
def test_dask_groupby_stats(client, tmpdir, datasets, part_mem_fraction):
engine = "parquet"
paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
df1 = cudf.read_parquet(paths[0])[mycols_pq]
df2 = cudf.read_parquet(paths[1])[mycol... | @pytest.mark.parametrize("part_mem_fraction", [0.01])
def test_dask_groupby_stats(client, tmpdir, datasets, part_mem_fraction):
| engine = "parquet"
paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
df1 = cudf.read_parquet(paths[0])[mycols_pq]
df2 = cudf.read_parquet(paths[1])[mycols_pq]
df0 = cudf.concat([df1, df2], axis=0)
cat_names = ["name-cat", "name-string"]
cont_names = ["x", "y", "id"]
... | disk
if cpu:
df_disk = dd_read_parquet(output_path).compute()
else:
df_disk = dask_cudf.read_parquet(output_path).compute()
# we don't have a deterministic ordering here, especially when using
# a dask client with multiple workers - so we need to sort the values here
columns = ["la... | 157 | 157 | 524 | 31 | 126 | davidxia/NVTabular | tests/unit/test_dask_nvt.py | Python | test_dask_groupby_stats | test_dask_groupby_stats | 138 | 175 | 138 | 140 | d3b6a11b36f8c0a2320a2b018e6fb06fb4623ac2 | bigcode/the-stack | train |
5f835e6297ff3bf888dba7e4 | train | function | @pytest.mark.parametrize("part_mem_fraction", [0.1])
@pytest.mark.parametrize("engine", ["parquet", "csv", "csv-no-header"])
@pytest.mark.parametrize("freq_threshold", [0, 150])
@pytest.mark.parametrize("cat_cache", ["device", None])
@pytest.mark.parametrize("on_host", [True, False])
@pytest.mark.parametrize("shuffle",... | @pytest.mark.parametrize("part_mem_fraction", [0.1])
@pytest.mark.parametrize("engine", ["parquet", "csv", "csv-no-header"])
@pytest.mark.parametrize("freq_threshold", [0, 150])
@pytest.mark.parametrize("cat_cache", ["device", None])
@pytest.mark.parametrize("on_host", [True, False])
@pytest.mark.parametrize("shuffle",... | paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
paths = sorted(paths)
if engine == "parquet":
df1 = cudf.read_parquet(paths[0])[mycols_pq]
df2 = cudf.read_parquet(paths[1])[mycols_pq]
elif engine == "csv":
df1 = cudf.read_csv(paths[0], header=0)[mycols_csv... | cols_pq, run_in_context
# Dummy operator logic to test stats
# TODO: Possibly add public API to add
# standalone Stat Ops
def _dummy_op_logic(gdf, target_columns, _id="dummy", **kwargs):
cont_names = target_columns
if not cont_names:
return gdf
new_gdf = gdf[cont_names]
new_cols = [f"{co... | 256 | 256 | 979 | 141 | 114 | davidxia/NVTabular | tests/unit/test_dask_nvt.py | Python | test_dask_workflow_api_dlrm | test_dask_workflow_api_dlrm | 47 | 135 | 47 | 65 | 7833a2b9c8566261110a13f0984b1bf387796cbe | bigcode/the-stack | train |
744092051e19172eed65bf03 | train | function | @pytest.mark.parametrize("engine", ["parquet"])
@pytest.mark.parametrize("cpu", [None, True])
def test_dask_normalize(client, tmpdir, datasets, engine, cpu):
paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
df1 = cudf.read_parquet(paths[0])[mycols_pq]
df2 = cudf.read_parquet(paths[1]... | @pytest.mark.parametrize("engine", ["parquet"])
@pytest.mark.parametrize("cpu", [None, True])
def test_dask_normalize(client, tmpdir, datasets, engine, cpu):
| paths = glob.glob(str(datasets[engine]) + "/*." + engine.split("-")[0])
df1 = cudf.read_parquet(paths[0])[mycols_pq]
df2 = cudf.read_parquet(paths[1])[mycols_pq]
df0 = cudf.concat([df1, df2], axis=0)
cat_names = ["name-cat", "name-string"]
cont_names = ["x", "y", "id"]
label_name = ["label"... | client=client if use_client else None,
)
dataset = Dataset(paths, part_mem_fraction=part_mem_fraction)
result = workflow.fit_transform(dataset).to_ddf().compute()
assert "name-cat_x_sum" in result.columns
assert "name-string_x_sum" in result.columns
@pytest.mark.parametrize("engine", ["parq... | 102 | 102 | 341 | 38 | 63 | davidxia/NVTabular | tests/unit/test_dask_nvt.py | Python | test_dask_normalize | test_dask_normalize | 208 | 238 | 208 | 211 | 46245944589adcdc72588c04709cd616badc03b3 | bigcode/the-stack | train |
61846085b2084e2301c1adba | train | function | @pytest.mark.parametrize("cpu", [None, True])
def test_filtered_partition(tmpdir, cpu):
# Toy DataFrame example
df = pd.DataFrame({"col": range(100)})
ddf = dd_from_pandas(df, npartitions=5)
dataset = Dataset(ddf, cpu=cpu)
# Workflow
filtered = ["col"] >> ops.Filter(lambda df: df["col"] < 75)
... | @pytest.mark.parametrize("cpu", [None, True])
def test_filtered_partition(tmpdir, cpu):
# Toy DataFrame example
| df = pd.DataFrame({"col": range(100)})
ddf = dd_from_pandas(df, npartitions=5)
dataset = Dataset(ddf, cpu=cpu)
# Workflow
filtered = ["col"] >> ops.Filter(lambda df: df["col"] < 75)
workflow = Workflow(filtered)
# Write result to disk
workflow.transform(dataset).to_parquet(str(tmpdir))... | "x"])[["name-string", "label"]],
df_disk.sort_values(["id", "x"])[["name-string", "label"]],
check_index=False,
)
@pytest.mark.parametrize("cpu", [None, True])
def test_filtered_partition(tmpdir, cpu):
# Toy DataFrame example
| 64 | 64 | 116 | 27 | 37 | davidxia/NVTabular | tests/unit/test_dask_nvt.py | Python | test_filtered_partition | test_filtered_partition | 283 | 295 | 283 | 285 | 6df4b730e0ea318a316b14a69c9376a0da76d967 | bigcode/the-stack | train |
31d87722ee31f53c03893666 | train | function | def load_data(filename: str):
"""
Load Agoda booking cancellation dataset
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector in either of the following formats:
1) Single dataframe with last column representing ... | def load_data(filename: str):
| """
Load Agoda booking cancellation dataset
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector in either of the following formats:
1) Single dataframe with last column representing the response
2) Tuple of p... | from challenge.agoda_cancellation_estimator import AgodaCancellationEstimator
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
from IMLearn.base import BaseEstimator
def load_data(filename: str):
| 49 | 64 | 172 | 7 | 41 | edenmelman/IML.HUJI | challenge/agoda_cancellation_prediction.py | Python | load_data | load_data | 9 | 32 | 9 | 9 | 2e1da8b845140fa05ac88fc2bf3b5c61fded8fd4 | bigcode/the-stack | train |
3e23b4d518e2857705d4194a | train | function | def evaluate_and_export(estimator: BaseEstimator, X: np.ndarray, filename: str):
"""
Export to specified file the prediction results of given estimator on given testset.
File saved is in csv format with a single column named 'predicted_values' and n_samples rows containing
predicted values.
Parame... | def evaluate_and_export(estimator: BaseEstimator, X: np.ndarray, filename: str):
| """
Export to specified file the prediction results of given estimator on given testset.
File saved is in csv format with a single column named 'predicted_values' and n_samples rows containing
predicted values.
Parameters
----------
estimator: BaseEstimator or any object implementing predi... | ",
"hotel_id",
"accommadation_type_name",
"hotel_star_rating",
"customer_nationality"]]
labels = full_data["cancellation_datetime"]
return features, labels
def evaluate_and_export(estimator: BaseEstimator, X... | 64 | 64 | 155 | 19 | 44 | edenmelman/IML.HUJI | challenge/agoda_cancellation_prediction.py | Python | evaluate_and_export | evaluate_and_export | 35 | 54 | 35 | 35 | c97aa8b9a3905d68143c0af96528b058a3dbe7db | bigcode/the-stack | train |
a0cd3245c9ace171bf367640 | train | function | def make_nb_list(cleansing, load, nb_list, train, transform):
for stage in [load, cleansing, transform, train]:
if stage:
nb_list.append(stage)
else:
break
| def make_nb_list(cleansing, load, nb_list, train, transform):
| for stage in [load, cleansing, transform, train]:
if stage:
nb_list.append(stage)
else:
break
| 8') as nb:
sub_nb = json.load(nb)
if i == 0:
combined_nb = sub_nb
else:
combined_nb['cells'].extend(sub_nb['cells'])
return combined_nb
def make_nb_list(cleansing, load, nb_list, train, transform):
| 64 | 64 | 46 | 17 | 46 | zalman0813/jupyter_notebook_handling | nb_handling.py | Python | make_nb_list | make_nb_list | 29 | 34 | 29 | 29 | 6a50ff0ca22b4bc777d3991a1eb7fa7b860a3293 | bigcode/the-stack | train |
f8931fc4d29a1665b1230b73 | train | function | def initiate_nb(first_stage, source_nb):
nb = {}
nb['cells'] = [first_stage]
nb['metadata'] = source_nb['metadata']
nb['nbformat'] = 4
nb['nbformat_minor'] = 2
return nb
| def initiate_nb(first_stage, source_nb):
| nb = {}
nb['cells'] = [first_stage]
nb['metadata'] = source_nb['metadata']
nb['nbformat'] = 4
nb['nbformat_minor'] = 2
return nb
| _name)
nb['cells'] = [cell]
else:
nb['cells'].extend([cell])
with open(output_path, mode = 'w', encoding='utf-8') as f:
json.dump(nb, f)
print(output_path)
def initiate_nb(first_stage, source_nb):
| 64 | 64 | 59 | 9 | 55 | zalman0813/jupyter_notebook_handling | nb_handling.py | Python | initiate_nb | initiate_nb | 61 | 67 | 61 | 61 | a417cb15a2a4d59884109905e2375cec97a82592 | bigcode/the-stack | train |
42db92c8ba44db4981561280 | train | function | def decompose_nb_stages(file_name='', output_folder='', markdown_header='STAGE'):
current_path = os.getcwd()
with open(file_name, mode = 'r', encoding='utf-8') as f:
source_nb = json.load(f)
first_stage = source_nb['cells'][0]
nb = initiate_nb(first_stage, source_nb)
decomposed_nb_file_name ... | def decompose_nb_stages(file_name='', output_folder='', markdown_header='STAGE'):
| current_path = os.getcwd()
with open(file_name, mode = 'r', encoding='utf-8') as f:
source_nb = json.load(f)
first_stage = source_nb['cells'][0]
nb = initiate_nb(first_stage, source_nb)
decomposed_nb_file_name = first_stage['source'][0][3:].split(' ')[-1] + '.ipynb'
output_path = os.path... | _nb = sub_nb
else:
combined_nb['cells'].extend(sub_nb['cells'])
return combined_nb
def make_nb_list(cleansing, load, nb_list, train, transform):
for stage in [load, cleansing, transform, train]:
if stage:
nb_list.append(stage)
else:
break
def... | 89 | 89 | 299 | 18 | 70 | zalman0813/jupyter_notebook_handling | nb_handling.py | Python | decompose_nb_stages | decompose_nb_stages | 37 | 58 | 37 | 37 | 4bfd9076aad3c40ec84b398833309394b4c048dc | bigcode/the-stack | train |
e55b51f0fc686bd31dc037d7 | train | function | def nbmerge(load='', cleansing=None, transform=None, train=None, output="nbmerge.ipynb"):
if os.path.isfile(load):
nb_list = []
make_nb_list(cleansing, load, nb_list, train, transform)
combined_nb = generated_combined_nb(nb_list)
with open(output, mode='w', encoding='utf-8') as f:
... | def nbmerge(load='', cleansing=None, transform=None, train=None, output="nbmerge.ipynb"):
| if os.path.isfile(load):
nb_list = []
make_nb_list(cleansing, load, nb_list, train, transform)
combined_nb = generated_combined_nb(nb_list)
with open(output, mode='w', encoding='utf-8') as f:
json.dump(combined_nb, f)
else:
print("load is a required parameter"... | #!/usr/bin/env python
import os
import fire
import json
def nbmerge(load='', cleansing=None, transform=None, train=None, output="nbmerge.ipynb"):
| 37 | 64 | 101 | 22 | 14 | zalman0813/jupyter_notebook_handling | nb_handling.py | Python | nbmerge | nbmerge | 7 | 15 | 7 | 7 | 92058dda33d07bb18625cf28c7504664ec80d5aa | bigcode/the-stack | train |
cbe6f943ed1279c7b839e16a | train | function | def generated_combined_nb(nb_list):
for i, notebook in enumerate(nb_list):
with open(notebook, mode='r', encoding='utf-8') as nb:
sub_nb = json.load(nb)
if i == 0:
combined_nb = sub_nb
else:
combined_nb['cells'].extend(sub_nb['cells'])
... | def generated_combined_nb(nb_list):
| for i, notebook in enumerate(nb_list):
with open(notebook, mode='r', encoding='utf-8') as nb:
sub_nb = json.load(nb)
if i == 0:
combined_nb = sub_nb
else:
combined_nb['cells'].extend(sub_nb['cells'])
return combined_nb
| _list, train, transform)
combined_nb = generated_combined_nb(nb_list)
with open(output, mode='w', encoding='utf-8') as f:
json.dump(combined_nb, f)
else:
print("load is a required parameter")
def generated_combined_nb(nb_list):
| 64 | 64 | 79 | 8 | 56 | zalman0813/jupyter_notebook_handling | nb_handling.py | Python | generated_combined_nb | generated_combined_nb | 18 | 26 | 18 | 18 | bdab3af8e7ffe18df6670cbc18a86ab720a6dd2a | bigcode/the-stack | train |
a7c244916fa8003b6ea8e360 | train | class | class Cli():
def __init__(self):
self.nbmerge = nbmerge
self.nbdecompose = decompose_nb_stages
| class Cli():
| def __init__(self):
self.nbmerge = nbmerge
self.nbdecompose = decompose_nb_stages
| _path)
def initiate_nb(first_stage, source_nb):
nb = {}
nb['cells'] = [first_stage]
nb['metadata'] = source_nb['metadata']
nb['nbformat'] = 4
nb['nbformat_minor'] = 2
return nb
class Cli():
| 64 | 64 | 30 | 3 | 60 | zalman0813/jupyter_notebook_handling | nb_handling.py | Python | Cli | Cli | 70 | 74 | 70 | 71 | 4ecb1ff00f049eb35c7e02e955e71e45c2fffdcc | bigcode/the-stack | train |
0f7b0ddc49dd7f951e0e4c90 | train | function | def _card_template_id_to_string(card_template_id):
from manabi.apps.flashcards.models import (
PRODUCTION, RECOGNITION, KANJI_READING, KANJI_WRITING)
return {
PRODUCTION: 'production',
RECOGNITION: 'recognition',
KANJI_READING: 'kanji_reading',
KANJI_WRITING: 'kanji_writ... | def _card_template_id_to_string(card_template_id):
| from manabi.apps.flashcards.models import (
PRODUCTION, RECOGNITION, KANJI_READING, KANJI_WRITING)
return {
PRODUCTION: 'production',
RECOGNITION: 'recognition',
KANJI_READING: 'kanji_reading',
KANJI_WRITING: 'kanji_writing',
}[card_template_id]
| expression,
reading=reading,
meaning=meaning,
reader_source=reader_source,
example_sentence=example_sentence or '',
jmdict_id=jmdict_id,
)
fact.set_active_card_templates(active_card_templates)
return fact
def _c... | 64 | 64 | 95 | 11 | 52 | aehlke/manabi | manabi/apps/flashcards/models/facts.py | Python | _card_template_id_to_string | _card_template_id_to_string | 150 | 159 | 150 | 150 | 4968774318bc8bcc3bef5b0fc75ba025771cd976 | bigcode/the-stack | train |
8eb3c80fed164fb07b5525e9 | train | class | class FactQuerySet(QuerySet):
def deck_facts(self, deck):
return self.filter(deck=deck)
def buried(self, user, review_time=None, excluded_card_ids=[]):
'''
Facts with cards buried due to siblings.
'''
if review_time is None:
review_time = datetime.utcnow()
... | class FactQuerySet(QuerySet):
| def deck_facts(self, deck):
return self.filter(deck=deck)
def buried(self, user, review_time=None, excluded_card_ids=[]):
'''
Facts with cards buried due to siblings.
'''
if review_time is None:
review_time = datetime.utcnow()
return self.filter(
... | from datetime import datetime, timedelta
import random
from django.db.models import Prefetch
from django.db.models.query import QuerySet
from django.contrib.auth.models import User
from django.db import models, transaction
from django.db.models import Q, F
from django.utils.functional import cached_property
from natto... | 232 | 239 | 799 | 7 | 225 | aehlke/manabi | manabi/apps/flashcards/models/facts.py | Python | FactQuerySet | FactQuerySet | 31 | 147 | 31 | 31 | a1f641e6356d9b33e3e532bb9a9c291dfbb61aea | bigcode/the-stack | train |
a944e0bbef98ef692f2e1973 | train | function | def _card_template_string_to_id(card_template):
from manabi.apps.flashcards.models import (
PRODUCTION, RECOGNITION, KANJI_READING, KANJI_WRITING)
return {
'production': PRODUCTION,
'recognition': RECOGNITION,
'kanji_reading': KANJI_READING,
'kanji_writing': KANJI_WRITIN... | def _card_template_string_to_id(card_template):
| from manabi.apps.flashcards.models import (
PRODUCTION, RECOGNITION, KANJI_READING, KANJI_WRITING)
return {
'production': PRODUCTION,
'recognition': RECOGNITION,
'kanji_reading': KANJI_READING,
'kanji_writing': KANJI_WRITING,
}[card_template]
| )
return {
PRODUCTION: 'production',
RECOGNITION: 'recognition',
KANJI_READING: 'kanji_reading',
KANJI_WRITING: 'kanji_writing',
}[card_template_id]
def _card_template_string_to_id(card_template):
| 64 | 64 | 93 | 10 | 54 | aehlke/manabi | manabi/apps/flashcards/models/facts.py | Python | _card_template_string_to_id | _card_template_string_to_id | 162 | 171 | 162 | 162 | 3e34c7248385f1f67953c31afc15ceeac92a014f | bigcode/the-stack | train |
d9a7403f210223831b25404e | train | class | class Fact(models.Model):
objects = FactQuerySet.as_manager()
deck = models.ForeignKey(
'flashcards.Deck', models.CASCADE, db_index=True, related_name='facts')
synchronized_with = models.ForeignKey(
'self', models.CASCADE,
null=True, blank=True, related_name='subscriber_facts')
... | class Fact(models.Model):
| objects = FactQuerySet.as_manager()
deck = models.ForeignKey(
'flashcards.Deck', models.CASCADE, db_index=True, related_name='facts')
synchronized_with = models.ForeignKey(
'self', models.CASCADE,
null=True, blank=True, related_name='subscriber_facts')
forked = models.BooleanFi... | .create(
deck=deck,
expression=expression,
reading=reading,
meaning=meaning,
reader_source=reader_source,
example_sentence=example_sentence or '',
jmdict_id=jmdict_id,
)
fact.set_active_c... | 256 | 256 | 2,094 | 5 | 251 | aehlke/manabi | manabi/apps/flashcards/models/facts.py | Python | Fact | Fact | 174 | 497 | 174 | 174 | 25f6883ba8a6475de880991cb67fffe9606d960b | bigcode/the-stack | train |
2d517af91eefa42c27f2aebd | train | class | class TestServerInfo(IntegrationTestCase):
@test_async_and_sync(globals())
async def test_basic_functionality(self, client):
response = await client.request(ServerInfo())
self.assertTrue(response.is_successful())
| class TestServerInfo(IntegrationTestCase):
@test_async_and_sync(globals())
| async def test_basic_functionality(self, client):
response = await client.request(ServerInfo())
self.assertTrue(response.is_successful())
| from tests.integration.integration_test_case import IntegrationTestCase
from tests.integration.it_utils import test_async_and_sync
from xrpl.models.requests import ServerInfo
class TestServerInfo(IntegrationTestCase):
@test_async_and_sync(globals())
| 49 | 64 | 47 | 18 | 30 | SubCODERS/xrpl-py | tests/integration/reqs/test_server_info.py | Python | TestServerInfo | TestServerInfo | 6 | 10 | 6 | 7 | 38e0301fa6eadce4fcb94c7fec0884ce88fb902e | bigcode/the-stack | train |
016e2c372c7368d19af51a04 | train | function | def detectKeyPoints(detect_image):
detector = cv2.AKAZE_create()
keypoints = detector.detect(detect_image)
return keypoints
| def detectKeyPoints(detect_image):
| detector = cv2.AKAZE_create()
keypoints = detector.detect(detect_image)
return keypoints
| import os
import glob
import argparse
import cv2
def detectKeyPoints(detect_image):
| 21 | 64 | 34 | 8 | 12 | toshikaz55/detectKeyPoints | detect_keypoints.py | Python | detectKeyPoints | detectKeyPoints | 7 | 12 | 7 | 8 | fbc47e9575d8dfe9dad12c9c7204d39cafe16d39 | bigcode/the-stack | train |
60ff45b18100d6edc1573dd0 | train | function | def around_import(snip):
return 'import' in snip.buffer[snip.line]
| def around_import(snip):
| return 'import' in snip.buffer[snip.line]
| ip.line - 1])
def around_for(snip):
return 'for' in snip.buffer[snip.line]
def around_function(snip):
return re.search('=>|function|^\s+\w+\(.*\)', snip.buffer[snip.line])
def around_import(snip):
| 64 | 64 | 20 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_import | around_import | 32 | 33 | 32 | 32 | b1bc5b551158802d8a24fc30d7fa0c339c695471 | bigcode/the-stack | train |
2087723981b088ca7225e990 | train | function | def around_catch(snip):
return 'catch' in snip.buffer[snip.line - 1]
| def around_catch(snip):
| return 'catch' in snip.buffer[snip.line - 1]
| import re
import os
import vim
def around_assign(snip):
return '=' in snip.buffer[snip.line]
def around_catch(snip):
| 34 | 64 | 24 | 7 | 27 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_catch | around_catch | 8 | 9 | 8 | 8 | 5edc89f71ea893229c376cc2a0817bfe51203797 | bigcode/the-stack | train |
9a6f737a65eb4c73f0963309 | train | function | def to_camel(text):
return re.sub('[-_]([a-zA-Z0-9])', lambda m: m.group(1).upper(), text)
| def to_camel(text):
| return re.sub('[-_]([a-zA-Z0-9])', lambda m: m.group(1).upper(), text)
| line('.') . '\"'")
def singularize(plural):
return re.sub('(?<!e)es|s$', '', plural)
def singularize_idx(plural):
return singularize(plural) + 'Idx' if len(plural) > 0 else plural
def to_camel(text):
| 64 | 64 | 35 | 6 | 57 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | to_camel | to_camel | 69 | 70 | 69 | 69 | cae7fbaf5bf7640555c4ff5600b1bffe8208acb4 | bigcode/the-stack | train |
81837abca545db31d001b38d | train | function | def singularize_idx(plural):
return singularize(plural) + 'Idx' if len(plural) > 0 else plural
| def singularize_idx(plural):
| return singularize(plural) + 'Idx' if len(plural) > 0 else plural
| ('\..*', '', os.path.basename(path)))
def path_and_line():
return vim.eval("'\"'. expand('%') . ':' . line('.') . '\"'")
def singularize(plural):
return re.sub('(?<!e)es|s$', '', plural)
def singularize_idx(plural):
| 64 | 64 | 29 | 7 | 57 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | singularize_idx | singularize_idx | 66 | 67 | 66 | 66 | 8dc7e1c1cc5dc929d4fcb85cd726aead0412fabf | bigcode/the-stack | train |
fb702d304512b4f6c53cd7d9 | train | function | def around_first_line_or_require(snip):
return 'const' not in snip.buffer[snip.line] and (snip.line == 0 or 'require' in snip.buffer[snip.line - 1])
| def around_first_line_or_require(snip):
| return 'const' not in snip.buffer[snip.line] and (snip.line == 0 or 'require' in snip.buffer[snip.line - 1])
| ip.line]) and '=' not in snip.buffer[snip.line]
def around_expect(snip):
return 'expect' in snip.buffer[snip.line]
def around_export(snip):
return 'export' in snip.buffer[snip.line]
def around_first_line_or_require(snip):
| 64 | 64 | 48 | 9 | 55 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_first_line_or_require | around_first_line_or_require | 23 | 24 | 23 | 23 | 1fffcb092ae3c8700a03f8a820a51976f30a711a | bigcode/the-stack | train |
bb496112ce6df840edc808f7 | train | function | def around_expect(snip):
return 'expect' in snip.buffer[snip.line]
| def around_expect(snip):
| return 'expect' in snip.buffer[snip.line]
| _class(snip):
return 'class' in snip.buffer[snip.line]
def around_const_let_var(snip):
return re.search('const|let|var', snip.buffer[snip.line]) and '=' not in snip.buffer[snip.line]
def around_expect(snip):
| 64 | 64 | 20 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_expect | around_expect | 17 | 18 | 17 | 17 | fb3eef18bbce4da601bb6241e8a2631b6aebbbda | bigcode/the-stack | train |
36d2453aaea52e388a6029e6 | train | function | def around_const_let_var(snip):
return re.search('const|let|var', snip.buffer[snip.line]) and '=' not in snip.buffer[snip.line]
| def around_const_let_var(snip):
| return re.search('const|let|var', snip.buffer[snip.line]) and '=' not in snip.buffer[snip.line]
| return '=' in snip.buffer[snip.line]
def around_catch(snip):
return 'catch' in snip.buffer[snip.line - 1]
def around_class(snip):
return 'class' in snip.buffer[snip.line]
def around_const_let_var(snip):
| 64 | 64 | 40 | 9 | 55 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_const_let_var | around_const_let_var | 14 | 15 | 14 | 14 | 861cf8fae3cecc9e8ce181bbb02cd5941f4e7189 | bigcode/the-stack | train |
33ef11ed35dcf68556b43f16 | train | function | def around_regex(snip):
return re.search('/.+/', snip.buffer[snip.line])
| def around_regex(snip):
| return re.search('/.+/', snip.buffer[snip.line])
| |function|^\s+\w+\(.*\)', snip.buffer[snip.line])
def around_import(snip):
return 'import' in snip.buffer[snip.line]
def around_json_parse(snip):
return 'JSON.parse' in snip.v
def around_regex(snip):
| 64 | 64 | 21 | 6 | 57 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_regex | around_regex | 38 | 39 | 38 | 38 | ade7c86c6c564ea98cafb871ec93ca0acb3008dd | bigcode/the-stack | train |
d22463bed9c536c0a1102db6 | train | function | def around_switch(snip):
return re.search('break|switch', snip.buffer[snip.line - 1]) or (
snip.line - 2 >= 0 and
'case' in snip.buffer[snip.line - 2] and
'return' in snip.buffer[snip.line - 1]
)
| def around_switch(snip):
| return re.search('break|switch', snip.buffer[snip.line - 1]) or (
snip.line - 2 >= 0 and
'case' in snip.buffer[snip.line - 2] and
'return' in snip.buffer[snip.line - 1]
)
| around_json_parse(snip):
return 'JSON.parse' in snip.v
def around_regex(snip):
return re.search('/.+/', snip.buffer[snip.line])
def around_require(snip):
return 'require' in snip.buffer[snip.line]
def around_switch(snip):
| 64 | 64 | 76 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_switch | around_switch | 44 | 49 | 44 | 44 | b85a9817ecf0be46cdc8bdb0bdd03fbc39736883 | bigcode/the-stack | train |
775f8e3d011caa292cd724f3 | train | function | def around_template_string(snip):
return '`' in snip.buffer[snip.line]
| def around_template_string(snip):
| return '`' in snip.buffer[snip.line]
| snip.line - 1]) or (
snip.line - 2 >= 0 and
'case' in snip.buffer[snip.line - 2] and
'return' in snip.buffer[snip.line - 1]
)
def around_template_string(snip):
| 64 | 64 | 20 | 7 | 57 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_template_string | around_template_string | 51 | 52 | 51 | 51 | d37e37dc869cee0976b9fec29cdf171e49e37188 | bigcode/the-stack | train |
b09852ea0106d371c9dc2f5f | train | function | def around_assign(snip):
return '=' in snip.buffer[snip.line]
| def around_assign(snip):
| return '=' in snip.buffer[snip.line]
| import re
import os
import vim
def around_assign(snip):
| 15 | 64 | 18 | 6 | 8 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_assign | around_assign | 5 | 6 | 5 | 5 | 3eb3fa8f6aa58886ae0c84f718e7b1081dd4aa4a | bigcode/the-stack | train |
f1793fca35e2055ff27f6ca9 | train | function | def around_throw(snip):
return 'throw' in snip.buffer[snip.line]
| def around_throw(snip):
| return 'throw' in snip.buffer[snip.line]
| and
'case' in snip.buffer[snip.line - 2] and
'return' in snip.buffer[snip.line - 1]
)
def around_template_string(snip):
return '`' in snip.buffer[snip.line]
def around_throw(snip):
| 64 | 64 | 20 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_throw | around_throw | 54 | 55 | 54 | 54 | 4a3c42efed0d04dacde04ccb5b86da4208f5b929 | bigcode/the-stack | train |
d034a583010039e877be82d0 | train | function | def singularize(plural):
return re.sub('(?<!e)es|s$', '', plural)
| def singularize(plural):
| return re.sub('(?<!e)es|s$', '', plural)
| throw' in snip.buffer[snip.line]
def importname(path):
return to_camel(re.sub('\..*', '', os.path.basename(path)))
def path_and_line():
return vim.eval("'\"'. expand('%') . ':' . line('.') . '\"'")
def singularize(plural):
| 63 | 64 | 22 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | singularize | singularize | 63 | 64 | 63 | 63 | 053ffdb37c0a34f369c7086d512aa2cfac064f28 | bigcode/the-stack | train |
64e9197720128056560ccceb | train | function | def around_json_parse(snip):
return 'JSON.parse' in snip.v
| def around_json_parse(snip):
| return 'JSON.parse' in snip.v
| [snip.line]
def around_function(snip):
return re.search('=>|function|^\s+\w+\(.*\)', snip.buffer[snip.line])
def around_import(snip):
return 'import' in snip.buffer[snip.line]
def around_json_parse(snip):
| 64 | 64 | 18 | 7 | 57 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_json_parse | around_json_parse | 35 | 36 | 35 | 35 | 1fe405d85aa7b17fa9f7a6517d7f9f822237f557 | bigcode/the-stack | train |
75d1f82f2b910617c90db3d9 | train | function | def around_function(snip):
return re.search('=>|function|^\s+\w+\(.*\)', snip.buffer[snip.line])
| def around_function(snip):
| return re.search('=>|function|^\s+\w+\(.*\)', snip.buffer[snip.line])
| return 'const' not in snip.buffer[snip.line] and (snip.line == 0 or 'require' in snip.buffer[snip.line - 1])
def around_for(snip):
return 'for' in snip.buffer[snip.line]
def around_function(snip):
| 64 | 64 | 32 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_function | around_function | 29 | 30 | 29 | 29 | bc0ef4a43ecee4c4a79c0312a75f10e38e8c3671 | bigcode/the-stack | train |
2f64f6ebb26078a592b64c80 | train | function | def around_export(snip):
return 'export' in snip.buffer[snip.line]
| def around_export(snip):
| return 'export' in snip.buffer[snip.line]
| _const_let_var(snip):
return re.search('const|let|var', snip.buffer[snip.line]) and '=' not in snip.buffer[snip.line]
def around_expect(snip):
return 'expect' in snip.buffer[snip.line]
def around_export(snip):
| 64 | 64 | 20 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_export | around_export | 20 | 21 | 20 | 20 | 4cf8339d12b7f7cc6acef6d2359f765b08425b3b | bigcode/the-stack | train |
ebe4dce53d741160a66f6df8 | train | function | def around_for(snip):
return 'for' in snip.buffer[snip.line]
| def around_for(snip):
| return 'for' in snip.buffer[snip.line]
| ' in snip.buffer[snip.line]
def around_first_line_or_require(snip):
return 'const' not in snip.buffer[snip.line] and (snip.line == 0 or 'require' in snip.buffer[snip.line - 1])
def around_for(snip):
| 64 | 64 | 20 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_for | around_for | 26 | 27 | 26 | 26 | 62718a6d3e95dd29e57f98812f6fa825eef45075 | bigcode/the-stack | train |
6f0754a424e5e68014e9e1a9 | train | function | def path_and_line():
return vim.eval("'\"'. expand('%') . ':' . line('.') . '\"'")
| def path_and_line():
| return vim.eval("'\"'. expand('%') . ':' . line('.') . '\"'")
| _string(snip):
return '`' in snip.buffer[snip.line]
def around_throw(snip):
return 'throw' in snip.buffer[snip.line]
def importname(path):
return to_camel(re.sub('\..*', '', os.path.basename(path)))
def path_and_line():
| 64 | 64 | 24 | 5 | 59 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | path_and_line | path_and_line | 60 | 61 | 60 | 60 | 6a7528a7c9b1fb21878b7017fffefd307f488991 | bigcode/the-stack | train |
695dc0818d82446e8f16877a | train | function | def importname(path):
return to_camel(re.sub('\..*', '', os.path.basename(path)))
| def importname(path):
| return to_camel(re.sub('\..*', '', os.path.basename(path)))
|
'return' in snip.buffer[snip.line - 1]
)
def around_template_string(snip):
return '`' in snip.buffer[snip.line]
def around_throw(snip):
return 'throw' in snip.buffer[snip.line]
def importname(path):
| 64 | 64 | 22 | 5 | 59 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | importname | importname | 57 | 58 | 57 | 57 | 85f5036d463c2abac69c5094b188e4cb39b62a62 | bigcode/the-stack | train |
c3bcafb6573c13a17e47b43c | train | function | def around_require(snip):
return 'require' in snip.buffer[snip.line]
| def around_require(snip):
| return 'require' in snip.buffer[snip.line]
| around_import(snip):
return 'import' in snip.buffer[snip.line]
def around_json_parse(snip):
return 'JSON.parse' in snip.v
def around_regex(snip):
return re.search('/.+/', snip.buffer[snip.line])
def around_require(snip):
| 64 | 64 | 20 | 6 | 58 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_require | around_require | 41 | 42 | 41 | 41 | 89b61e240477667dca93f036c0817aea6764c341 | bigcode/the-stack | train |
e50e732714004300b273e0d9 | train | function | def around_class(snip):
return 'class' in snip.buffer[snip.line]
| def around_class(snip):
| return 'class' in snip.buffer[snip.line]
| import re
import os
import vim
def around_assign(snip):
return '=' in snip.buffer[snip.line]
def around_catch(snip):
return 'catch' in snip.buffer[snip.line - 1]
def around_class(snip):
| 57 | 64 | 20 | 6 | 51 | sharils/home | .vim/plugged/after/pythonx/my_snippet_helpers.py | Python | around_class | around_class | 11 | 12 | 11 | 11 | a1216e6dfc770f196d3db6c1947a1203dc71305f | bigcode/the-stack | train |
3db79017806d8e3d71c19563 | train | class | class DatasetGenerator:
_implimented_freqs = ["month", "quarter"]
def __init__(self, data_list: str, stock_path: str, sec_path: str, freq: str):
self.data_list = data_list
self.stock_df = pd.read_csv(
stock_path,
usecols=["ticker_symbol", "date", "Close"],
pa... | class DatasetGenerator:
| _implimented_freqs = ["month", "quarter"]
def __init__(self, data_list: str, stock_path: str, sec_path: str, freq: str):
self.data_list = data_list
self.stock_df = pd.read_csv(
stock_path,
usecols=["ticker_symbol", "date", "Close"],
parse_dates=["date"],
... | import os
from glob import glob
import numpy as np
import pandas as pd
import torch
from torch_geometric.utils import dense_to_sparse
from torch_geometric.utils import dense_to_sparse
from torch_geometric_temporal.signal import DynamicGraphTemporalSignal
from sklearn.preprocessing import normalize
class DatasetGenerato... | 64 | 256 | 869 | 4 | 59 | syeehyn/spug | spug/dataset/dataset_generator.py | Python | DatasetGenerator | DatasetGenerator | 12 | 114 | 12 | 12 | 5e8280ea9c874ea862724607e759850fea17e8ed | bigcode/the-stack | train |
7395c449e4c0b4002abf022c | train | class | class TestTRPOAgent(BaseAgentTest, unittest.TestCase):
agent = TRPOAgent
deterministic = False
config = Configuration(
batch_size=64,
normalize_rewards=True
)
| class TestTRPOAgent(BaseAgentTest, unittest.TestCase):
| agent = TRPOAgent
deterministic = False
config = Configuration(
batch_size=64,
normalize_rewards=True
)
| __ import absolute_import
from __future__ import print_function
from __future__ import division
import unittest
from tensorforce import Configuration
from tensorforce.agents import TRPOAgent
from tensorforce.tests.base_agent_test import BaseAgentTest
class TestTRPOAgent(BaseAgentTest, unittest.TestCase):
| 64 | 64 | 43 | 13 | 50 | ekerazha/tensorforce | tensorforce/tests/test_trpo_agent.py | Python | TestTRPOAgent | TestTRPOAgent | 27 | 34 | 27 | 28 | 4263dcc55e2afe82517d17a52cc220d5f70cfe16 | bigcode/the-stack | train |
5e802fce5a614555cae88fef | train | class | class MatchingHash(FileHash):
def __init__(self):
return super().__init__('', '')
def __eq__(self, other):
return True
| class MatchingHash(FileHash):
| def __init__(self):
return super().__init__('', '')
def __eq__(self, other):
return True
| from unittest import mock
from .utils import config_from_parts_or_dicts, normalize
from dbt.contracts.files import SourceFile, FileHash, FilePath
from dbt.parser import ParseResult
from dbt.parser.search import FileBlock
from dbt.parser import manifest
class MatchingHash(FileHash):
| 64 | 64 | 35 | 6 | 57 | joelluijmes/dbt | test/unit/test_parse_manifest.py | Python | MatchingHash | MatchingHash | 12 | 17 | 12 | 12 | 150f30e5d5c2d069419b0187acb3af222b59653b | bigcode/the-stack | train |
22fe174afd099d30bc99f3cb | train | class | class TestLoader(unittest.TestCase):
def setUp(self):
profile_data = {
'target': 'test',
'quoting': {},
'outputs': {
'test': {
'type': 'redshift',
'host': 'localhost',
'schema': 'analytics',
... | class TestLoader(unittest.TestCase):
| def setUp(self):
profile_data = {
'target': 'test',
'quoting': {},
'outputs': {
'test': {
'type': 'redshift',
'host': 'localhost',
'schema': 'analytics',
'user': 'test',
... | import unittest
from unittest import mock
from .utils import config_from_parts_or_dicts, normalize
from dbt.contracts.files import SourceFile, FileHash, FilePath
from dbt.parser import ParseResult
from dbt.parser.search import FileBlock
from dbt.parser import manifest
class MatchingHash(FileHash):
def __init__(... | 140 | 256 | 1,031 | 7 | 132 | joelluijmes/dbt | test/unit/test_parse_manifest.py | Python | TestLoader | TestLoader | 28 | 144 | 28 | 28 | 59bc6a13fa9aedf80abf460125d258aff1814839 | bigcode/the-stack | train |
8bcf05ce8ab1029b67a767d1 | train | class | class MismatchedHash(FileHash):
def __init__(self):
return super().__init__('', '')
def __eq__(self, other):
return False
| class MismatchedHash(FileHash):
| def __init__(self):
return super().__init__('', '')
def __eq__(self, other):
return False
| .parser import ParseResult
from dbt.parser.search import FileBlock
from dbt.parser import manifest
class MatchingHash(FileHash):
def __init__(self):
return super().__init__('', '')
def __eq__(self, other):
return True
class MismatchedHash(FileHash):
| 64 | 64 | 37 | 8 | 55 | joelluijmes/dbt | test/unit/test_parse_manifest.py | Python | MismatchedHash | MismatchedHash | 20 | 25 | 20 | 20 | 5deb6099b4631bb955853fa9f25f53f7d6c55002 | bigcode/the-stack | train |
2f2744f2255124ae8c94cb3b | train | class | class MorganFP(torch.nn.Module):
def __init__(self, dim_features, dim_target, model_configs, dataset_configs):
super(MorganFP, self).__init__()
hidden_dim = model_configs['hidden_units']
dim_features = 2048
self.mlp = torch.nn.Sequential(torch.nn.Linear(dim_features, hidden_dim), nn... | class MorganFP(torch.nn.Module):
| def __init__(self, dim_features, dim_target, model_configs, dataset_configs):
super(MorganFP, self).__init__()
hidden_dim = model_configs['hidden_units']
dim_features = 2048
self.mlp = torch.nn.Sequential(torch.nn.Linear(dim_features, hidden_dim), nn.ReLU(),
... |
import torch
import torch.nn as nn
from torch_geometric.nn import global_add_pool
class MorganFP(torch.nn.Module):
| 27 | 114 | 381 | 7 | 19 | Jh-SYSU/MolRep | MolRep/Models/graph_based/MorganFP.py | Python | MorganFP | MorganFP | 7 | 43 | 7 | 8 | 02db0bf523c26d09267b89642b9f70e66b8f0f35 | bigcode/the-stack | train |
4179976abfc6b1b45f2fe569 | train | class | class PyProjectTranslator(ProjectTranslator, PyTranslator):
def produce(self, ctx):
"""
Setup output tuple variable and generate code to initialize it
as an empty tuple with the correct schema..
There is a special case when if there is no child operator, such as
SELECT 1
... | class PyProjectTranslator(ProjectTranslator, PyTranslator):
| def produce(self, ctx):
"""
Setup output tuple variable and generate code to initialize it
as an empty tuple with the correct schema..
There is a special case when if there is no child operator, such as
SELECT 1
where produce should pretend it is an access method ... | from ..project import *
from ..translator import *
from .translator import *
class PyProjectTranslator(ProjectTranslator, PyTranslator):
| 25 | 73 | 244 | 10 | 15 | ivychen/databass-public | databass/compile/py/project.py | Python | PyProjectTranslator | PyProjectTranslator | 5 | 37 | 5 | 6 | 1b83b219bf85da9540b50efab736becc21750b20 | bigcode/the-stack | train |
19bb6c6944d3bbed1cc6b603 | train | function | def listen_microfone():
#Habilita o microfone para ouvir o usuario
microfone = sr.Recognizer()
frase = ""
with sr.Microphone() as source:
#Chama a funcao de reducao de ruido disponivel na speech_recognition
microfone.adjust_for_ambient_noise(source)
print("Diga alguma coisa: ")
... | def listen_microfone():
#Habilita o microfone para ouvir o usuario
| microfone = sr.Recognizer()
frase = ""
with sr.Microphone() as source:
#Chama a funcao de reducao de ruido disponivel na speech_recognition
microfone.adjust_for_ambient_noise(source)
print("Diga alguma coisa: ")
audio = microfone.listen(source)
try:
frase = microf... | import speech_recognition as sr
def listen_microfone():
#Habilita o microfone para ouvir o usuario
| 25 | 64 | 124 | 18 | 6 | jvrcavalcanti/Joguinho-sem-nome-python- | speech_to_text/listen.py | Python | listen_microfone | listen_microfone | 4 | 18 | 4 | 5 | 0600efeb5f91ac4c20f06234e8e1d96b83d4e33d | bigcode/the-stack | train |
3f1a2c48a26e8c0064654242 | train | class | class PaymentReconciliationTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
js = json.load(handle)
self.assertEqual("PaymentR... | class PaymentReconciliationTests(unittest.TestCase):
| def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
js = json.load(handle)
self.assertEqual("PaymentReconciliation", js["resourceType"])
return pa... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 on 2016-06-23.
# 2016, SMART Health IT.
import io
import json
import os
import unittest
from . import paymentreconciliation
from .fhirdate import FHIRDate
class PaymentReconciliationTests(unittest.TestCase):
| 87 | 244 | 815 | 9 | 77 | all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_1_0_6/models/paymentreconciliation_tests.py | Python | PaymentReconciliationTests | PaymentReconciliationTests | 17 | 68 | 17 | 17 | 2f39f30a95ee6716491e268ac60828e150af6f6f | bigcode/the-stack | train |
e02203926c9daa81e72d75a6 | train | class | class TestAggregateBetweenDates:
def test_calendars(self):
# generate test DataArray
time_std = date_range("1991-07-01", "1993-06-30", freq="D", calendar="standard")
time_365 = date_range("1991-07-01", "1993-06-30", freq="D", calendar="noleap")
data_std = xr.DataArray(
np... | class TestAggregateBetweenDates:
| def test_calendars(self):
# generate test DataArray
time_std = date_range("1991-07-01", "1993-06-30", freq="D", calendar="standard")
time_365 = date_range("1991-07-01", "1993-06-30", freq="D", calendar="noleap")
data_std = xr.DataArray(
np.ones((time_std.size, 4)),
... | _series(np.arange(365))
out = generic.threshold_count(ts, "<", 50, "Y")
np.testing.assert_array_equal(out, [50, 0])
class TestDomainCount:
def test_simple(self, tas_series):
ts = tas_series(np.arange(365))
out = generic.domain_count(ts, low=10, high=20, freq="Y")
np.testing... | 256 | 256 | 1,886 | 6 | 249 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | TestAggregateBetweenDates | TestAggregateBetweenDates | 63 | 261 | 63 | 63 | a6ed3a2990e19d9a65ded09c47bcdcc6cca998b3 | bigcode/the-stack | train |
7d0284faf634e407524cdb64 | train | function | def test_select_time_doys():
da = series("2003-02-13", "2004-12-31", "default")
out = generic.select_time(da, drop=True, doy_bounds=(360, 75))
exp = xr.concat(
(
series("2003-02-13", "2003-03-16", "default"),
series("2003-12-26", "2004-03-15", "default"),
series(... | def test_select_time_doys():
| da = series("2003-02-13", "2004-12-31", "default")
out = generic.select_time(da, drop=True, doy_bounds=(360, 75))
exp = xr.concat(
(
series("2003-02-13", "2003-03-16", "default"),
series("2003-12-26", "2004-03-15", "default"),
series("2004-12-25", "2004-12-31", "... | 3-11-30", "365_day"),
series("1994-03-01", "1994-05-31", "365_day"),
series("1994-09-01", "1994-11-30", "365_day"),
),
"time",
)
xr.testing.assert_equal(out, exp)
def test_select_time_doys():
| 78 | 78 | 263 | 7 | 71 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | test_select_time_doys | test_select_time_doys | 375 | 399 | 375 | 375 | 07947f99c6b944cb4c7c840b1c2a7aa9f7c19c36 | bigcode/the-stack | train |
dc6159fc961628f28d115fc8 | train | class | class TestDomainCount:
def test_simple(self, tas_series):
ts = tas_series(np.arange(365))
out = generic.domain_count(ts, low=10, high=20, freq="Y")
np.testing.assert_array_equal(out, [10, 0])
| class TestDomainCount:
| def test_simple(self, tas_series):
ts = tas_series(np.arange(365))
out = generic.domain_count(ts, low=10, high=20, freq="Y")
np.testing.assert_array_equal(out, [10, 0])
| 31 + 29
class TestThresholdCount:
def test_simple(self, tas_series):
ts = tas_series(np.arange(365))
out = generic.threshold_count(ts, "<", 50, "Y")
np.testing.assert_array_equal(out, [50, 0])
class TestDomainCount:
| 64 | 64 | 58 | 5 | 59 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | TestDomainCount | TestDomainCount | 38 | 42 | 38 | 38 | 9d3d794c170453d87fe81ad092660dc341eee86b | bigcode/the-stack | train |
b54db9865dfafae04a054911 | train | class | class TestDegreeDays:
def test_simple(self, tas_series):
tas = tas_series(np.array([-10, 15, 20, 3, 10]) + 273.15)
out = generic.degree_days(tas, thresh="10 degC", condition=">")
out_kelvin = generic.degree_days(tas, thresh="283.15 degK", condition=">")
np.testing.assert_allclose(o... | class TestDegreeDays:
| def test_simple(self, tas_series):
tas = tas_series(np.array([-10, 15, 20, 3, 10]) + 273.15)
out = generic.degree_days(tas, thresh="10 degC", condition=">")
out_kelvin = generic.degree_days(tas, thresh="283.15 degK", condition=">")
np.testing.assert_allclose(out, [0, 5, 10, 0, 0])
... | =e[0]).transpose(), np.array(e[1]), 2
)
elif event == "equinox":
np.testing.assert_allclose(
dl.sel(time=e[0]).transpose(), np.array(e[1]), rtol=2e-1
)
class TestDegreeDays:
| 64 | 64 | 118 | 5 | 59 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | TestDegreeDays | TestDegreeDays | 300 | 308 | 300 | 300 | 6c9aeadcc2f1728b05bdef58529cc8585151584e | bigcode/the-stack | train |
a2523267c9b19d5feb10df67 | train | function | def test_select_time_month():
da = series("1993-01-05", "1994-12-31", "default")
out = generic.select_time(da, drop=True, month=1)
exp = xr.concat(
(
series("1993-01-05", "1993-01-31", "default"),
series("1994-01-01", "1994-01-31", "default"),
),
"time",
... | def test_select_time_month():
| da = series("1993-01-05", "1994-12-31", "default")
out = generic.select_time(da, drop=True, month=1)
exp = xr.concat(
(
series("1993-01-05", "1993-01-31", "default"),
series("1994-01-01", "1994-01-31", "default"),
),
"time",
)
xr.testing.assert_equal(... | ", condition=">")
np.testing.assert_allclose(out, [0, 5, 10, 0, 0])
np.testing.assert_allclose(out, out_kelvin)
def series(start, end, calendar):
time = date_range(start, end, calendar=calendar)
return xr.DataArray([1] * time.size, dims=("time",), coords={"time": time})
def test_select_time_m... | 90 | 90 | 301 | 6 | 84 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | test_select_time_month | test_select_time_month | 316 | 344 | 316 | 316 | 53724e5c1df08186668f2d0318adc62d14aafe86 | bigcode/the-stack | train |
522251727eca00b49cee3c15 | train | class | class TestDayLength:
def test_multiple_lats(self):
time_data = date_range(
"1992-12-01", "1994-01-01", freq="D", calendar="standard"
)
data = xr.DataArray(
np.ones((time_data.size, 7)),
dims=("time", "lat"),
coords={"time": time_data, "lat": [-... | class TestDayLength:
| def test_multiple_lats(self):
time_data = date_range(
"1992-12-01", "1994-01-01", freq="D", calendar="standard"
)
data = xr.DataArray(
np.ones((time_data.size, 7)),
dims=("time", "lat"),
coords={"time": time_data, "lat": [-60, -45, -30, 0, 30, ... | , op="sum", freq="YS")
np.testing.assert_allclose(out, np.array([np.nan, 272, 273, 272, 272, np.nan]))
# given no freq and only strings for start and end dates
with pytest.raises(ValueError):
generic.aggregate_between_dates(data, start, end, op="sum")
# given a malformed d... | 123 | 123 | 413 | 5 | 118 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | TestDayLength | TestDayLength | 264 | 297 | 264 | 264 | c42c484930656e7ca9649724e0691524077347ab | bigcode/the-stack | train |
aca006105c9835738488983b | train | function | def series(start, end, calendar):
time = date_range(start, end, calendar=calendar)
return xr.DataArray([1] * time.size, dims=("time",), coords={"time": time})
| def series(start, end, calendar):
| time = date_range(start, end, calendar=calendar)
return xr.DataArray([1] * time.size, dims=("time",), coords={"time": time})
| _kelvin = generic.degree_days(tas, thresh="283.15 degK", condition=">")
np.testing.assert_allclose(out, [0, 5, 10, 0, 0])
np.testing.assert_allclose(out, out_kelvin)
def series(start, end, calendar):
| 64 | 64 | 44 | 8 | 56 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | series | series | 311 | 313 | 311 | 311 | bc2d257bd0f5649df84a29ba8c0c451a8379d52d | bigcode/the-stack | train |
edc73d380b67348fc70e787a | train | function | def test_select_time_season():
da = series("1993-01-05", "1994-12-31", "default")
out = generic.select_time(da, drop=True, season="DJF")
exp = xr.concat(
(
series("1993-01-05", "1993-02-28", "default"),
series("1993-12-01", "1994-02-28", "default"),
series("1994-... | def test_select_time_season():
| da = series("1993-01-05", "1994-12-31", "default")
out = generic.select_time(da, drop=True, season="DJF")
exp = xr.concat(
(
series("1993-01-05", "1993-02-28", "default"),
series("1993-12-01", "1994-02-28", "default"),
series("1994-12-01", "1994-12-31", "default"... | 1993-06-01", "1993-06-30", "360_day"),
series("1994-03-01", "1994-03-30", "360_day"),
series("1994-06-01", "1994-06-30", "360_day"),
),
"time",
)
xr.testing.assert_equal(out, exp)
def test_select_time_season():
| 87 | 87 | 292 | 7 | 80 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | test_select_time_season | test_select_time_season | 347 | 372 | 347 | 347 | 45ff823bc9a3a317e74f11e5347db59a50ca69d9 | bigcode/the-stack | train |
9f3632d69de51faff00f8d7f | train | function | def test_select_time_dates():
da = series("2003-02-13", "2004-11-01", "all_leap")
da = da.where(da.time.dt.dayofyear != 92, drop=True) # no 04-01
out = generic.select_time(da, drop=True, date_bounds=("04-01", "12-04"))
exp = xr.concat(
(
series("2003-04-02", "2003-12-04", "all_leap... | def test_select_time_dates():
| da = series("2003-02-13", "2004-11-01", "all_leap")
da = da.where(da.time.dt.dayofyear != 92, drop=True) # no 04-01
out = generic.select_time(da, drop=True, date_bounds=("04-01", "12-04"))
exp = xr.concat(
(
series("2003-04-02", "2003-12-04", "all_leap"),
series("2004-0... | , doy_bounds=(25, 80))
exp = xr.concat(
(
series("2003-02-13", "2003-03-21", "proleptic_gregorian"),
series("2004-01-25", "2004-03-20", "proleptic_gregorian"),
),
"time",
)
xr.testing.assert_equal(out, exp)
def test_select_time_dates():
| 92 | 92 | 309 | 6 | 86 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | test_select_time_dates | test_select_time_dates | 402 | 428 | 402 | 402 | 0f66dd1b80c1be64897fbe2475aafdc4ed734871 | bigcode/the-stack | train |
42126d22d0c40c4023f9263f | train | class | class TestSelectResampleOp:
def test_month(self, q_series):
q = q_series(np.arange(1000))
o = generic.select_resample_op(q, "count", freq="YS", month=3)
np.testing.assert_array_equal(o, 31)
def test_season_default(self, q_series):
# Will use freq='YS', so count J, F and D of eac... | class TestSelectResampleOp:
| def test_month(self, q_series):
q = q_series(np.arange(1000))
o = generic.select_resample_op(q, "count", freq="YS", month=3)
np.testing.assert_array_equal(o, 31)
def test_season_default(self, q_series):
# Will use freq='YS', so count J, F and D of each year.
q = q_series... | import cftime
import numpy as np
import pandas as pd
import pytest
import xarray as xr
import xclim as xc
from xclim.core.calendar import date_range
from xclim.indices import generic
class TestSelectResampleOp:
| 55 | 64 | 196 | 7 | 47 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | TestSelectResampleOp | TestSelectResampleOp | 12 | 28 | 12 | 12 | 0c69828f7799583bb1fcd47beae66ac59f3e60d9 | bigcode/the-stack | train |
ce3b5788d24466eeb3adfee4 | train | function | def test_doyminmax(q_series):
a = np.ones(365)
a[9] = 2
a[19] = -2
a[39] = 4
a[49] = -4
q = q_series(a)
dmx = generic.doymax(q)
dmn = generic.doymin(q)
assert dmx.values == [40]
assert dmn.values == [50]
for da in [dmx, dmn]:
for attr in ["units", "is_dayofyear", "cal... | def test_doyminmax(q_series):
| a = np.ones(365)
a[9] = 2
a[19] = -2
a[39] = 4
a[49] = -4
q = q_series(a)
dmx = generic.doymax(q)
dmn = generic.doymin(q)
assert dmx.values == [40]
assert dmn.values == [50]
for da in [dmx, dmn]:
for attr in ["units", "is_dayofyear", "calendar"]:
assert at... | Count:
def test_simple(self, tas_series):
ts = tas_series(np.arange(365))
out = generic.domain_count(ts, low=10, high=20, freq="Y")
np.testing.assert_array_equal(out, [10, 0])
def test_doyminmax(q_series):
| 64 | 64 | 156 | 9 | 55 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | test_doyminmax | test_doyminmax | 45 | 60 | 45 | 45 | 96dc06c6ab2bb23428099a05f878c985e142453b | bigcode/the-stack | train |
3fec86edd4389dada0b1bf74 | train | class | class TestThresholdCount:
def test_simple(self, tas_series):
ts = tas_series(np.arange(365))
out = generic.threshold_count(ts, "<", 50, "Y")
np.testing.assert_array_equal(out, [50, 0])
| class TestThresholdCount:
| def test_simple(self, tas_series):
ts = tas_series(np.arange(365))
out = generic.threshold_count(ts, "<", 50, "Y")
np.testing.assert_array_equal(out, [50, 0])
|
def test_season(self, q_series):
q = q_series(np.arange(1000))
o = generic.select_resample_op(q, "count", freq="AS-DEC", season="DJF")
assert o[0] == 31 + 29
class TestThresholdCount:
| 64 | 64 | 54 | 5 | 58 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | TestThresholdCount | TestThresholdCount | 31 | 35 | 31 | 31 | 07895733af032d9dcc17d2369bdf853dca05e2e8 | bigcode/the-stack | train |
227da22c43ce3c78f7f2d59a | train | function | def test_select_time_errors():
da = series("2003-01-01", "2004-01-01", "standard")
xr.testing.assert_identical(da, generic.select_time(da))
with pytest.raises(ValueError, match="Only one method of indexing may be given"):
generic.select_time(da, season="DJF", month=[3, 4, 5])
with pytest.rais... | def test_select_time_errors():
| da = series("2003-01-01", "2004-01-01", "standard")
xr.testing.assert_identical(da, generic.select_time(da))
with pytest.raises(ValueError, match="Only one method of indexing may be given"):
generic.select_time(da, season="DJF", month=[3, 4, 5])
with pytest.raises(ValueError, match="invalid d... | series("2004-10-05", "2005-02-28", "standard"),
series("2005-10-05", "2005-11-01", "standard"),
),
"time",
)
xr.testing.assert_equal(out, exp)
def test_select_time_errors():
| 64 | 64 | 168 | 6 | 58 | fossabot/xclim | xclim/testing/tests/test_generic.py | Python | test_select_time_errors | test_select_time_errors | 431 | 446 | 431 | 431 | e9c8734e684dab4b43bfdaa3bd7de2edd000e9c1 | bigcode/the-stack | train |
5b1c7865b333641d417c83f7 | train | class | class Migration(migrations.Migration):
dependencies = [
('Generator', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='level',
name='level',
field=models.IntegerField(default=1),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('Generator', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='level',
name='level',
field=models.IntegerField(default=1),
),
]
| # Generated by Django 3.0.4 on 2020-03-24 07:19
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 55 | 7 | 30 | SmilingTornado/sfia_generator | Generator/migrations/0002_auto_20200324_1419.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | a0f76e5f67a07b46d7811a9ca61ab8de9cbca035 | bigcode/the-stack | train |
b65616570d937fe18088bb95 | train | class | class GeneralizedAdvantageBuffer:
def __init__(
self,
v,
features,
n_steps,
n_envs,
discount_factor=1,
lam=1
):
self.v = v
self.features = features
self.n_steps = n_steps
self.n_envs = n_envs
... | class GeneralizedAdvantageBuffer:
| def __init__(
self,
v,
features,
n_steps,
n_envs,
discount_factor=1,
lam=1
):
self.v = v
self.features = features
self.n_steps = n_steps
self.n_envs = n_envs
self.gamma = discount_factor
... | import torch
from all.environments import State
class GeneralizedAdvantageBuffer:
| 17 | 177 | 590 | 7 | 9 | tipavlos/autonomous-learning-library | all/memory/generalized_advantage.py | Python | GeneralizedAdvantageBuffer | GeneralizedAdvantageBuffer | 4 | 80 | 4 | 4 | 2240314ccd50a2437d35be1645e4e1c80fb9a42d | bigcode/the-stack | train |
d53714cf5a2157273f5c6dab | train | class | class BaseConfig:
SECRET_KEY = os.getenv("SECRET_KEY") or "ohsosecret"
SQLALCHEMY_TRACK_MODIFICATIONS = False
| class BaseConfig:
| SECRET_KEY = os.getenv("SECRET_KEY") or "ohsosecret"
SQLALCHEMY_TRACK_MODIFICATIONS = False
| """QS Tech Test config objects"""
import os
class BaseConfig:
| 14 | 64 | 31 | 4 | 9 | greener2/qs_techtest | qs_techtest/config.py | Python | BaseConfig | BaseConfig | 6 | 8 | 6 | 6 | 7df09e9fa394c2c483f7293b1babcf4261025f74 | bigcode/the-stack | train |
94a8cacbf7e294b8adc41686 | train | class | class Testing(BaseConfig):
SQLALCHEMY_DATABASE_URI = "sqlite://"
| class Testing(BaseConfig):
| SQLALCHEMY_DATABASE_URI = "sqlite://"
| QS Tech Test config objects"""
import os
class BaseConfig:
SECRET_KEY = os.getenv("SECRET_KEY") or "ohsosecret"
SQLALCHEMY_TRACK_MODIFICATIONS = False
class Development(BaseConfig):
SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URI")
class Testing(BaseConfig):
| 64 | 64 | 17 | 5 | 59 | greener2/qs_techtest | qs_techtest/config.py | Python | Testing | Testing | 15 | 16 | 15 | 15 | f7e47ea2808453b53dfefa04a84ff61070d5da68 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.