id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
344089 | import operator as op
from sweetpea import fully_cross_block
from sweetpea.primitives import Factor, DerivedLevel, WithinTrial
# Stroop 3, but the text value must always follow color.
color = Factor("color", ["red", "blue", "green"])
text = Factor("text", ["red", "blue", "green"])
# Global keyw... | StarcoderdataPython |
5117312 | import json
import os
def writejson(filename, v):
with open(filename, 'w') as f:
f.write(json.dumps(v, indent=2))
def mkdirsafeish( name ):
if not os.path.exists(name):
os.makedirs(name)
| StarcoderdataPython |
5008237 | import logging
class ProgramCrew(object):
def __init__(self):
self.person_id = None # type: unicode
self.name_id = None # type: unicode
self.billing_order = None # type: unicode
self.role = None # type: unicode
self.name = None # type: unicode
def __unicode__(... | StarcoderdataPython |
11237286 | #!/usr/bin/env python
# Import the components
from flask import Flask, request, redirect, url_for, render_template
# Import the database functions corresponding to queries
from reportingtooldb import (get_most_popular_articles,
get_most_popular_authors,
get_mo... | StarcoderdataPython |
6520570 | <gh_stars>10-100
#
# PySNMP MIB module TUBS-IBR-PROC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TUBS-IBR-PROC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:20:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3... | StarcoderdataPython |
5066379 | import gzip
import os
import pandas as pd
import re
import sys
import tarfile
sys.path.append(os.path.abspath(os.path.join("..")))
from parsers.loadgen_parser import LoadgenParser
def get_node_names(experiment_dirname):
return [dirname
for dirname in os.listdir(os.path.join(os.path.dirname(__file__),... | StarcoderdataPython |
3452284 | <filename>nanomesh/data/__init__.py
"""Module containing sample data."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import numpy as np
from skimage.data import binary_blobs
from nanomesh._doc import doc
data_dir = Path(__file__).parent
if TYPE_CHECKING:
from n... | StarcoderdataPython |
6589647 | <reponame>vontell/SimCrawl<gh_stars>0
'''
ok so here are sections
2W: 2AB
4E: 3/4C
4W: 4AB
5C: 5AB
6E: 5/6C
6W: 6AB
8C: B Tower
8E: 7ABC
8W: A Tower
9E: C Tower
'''
# c_tower_set = set([975,1078B,1074,978,1078A,1040,940,1040,938,977,873,1077,1073,978,1075,980,840,939,874,840,941,940,939,875,1039,973,1078B,1039,839,87... | StarcoderdataPython |
1934036 | import drawSvg as draw
import pandas as pd
# >>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
# ... index=[4, 5, 6], columns=['A', 'B', 'C'])
# >>> df
# A B C
# 4 0 2 3
# 5 0 4 1
# 6 10 20 30
df = pd.DataFrame([[15.7, 11.9, 3.8]], index=[1], columns=['Comp', 'Traffic... | StarcoderdataPython |
3318602 | <reponame>timgates42/tweetmotif<gh_stars>10-100
import sys
from collections import defaultdict
import twokenize
import bigrams
import lang_model
class LinkedCorpus:
" Hold tweets & indexes .. that is, ngrams are 'linked' to their tweets. "
def __init__(self):
self.model = lang_model.LocalLM()
self.index = ... | StarcoderdataPython |
9646383 | <filename>src/comments/urls.py
from django.urls import path,include
from . import views
app_name='comments'
urlpatterns = [
path('comment/create/<int:post_pk>/', views.create_comment, name='create_comment'),
path('privatecomment/create/<int:assignment_pk>/', views.create_private_comment, name='private_comment... | StarcoderdataPython |
1655990 | from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='a comment bot for getting reddit karma',
author='<NAME>, PhD',
license='MIT',
)
| StarcoderdataPython |
11226268 | EXPECTED_OUTLET_DATA_COLS = [
"AddressChangeCode",
"BureauOfEconomicsAnalysisCode",
"CategorizationOfLocale_By_SizeAndProximityToCities",
"CategorizationOfLocale_By_SizeAndProximityToCities_FromRuralEducationAchievementProgram",
"CensusBlock",
"CensusTract",
"CongressionalDistrict",
"Cor... | StarcoderdataPython |
8118525 | <reponame>societe-generale/jaeger-client-python
# Copyright (c) 2016 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | StarcoderdataPython |
8170938 | <reponame>asanoviskhak/Outtalent
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
return [list(row) for row in zip(*A)]
| StarcoderdataPython |
1875701 | <reponame>parveshkatoch/Scavenger---OSINT-Bot<gh_stars>1-10
#!/usr/bin/python
import time
import datetime
import os
from os import listdir
from os.path import isfile, join
class ScavUtility:
def __init__(self):
pass
def testifreadytoarchive(self, directory):
pastecount = len([name for name in... | StarcoderdataPython |
188203 | #<NAME>
# Write a program that asks the user to input any positive integer and outputs the successive values of the following calculation.
# At each step calculate the next value by taking the current value and
# if it is even, divide it by two, but if it is odd, multiply it by three and add one.
# Have the program end... | StarcoderdataPython |
145767 | from synapseaware.isthmus import topological_thinning
from synapseaware.teaser import teaser
from synapseaware.connectome import wiring
prefix = 'Fib25'
label = 1
topological_thinning.TopologicalThinning(prefix, label)
teaser.TEASER(prefix, label)
wiring.GenerateSkeleton(prefix, label)
wiring.RefineSkeleton(pref... | StarcoderdataPython |
6422330 | import pytest
from tetris.grid import Point, TetrisGrid, clear_rows
locked_points0 = {
Point(0, 11): (1, 1, 1),
Point(1, 11): (1, 1, 1),
Point(2, 11): (1, 1, 1),
Point(3, 11): (1, 1, 1),
Point(4, 11): (1, 1, 1),
Point(0, 10): (1, 1, 1),
# Point(1, 10): (1, 1, 1),
Point(2, 10): (1, 1, ... | StarcoderdataPython |
3432094 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
import sys
import platform
import random
import string
import importlib
#Parameters
import optparse
import configparser
import OmniDB.custom_settings
import OmniDB_app.include.OmniDatabase as OmniDatabase
import OmniDB_app.include.Spartacus.Utils as... | StarcoderdataPython |
1958504 | <gh_stars>1-10
from mojo.events import publishEvent
if __name__ == "__main__":
publishEvent(
"AutoInstaller.AddExternalFonts"
)
| StarcoderdataPython |
3588564 | <gh_stars>0
def divide_range(Ori_img_W, Ori_img_H, section_num, mode=0):
'''
:param Ori_img_W:
:param Ori_img_H:
:param section_num: divide the weight/height to (%s section_num) parts.
:param mode: mode=0 to divide weight, mode=1 to divide height
:return:
'''
if mode==0:
sec... | StarcoderdataPython |
4996347 | <reponame>georgetown-analytics/DC-Bikeshare<gh_stars>10-100
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import time
import os
import matplotlib.pyplot as plt
import sys
TIMESTR = time.strftime("%Y%m%d_%H%M%S")
def open_drive():
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
... | StarcoderdataPython |
3533413 | <filename>calendareshop/shopping/views.py
# -*- coding: utf-8 -*-
import json
import datetime
from collections import defaultdict
from django import forms
from django.db.models import Sum
from django.contrib import auth, messages
from django.contrib.admin.views.decorators import staff_member_required
from django.core.... | StarcoderdataPython |
11370961 | <filename>hooks/pre_gen_project.py
import re
import sys
name = '{{ cookiecutter.package_name }}'
if not re.match(r'^[_a-zA-Z][_a-zA-Z0-9]+$', name):
print('ERROR: Not a valid python package name: %s\n'
' Use \'_\' instead of \'-\' and start with a letter.' % name)
sys.exit(1)
| StarcoderdataPython |
9694066 | """
Translator method
"""
import json
import os
from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from dotenv import load_dotenv
load_dotenv()
apikey = os.environ['apikey']
url = os.environ['url']
authenticator = IAMAuthenticator(apikey)
language_translator ... | StarcoderdataPython |
3463895 | from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER, HANDSHAKE_DISPATCHER
from ryu.controller.handler import set_ev_cls
import ryu.ofproto.ofproto_v1_3 as ofproto
import ryu.ofproto.ofproto_v1_3_parser as ofparser
import ryu.ofproto... | StarcoderdataPython |
5192136 | from dogapi.common import is_p3k
__all__ = [
'SnapshotApi',
]
if is_p3k():
from urllib.parse import urlparse
else:
from urlparse import urlparse
class SnapshotApi(object):
def graph_snapshot(self, metric_query, start, end, event_query=None):
"""
Take a snapshot of a graph, returning ... | StarcoderdataPython |
1649850 | <gh_stars>10-100
import os
import glob
import argparse
import re
import json
def get_goal_files(root_dir, ext = "*.gc"):
"""Get all GOAL source files under root_dir."""
return [goal_file for file in os.walk(root_dir) for goal_file in glob.glob(os.path.join(file[0], ext))]
def get_sgs(goal_file):
"""Get a... | StarcoderdataPython |
9734603 | <gh_stars>10-100
# coding: utf-8
from __future__ import absolute_import, unicode_literals
from codecs import open # pylint:disable=redefined-builtin
from collections import defaultdict
from os.path import dirname, join
import sys
from setuptools import setup, find_packages
CLASSIFIERS = [
'Development Status... | StarcoderdataPython |
3529998 | <filename>.tox/bootstrap/lib/python3.7/site-packages/matrix/__init__.py
# -*- coding: utf-8 -*-
import re
import warnings
from fnmatch import fnmatch
from itertools import product
from backports.configparser2 import ConfigParser
try:
from collections import OrderedDict
except ImportError:
from .ordereddict im... | StarcoderdataPython |
11313800 |
ogp_types = {}
def ogp_type(cls):
type = cls.__name__.lower()
ogp_types[type] = cls()
return cls
class OGP:
def __init__(self, doc):
self.doc = doc
self.prefixes = []
og = doc.meta.namespaces.get('og')
if og:
type = og.get('type')
if type:
... | StarcoderdataPython |
3335955 | import sys
from helpfuncs import translateR
from inverse import inv
# parse spatial CSP and fill in the constraint matrix
def parsecsp(ConMatrix):
while True:
# assure not interrupted parsing
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
break
if n... | StarcoderdataPython |
313182 | # This files defiens the error table as a panda object
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from dotmap import DotMap
from collections import defaultdict
from kmodes.kmodes import KModes
class error_table():
def __init__(self, space=None, t... | StarcoderdataPython |
3513437 | <gh_stars>10-100
from .core import AutoGeneS
from typing import Optional, Tuple
import pandas as pd
import anndata
import numpy as np
import warnings
import dill as pickle
from sklearn.svm import NuSVR
from sklearn import linear_model
from scipy.optimize import nnls
from scipy import sparse
class Interface:
def ... | StarcoderdataPython |
6461904 | """
content.index
"""
from datetime import datetime
import logging
import os
from zoom.mvc import View
from zoom.page import page
from zoom.browse import browse
from pages import load_page
class MyView(View):
def index(self):
return page('Metrics and activity log and statistics will go here.', tit... | StarcoderdataPython |
3569164 | <gh_stars>1-10
import click
from app.domain.commands import DownloadIFQ
from app import bootstrap
@click.command()
@click.option(
'--day',
type=click.DateTime(),
required=True,
help='The day to summarize')
def run_command(day):
"""Downloads the IFQ issue for a specific day"""
print(f'download... | StarcoderdataPython |
4971847 | # pylint: disable=no-name-in-module
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import activations, initializers, regularizers
from tensorflow.keras.layers import Layer
from tensorflow.python.keras.utils import conv_utils #pylint: disable=no-name-in-module
from typing import List, Tuple, ... | StarcoderdataPython |
1928289 | <reponame>madcat1991/clustered_cars
"""
The script transforms bookings data into binary mode.
"""
import argparse
import logging
import sys
import numpy as np
import pandas as pd
from preprocessing.common import canonize_datetime, check_processed_columns
from feature_matrix.functions import replace_numerical_to_cate... | StarcoderdataPython |
384153 | import json
import os
import requests
import config as config
import twitter_helper as twitter_helper
from watson_developer_cloud import PersonalityInsightsV3
def send_pi_request(handle):
"""
Send a request to PI given a handle name
:return:
JSON in python format
"""
tweet_data = twitter_help... | StarcoderdataPython |
1987450 | <gh_stars>1-10
import nth_tac_toe
boardSize = 3
testGame = nth_tac_toe.Game(boardSize)
def X_manual():
while 1:
x_ip = input("x position:")
x_ip = x_ip.split(" ")
rc = testGame.updateBoard("x", x_ip)
if rc == None:
testGame.display()
break
def O_manual():... | StarcoderdataPython |
4948189 | #!/usr/bin/env python3
#
# Short version, harder to read
seats = []
for line in open('input.txt').read().splitlines():
seats.append(int(line.replace('B','1').replace('F','0').replace('R','1').replace('L','0'), 2))
# part 1
print(max(seats))
# part 2
seats.sort()
for i in range(1, len(seats)):
if seats[i] - s... | StarcoderdataPython |
9791885 | import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
import itertools
from pipeline import lab, experiment, psth
from pipeline import dict_to_hash
# ================== DEFINE LOOK-UP ==================
# ==================== Project =====================
experiment.Project.insert([('... | StarcoderdataPython |
1609076 | <filename>setup.py
import os.path
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import latest
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
long_description = f.read()
class Tox(TestCommand):
def final... | StarcoderdataPython |
4882130 | <filename>transpyler/templ_utils.py
import ast
import _ast
def is_const(node):
tree = node.ast
return (
isinstance(tree, _ast.Constant)
or isinstance(tree, _ast.UnaryOp)
and isinstance(tree.operand, _ast.Constant)
)
def get_val(node):
if not is_const(node):
return 'unk... | StarcoderdataPython |
175350 | #! /usr/bin/python3
import tkinter
import tkinter.messagebox as mb
def main():
window = tkinter.Tk()
mb.showinfo("Yo yo title", "Yo yo body")
answer = mb.askquestion("Do you ...", "Do something ?")
if answer == "yes":
print("Ok")
window.mainloop()
if __name__ == '__main__':
main(... | StarcoderdataPython |
3278262 | <filename>djaludir/core/tests/models/test_privacy.py
from django.conf import settings
from django.test import TestCase
from djaludir.core.models import Privacy
from djtools.utils.logging import seperator
class CorePrivacyTestCase(TestCase):
fixtures = ['user.json', 'privacy.json']
def setUp(self):
... | StarcoderdataPython |
3340143 | <reponame>Vivek-Kolhe/URL-Shortener
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
APP_URL = "https://someurl.com/"
db = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = Flask(__name__)
app.config["SECRET_KEY"] = "<PASSWORD>"
app.config["SQLALCHE... | StarcoderdataPython |
6561003 | from django.db import models
from django_oso.models import AuthorizedModel
class User(models.Model):
username = models.CharField(max_length=255)
is_moderator = models.BooleanField(default=False)
is_banned = models.BooleanField(default=False)
posts = models.ManyToManyField("Post")
class Meta:
... | StarcoderdataPython |
1996787 | <reponame>polde-live/interprog1
"""
An Introduction to Interactive Programming in Python (Part 1)
Practice exercises for buttons and input fields # 1.
print_hello
print_goodbye
"""
import simpleguitk as simplegui
def print_hello():
print "Hello"
def print_goodbye():
print "Goodbye"
frame = simplegui.c... | StarcoderdataPython |
3394650 | from distutils.core import setup
import setuptools
dependencies=[
"setuptools~=57.0.0",
"aiohttp~=3.7.4",
"PyYAML~=5.4.1",
]
setup(
name="chiahub_monitor",
version="0.0.5",
author="<NAME>",
author_email="<EMAIL>",
description="A monitoring utility for chia blockchain",
long_descri... | StarcoderdataPython |
390262 | # -*- coding: utf-8 -*-
# Generated by Django 1.9b1 on 2015-11-21 13:02
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | StarcoderdataPython |
3558705 | import allure
from page_objects.LoginPage import LoginPage
@allure.parent_suite("Проверка тестового магазина opencart")
@allure.suite("Тесты страницы авторизации")
@allure.epic("Проверка магазина на opencart")
@allure.feature("Проверка наличия элементов на странице логина")
@allure.title("Поиск элементов на странице... | StarcoderdataPython |
11327679 | from unittest import TestCase
from flask_jwt_extended import create_access_token
from dimensigon.domain.entities import Step, ActionTemplate, ActionType, Orchestration
from dimensigon.network.auth import HTTPBearerAuth
from dimensigon.web import create_app, db, errors
class TestOrchestration(TestCase):
def setU... | StarcoderdataPython |
6488447 | '''
https://www.youtube.com/watch?v=PNj8uEdd5c0
'''
import itertools
from contextlib import closing
from os import PathLike
import sqlite3
from typing import Tuple, Iterable
from dataclasses import dataclass
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.clock import Clock
from kivy.lang... | StarcoderdataPython |
11307646 | """ Entity Class
This file contains the entity class, and is a basis for all
objects within the project.
Methods:
- attack()
Handles the attack action of an entity.
- edit_hp()
Edits the hp of the entity.
Author: <NAME>
"""
# Import/s
import math
from DieClass import Die
class Entity:
def __init__(self... | StarcoderdataPython |
4970491 | <filename>tests/core/inst/mem/inst_lw.py
#=========================================================================
# lwu
#=========================================================================
import random
from pymtl import *
from tests.context import lizard
from tests.core.inst_utils import *
#----------------... | StarcoderdataPython |
189242 | #!/usr/bin/env python
# coding: utf-8
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import CharField
from django.utils import six
from django.utils.encoding import smart_text
class PasswordFieldDescriptor(object):
def __init__(self):
self.value = None
def... | StarcoderdataPython |
6692783 | from wing import Wing
from engine import Engine
from payload import Payload
__all__ = ('Wing', 'Engine', 'Payload')
| StarcoderdataPython |
276439 | answer1 = widget_inputs["radio1"]
answer2 = widget_inputs["radio2"]
answer3 = widget_inputs["radio3"]
answer4 = widget_inputs["radio4"]
is_correct = False
comments = []
def commentizer(new):
if new not in comments:
comments.append(new)
if answer1 == True:
is_correct = True
else:
is_correct = is_c... | StarcoderdataPython |
212754 | # encoding: utf-8
"""The recommended development HTTP server."""
# ## Imports
from __future__ import unicode_literals, print_function
try:
from waitress import serve as serve_
except ImportError:
print("You must install the 'waitress' package.")
raise
# ## Server Adapter
def serve(application, host='127.0.0.1... | StarcoderdataPython |
9625635 | """ File handling helper functions """
import os
import fnmatch
import tarfile
import warnings
def get_author():
try:
import platform
CURRENTOS = platform.system()
if CURRENTOS == "Windows":
import getpass
author = getpass.getuser()
else:
import ... | StarcoderdataPython |
4955349 | <reponame>volundmush/mudstring-python
from rich.style import Style
from .base import ProtoStyle
from .colors import COLORS
from typing import Union, Tuple, List
from rich.text import Text, Span
from rich.color import Color
import html
import re
from enum import IntFlag, IntEnum
from xml.etree import ElementTree
ANSI... | StarcoderdataPython |
249007 |
''' A module for representing permutations in Sym(N). '''
from bisect import bisect
from itertools import combinations
from math import factorial
import numpy as np
class Permutation:
''' This represents a permutation on 0, 1, ..., N-1. '''
def __init__(self, perm):
self.perm = perm
assert se... | StarcoderdataPython |
1959531 | import cv2
import numpy as np
class ColorPiker:
def __init__(self):
self.cam_id = 0
self.frameWidth = 640
self.frameHeight = 480
self.cap = cv2.VideoCapture(self.cam_id, cv2.CAP_DSHOW)
self.cap.set(3, self.frameWidth)
self.cap.set(4, self.frameHeight)
self.... | StarcoderdataPython |
1695248 | <reponame>5gconnectedbike/Navio2
'''OpenGL extension OES.sample_shading
This module customises the behaviour of the
OpenGL.raw.GLES2.OES.sample_shading to provide a more
Python-friendly API
Overview (from the spec)
In standard multisample rendering, an implementation is allowed to
assign the same sets of fragme... | StarcoderdataPython |
56931 | <reponame>vijaykumawat256/Prompt-Summarization
def count_calls(func, *args, **kwargs):
| StarcoderdataPython |
11268600 | <gh_stars>10-100
import paddle
import numpy as np
import test_grad.ppdet_resnet as ppdet_resnet
from paddle.regularizer import L2Decay
depth = 50
variant = 'd'
return_idx = [1, 2, 3]
dcn_v2_stages = [-1]
freeze_at = -1
freeze_norm = False
norm_decay = 0.
depth = 50
variant = 'd'
return_idx = [1, 2, 3]
dcn_v2_stages ... | StarcoderdataPython |
9688785 | <reponame>mluessi/mne-python<filename>mne/tests/test_label.py
import os.path as op
from nose.tools import assert_true
from ..datasets import sample
from .. import label_time_courses
examples_folder = op.join(op.dirname(__file__), '..', '..', 'examples')
data_path = sample.data_path(examples_folder)
stc_fname = op.joi... | StarcoderdataPython |
50835 | # -*- coding: utf-8 -*-
"""
/dms/exercisefolder/views_sitemap.py
.. zeigt die Sitemap des aktuellen Lernarchivs an
Django content Management System
<NAME>
<EMAIL>
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 02.05.2008 Beginn de... | StarcoderdataPython |
4995334 | <reponame>ahameedx/intel-inb-manageability
"""
Central telemetry/logging service for the manageability framework
Copyright (C) 2017-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
from .constants import (
STATE_CHANNEL,
CLOUDADAPTER_STATE_CHANNEL,
AGENT,
CONFIGURATION_UPDATE_... | StarcoderdataPython |
3380086 | <filename>autopycoin/models/nbeats.py
"""
N-BEATS implementation
"""
from typing import Callable, Union, Tuple, List, Optional
from typing import List, Optional
import tensorflow as tf
from keras.engine import data_adapter
from .training import UnivariateModel
from ..layers import TrendBlock, SeasonalityBlock, Gener... | StarcoderdataPython |
9668307 | import unittest
from machinetranslation.translator import englishToFrench, frenchToEnglish
class TestTranslatorModule(unittest.TestCase):
def test_en_to_fr_with_null(self):
result = englishToFrench(None)
self.assertEqual(result,"")
def test_fr_to_en_with_null(self):
result = frenchToE... | StarcoderdataPython |
5096103 | import os
import shutil
import warnings
import random
import logging
import msm_pele.constants as cs
import msm_pele.Helpers.helpers as hp
class EnviroBuilder(object):
"""
Base class wher the needed pele selfironment
is build by creating folders and files
"""
def __init__(self, folders, f... | StarcoderdataPython |
6699971 | <reponame>TheVinhLuong102/thinc
from typing import Tuple, List, Callable, Sequence
from murmurhash import hash_unicode
from ..model import Model
from ..config import registry
from ..types import Ints2d
InT = Sequence[Sequence[str]]
OutT = List[Ints2d]
@registry.layers("strings2arrays.v1")
def strings2arrays() -> M... | StarcoderdataPython |
11398967 | <filename>main2.py
import os
from ReaCombiner import file_utils
from ReaCombiner import gui
from ReaCombiner import db
# noinspection SpellCheckingInspection
def getHome():
if 'HOME' in os.environ:
return os.environ['HOME']
elif 'USERPROFILE' in os.environ:
return os.environ['USERPROFILE']
... | StarcoderdataPython |
11353141 | import subprocess
class ParallelExecutor:
def __init__(self, limit: int):
assert limit > 0, "Limit cannot be less than zero"
self.limit: int = limit
self.__executing: list = []
self.__finished: list = []
def execute(self, *args, **kwrgs):
if len(self.__executing) >= se... | StarcoderdataPython |
3254143 | import os
import numpy as np
from nilt_base.settingsreader import SetupTool
from morph_tools import setup_morpher, single_image_morpher
from grating_helper import get_morphing_info_from_specs
from glob import glob
st = SetupTool("grating_morpher")
log = st.log
def fmod(n):
if n < 5:
n += 1
return n
... | StarcoderdataPython |
9762113 | from os.path import join, dirname
from ctapipe.utils import get_dataset
from ctapipe.io.eventfilereader import EventFileReader, \
EventFileReaderFactory, HessioFileReader
def test_event_file_reader():
try:
EventFileReader(config=None, tool=None)
except TypeError:
return
raise TypeError... | StarcoderdataPython |
9619181 | from collections import namedtuple
from enigma_machine.conf.defaults import ALPHABET
Wire = namedtuple("Wire", "l_contact r_contact")
class Rotor:
def __init__(self, wheel_id, contact_mapping, notch, window="A", ring_setting="A", alphabet=ALPHABET):
""" Initialize Rotor
Args:
whee... | StarcoderdataPython |
9727140 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2016, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2016. UChicago Argonne, LLC. This... | StarcoderdataPython |
11322529 | #!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the ab... | StarcoderdataPython |
6559018 | <reponame>SYU15/cloudless
"""
Cloudless image build command line interface.
"""
import os
import sys
import click
from cloudless.cli.utils import NaturalOrderAliasedGroup
from cloudless.cli.utils import handle_profile_for_cli
from cloudless.util.image_build_configuration import ImageBuildConfiguration
from cloudless.te... | StarcoderdataPython |
11379686 | """Tests for elections_lk."""
import unittest
from elections_lk import party_color
class TestCase(unittest.TestCase):
"""Tests."""
def test_party_to_rgb_color(self):
"""Test."""
for party_id, expected_color in (
('UNP', (0, 0.5, 0)),
('NDF', (0, 0.5, 0)),
):
... | StarcoderdataPython |
37491 | <gh_stars>1-10
from src.fft_from_image.ChainGeneration import ChainGeneration
import numpy as np
class ThueMorse(ChainGeneration):
def __init__(self, repeat, tm_num):
ChainGeneration.__init__(self, repeat)
self.tm_num = tm_num
@staticmethod
def tm_construct(seq):
return [(i + 1) %... | StarcoderdataPython |
5123798 | class SurchargeList(list):
@property
def total(self):
return sum([surcharge.price for surcharge in self])
class SurchargePrice():
surcharge = None
price = None
def __init__(self, surcharge, price):
self.surcharge = surcharge
self.price = price
class Surcha... | StarcoderdataPython |
6477755 | """
**DEPRECATED**
A print function that pretty prints sympy Basic objects.
:moduleauthor: <NAME>
Usage
=====
Once the extension is loaded, Sympy Basic objects are automatically
pretty-printed.
As of SymPy 0.7.2, maintenance of this extension has moved to SymPy under
sympy.interactive.ipythonprinting... | StarcoderdataPython |
6459278 | """
The module contains functions related to data aggretion
"""
# Python libs
from datetime import datetime
from dateutil.relativedelta import relativedelta
# Django libs
from django.db.models import Avg
# Seshdash
from seshdash.models import Daily_Data_Point, Sesh_Site, Sesh_Alert
from seshdash.utils.time_utils imp... | StarcoderdataPython |
167067 | <gh_stars>1-10
import os
import pandas as pd
import numpy as np
from path import Path
from poor_trader import indicators
from poor_trader.config import SYSTEMS_PATH
def _trim_quotes(symbol, df_group_quotes):
df_quotes = df_group_quotes.filter(regex='^{}_'.format(symbol))
df_quotes.columns = [_.replace(symbol... | StarcoderdataPython |
78773 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from a2c_ppo_acktr.distributions import Bernoulli, Categorical, DiagGaussian
from a2c_ppo_acktr.utils import init
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class Policy(nn.Module):
... | StarcoderdataPython |
8136113 | from setuptools import setup
setup(
name='hh-deep-deep',
url='https://github.com/TeamHG-Memex/hh-deep-deep',
packages=['hh_deep_deep'],
include_package_data=True,
install_requires=[
'pykafka==2.6.0',
'tldextract',
],
entry_points = {
'console_scripts': [
... | StarcoderdataPython |
5062523 | #!/usr/bin/python
# (c) 2020, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# This module implements the operations for ONTAP MCC Mediator.
# The Mediator is supported for MCC IP configs from ONTAP 9.7 or later.
# This module requires REST APIs for Mediator w... | StarcoderdataPython |
329911 | import logging
from .taxid import TaxId
ID_PREFIXES = {
# "http://": {"url_prefix": "http://", "url_suffix": ""},
# "https://": {"url_prefix": "https://", "url_suffix": ""},
"W:": {"url_prefix": "http://wikipedia.org/wiki/", "url_suffix": ""},
"NBN:": {"url_prefix": "https://data.nbn.org.uk/Taxa/", "ur... | StarcoderdataPython |
347055 | from rest_framework import serializers
from .models import Marks
from .models import MaxRankBuckets
class MarksSerializer(serializers.ModelSerializer):
class Meta:
model = Marks
fields = "__all__"
class MaxRankBucketsSerializer(serializers.ModelSerializer):
class Meta:
model... | StarcoderdataPython |
224761 | import numpy as np
import matplotlib.pyplot as plt
import newton
def f1(x, y):
return x ** 3 - y * 2
def f2(x, y):
return x ** 2 + y ** 2 - 1
def f(xx):
x = xx[0]
y = xx[1]
return np.array([f1(x, y), f2(x, y)])
def df(xx):
x = xx[0]
y = xx[1]
return np.array([[3 * x ** 2, -2], [2... | StarcoderdataPython |
1800197 | r"""
Permutation group homomorphisms
AUTHORS:
- <NAME> (2006-03-21): first version
- <NAME> (2008-06): fixed kernel and image to return a group,
instead of a string.
EXAMPLES::
sage: G = CyclicPermutationGroup(4)
sage: H = DihedralGroup(4)
sage: g = G([(1,2,3,4)])
sage: phi = PermutationGroupMorp... | StarcoderdataPython |
3467319 | <reponame>neural-reckoning/decoding_sound_location
from base import *
def compute_confusion_matrix(analysis, estimator):
num_shuffles = analysis.settings['num_shuffles']
bins = analysis.moresettings['itd_bins']
binmids = 0.5*(bins[1:]+bins[:-1])
confmat = zeros((len(bins)-1, len(bins)-1))
shuffled_... | StarcoderdataPython |
6652072 | #!/usr/bin/env python3
"""A test program to test action servers for the JACO and MICO arms."""
import roslib; roslib.load_manifest('kinova_demo')
import rospy
import actionlib
import kinova_msgs.msg
import geometry_msgs.msg
import tf
import std_msgs.msg
import math
from kinova_msgs.srv import *
import argparse
pref... | StarcoderdataPython |
6406407 | <reponame>minshenglin/nfs-ganesha-tools
import rados
import cephfs
import xattr
import errno
import os
import sys
import ganesha
class CephHandler():
def __init__(self):
self.cluster = rados.Rados(conffile='/etc/ceph/ceph.conf')
self.cluster.connect()
self.fs = CephfsHandler(self.cluster)
... | StarcoderdataPython |
9617659 | from cbpro_client import cbpro_client
from logger import logger
import json
import sys
import string
@cbpro_client
@logger
def check_stats(cbpro_client, logger, product = 'BTC-USD'):
""" Check stats of a pair
Params:
- product (pair): string default BTC-USD
Return:
- price response
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.