id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
1815980 | <gh_stars>0
from sentry_sdk.hub import Hub
from sentry_sdk._types import MYPY
from sentry_sdk import _functools
if MYPY:
from typing import Any
def patch_views():
# type: () -> None
from django.core.handlers.base import BaseHandler
from sentry_sdk.integrations.django import DjangoIntegration
ol... | StarcoderdataPython |
9794850 | # Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A script to dump a trie from a validator DFA."""
import multiprocessing
import optparse
import sys
import traceback
import dfa_parser
import df... | StarcoderdataPython |
4911343 | <reponame>doctoryes/project_euler
# A permutation is an ordered arrangement of objects.
# For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
# If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 and 2 are:
... | StarcoderdataPython |
149152 | # Copyright 2019 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 or agreed to in writing, ... | StarcoderdataPython |
30092 | from __future__ import print_function
import pylab as plt
import numpy as np
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, QueryDict
from django.shortcuts import render_to_response, get_object_or_404, redirect, render
from django.template import Context, RequestContext, loader
fr... | StarcoderdataPython |
9796719 | <gh_stars>0
frase = 'Curso em Video Python'
print(frase.replace('Python', 'Android'))
print(frase)
print('Curso' in frase)
print(frase.lower().find('video'))
print(frase.split())
dividido = frase.split()
print(dividido)
| StarcoderdataPython |
3352506 | <gh_stars>0
#!/usr/bin/env python3
"""
Low level OpenGL vertex array wrapper
"""
# External, non built-in modules
import OpenGL.GL as GL # standard Python OpenGL wrapper
import numpy as np # all matrix manipulations & OpenGL args
class VertexArray:
""" helper class to create and self ... | StarcoderdataPython |
3548499 | <reponame>dcabatin/manim
from functools import reduce
import itertools as it
import operator as op
import copy
import numpy as np
import random
from manimlib.imports import *
from kuratowski.our_discrete_graph_scene import *
class MainGraph(Graph):
def construct(self):
self.vertices = [
# mai... | StarcoderdataPython |
12852369 | # tests for narps code
# - currently these are all just smoke tests
import pytest
import os
import pandas
from narps import Narps
from AnalyzeMaps import mk_overlap_maps,\
mk_range_maps, mk_std_maps,\
mk_correlation_maps_unthresh, analyze_clusters,\
plot_distance_from_mean, get_thresh_similarity
from MetaA... | StarcoderdataPython |
308943 | #!/usr/bin/python3
import boto3
import datetime
#from subprocess import call
import os
debug_on = True
today = datetime.date.today()
bucket_name = 'halimer-dns-analytics'
log_folder_name = '/var/log/'
tmp_dir = '/tmp/'
prefix = 'd=' + str(today) + '/'
pihole_log_file = 'pihole.log'
clean_log_name = 'clean_dns... | StarcoderdataPython |
3511006 | import pytest
import requests
from requests import HTTPError
from dcos_test_utils.helpers import Url
from dcos_test_utils.jobs import Jobs
class MockResponse:
def __init__(self, json: dict, status_code: int):
self._json = json
self._status_code = status_code
def json(self):
return se... | StarcoderdataPython |
283666 | <filename>srsran_controller/common/utils.py
from contextlib import contextmanager
from subprocess import Popen, PIPE
@contextmanager
def shutdown_on_error(instance):
try:
yield instance
except Exception:
instance.shutdown()
raise
def run_as_sudo(command, password, stdout=PIPE, stderr... | StarcoderdataPython |
9754676 | <reponame>lsst-camera-dh/ts3-analysis<filename>read_lims_db.py
import pickle
input = open('my_fakelims.db')
db = pickle.load(input)
| StarcoderdataPython |
12819507 | <filename>zoonado/recipes/sequential.py
from __future__ import unicode_literals
import logging
import re
import uuid
from tornado import gen
from zoonado import exc, WatchEvent
from .recipe import Recipe
log = logging.getLogger(__name__)
sequential_re = re.compile(r'.*[0-9]{10}$')
class SequentialRecipe(Recipe)... | StarcoderdataPython |
9643526 | <filename>Color.py<gh_stars>0
class Color:
def __init__(self, hue:int, vividness:int, brightness:int) -> None:
if hue > 29:
raise ValueError("Hue value cannot be larger than 30")
if vividness > 14:
raise ValueError("Vividness value cannot be larger than 15")
if brigh... | StarcoderdataPython |
5111966 | import argparse
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import scipy as sp
import scipy.stats
import pyemma
from pyemma.util.contexts import settings
import MDAnalysis as mda
# My own functions
from pensa import *
# -------------#
# --- MAIN --- #
# -------------#
if __name__ =... | StarcoderdataPython |
11212180 | """Module that contains exceptions handled in config parsing and loading."""
import traceback
from typing import Any, Optional
class IniError(Exception):
"""Exception caused by error in INI file syntax."""
def __init__(self,
line: int,
message: str,
origina... | StarcoderdataPython |
4971213 | <gh_stars>0
# Anagram check: O(NLogN)
def is_anagram(str1, str2):
print(str1)
print(str2)
if len(str1) != len(str2):
print('False')
return False
str1 = sorted(str1)
print(str1)
str2 = sorted(str2)
print(str2)
for i in range(len(str1)):
if str1[i] != st... | StarcoderdataPython |
347432 | """
Handles assembler functionality, powered by the Keystone engine.
:author: <NAME>
:license: MIT
"""
from __future__ import absolute_import
import logging
import re
from chiasm_shell.backend import Backend
l = logging.getLogger('chiasm_shell.assembler')
try:
import keystone as ks
except ImportError as e:
... | StarcoderdataPython |
1683559 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import sys
import os
import unittest
import re
import web
from paste.fixture import TestApp
#from nose.tools import *
import logging
import karesansui
import karesansui.urls
username = "ja@localhost"
password = "password"
class TestRestAPI(unittest.Tes... | StarcoderdataPython |
11305769 | <reponame>grepleria/SnitchDNS<gh_stars>100-1000
from app.lib.notifications.managers.type_manager import NotificationTypeManager
from app.lib.notifications.managers.subscription_manager import NotificationSubscriptionManager
from app.lib.notifications.managers.log_manager import NotificationLogManager
from app.lib.notif... | StarcoderdataPython |
4990623 | <gh_stars>10-100
from copy import copy
import types
import functools
def copy_func(f, new_funcs):
"""
Based on http://stackoverflow.com/a/6528148/190597
by <NAME>
>>> def f(a, b, c): return a + b + c
>>> g = copy_func(f, {})
>>> g is not f
True
>>> f(1, 2, 3) == g(1, 2, 3)
True
... | StarcoderdataPython |
1873481 | #Activity 2 (Connectivity)
import mysql.connector as mc
connectMySQL = mc.connect(host = 'localhost', user = 'root', password = '<PASSWORD>', database = 'mydb')
cursor = connectMySQL.cursor(buffered = True)
def insert_values():
item_code = input("Enter the ItemCode: ")
item_name = input("Enter the ItemName: ")
pr... | StarcoderdataPython |
11235036 | <filename>pkgs/dask-0.8.1-py27_0/lib/python2.7/site-packages/dask/array/numpy_compat.py
from __future__ import absolute_import, division, print_function
import numpy as np
import warnings
try:
isclose = np.isclose
except AttributeError:
def isclose(*args, **kwargs):
raise RuntimeError("You need numpy ... | StarcoderdataPython |
6645609 | <gh_stars>0
first_set = {2, 'd', 4, 3.23232, 'hehe'}
print(f'{first_set =}')
for items in first_set:
print(items) | StarcoderdataPython |
4848799 | class TreeNode(object):
def __init__(self, val: str):
if val.isalnum():
self.val = val
self.children = [None]*26
class Solution(object):
def __init__(self):
self.root = TreeNode('0')
self.result = ""
def longestWord(self, words):
"""
:typ... | StarcoderdataPython |
11239387 | def test_ast_to_code():
from robotframework_interactive.ast_to_code import ast_to_code
from robot.api import get_model
code = (
"*** Settings ***\n"
"Library lib WITH NAME foo\n"
"\n"
"*** Comments ***\n"
"some comment\n"
"\n"
"*** Test Case... | StarcoderdataPython |
231709 | <filename>crypto_app/msb_app/models/SigVarsModel.py
from sqlalchemy import ForeignKey
from .. import db
from crypto_utils.conversions import SigConversion
class SigVarsModel(db.Model):
__tablename__ = 'sigvars'
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.Integer)
u_ = db.Co... | StarcoderdataPython |
1696254 | <reponame>domwillcode/home-assistant
"""Tests for ZHA integration init."""
import pytest
from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH
from homeassistant.components.zha.core.const import (
CONF_BAUDRATE,
CONF_RADIO_TYPE,
CONF_USB_PATH,
DOMAIN,
)
from homeassistant.const import MAJOR_VERSION, ... | StarcoderdataPython |
9776619 | <reponame>chriszhou0916/czai4art<filename>trainer/callbacks/__init__.py
from trainer.callbacks.copy_keras_models import CopyKerasModel
from trainer.callbacks.log_code import LogCode
from trainer.callbacks.generate_images import GenerateImages
from trainer.callbacks.start_tensorboard import StartTensorBoard
from trainer... | StarcoderdataPython |
5106005 | <gh_stars>0
from django.db import models
from base.models import EONBaseModel, Topic
class BlogManager(models.Manager):
"""Create descriptive filter names for easier to read view"""
def published(self):
return self.filter(published=True)
class Blog(EONBaseModel):
title = models.CharField(max_l... | StarcoderdataPython |
9636966 | <filename>qualtrics/client.py
"""
Qualtrics API Client
"""
# Local imports
from qualtrics.api import QualtricsAPI
from qualtrics import components
class QualtricsClient(QualtricsAPI):
"""
Ties in functionality of individual components
"""
def __init__(self, data_center, api_key):
super().__i... | StarcoderdataPython |
9733943 | <reponame>BhavyeMathur/goopylib
from goopylib.imports import *
window = Window(title="B-Spline Curve Example Program", height=600, width=600)
control_points = [[70, 350], [200, 250], [400, 470], [300, 500], [230, 450], [120, 570]]
spline_points = []
resolution = 0.1
Line(*control_points, outline=RED).draw()
for po... | StarcoderdataPython |
9602765 | # Copyright 2016 Tesora, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | StarcoderdataPython |
5171753 | import numpy as np
from flaml import AutoML
def test_forecast_automl(budget=5):
# using dataframe
import statsmodels.api as sm
data = sm.datasets.co2.load_pandas().data['co2'].resample('MS').mean()
data = data.fillna(data.bfill()).to_frame().reset_index().rename(
columns={'index': 'ds', 'co2':... | StarcoderdataPython |
79030 | <filename>templates/commonfilters.py
import re
import pandocfilters as pf
def lb(s):
return pf.RawBlock('latex', s)
def li(s):
return pf.RawInline('latex', s)
def fig(name, props, anim):
return li('\\includegraphics%s[%s]{%s}\n' %
('<' + anim + '>' if len(anim) > 0 else '', props, name))
def... | StarcoderdataPython |
1945783 | <filename>7day/UL2/01_naver_home/02_naver_adjust_bs4.py
import urllib.request
import bs4
url = "https://www.naver.com/"
html = urllib.request.urlopen(url)
bs_obj = bs4.BeautifulSoup(html, "html.parser")
print(bs_obj) | StarcoderdataPython |
8094969 | # Copyright (c) 2020 - present <NAME> <https://github.com/VitorOriel>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, ... | StarcoderdataPython |
1856463 | import abjad
from presentation import *
import abjadext.rmakers
rmakers = abjadext.rmakers
def rotate(l, n):
return l[-n:] + l[:-n]
### PRE ###
def show_demo():
divisions = [(3, 8), (5, 4), (1, 4), (13, 16)]
score = abjad.Score()
counts = [1, 2, 3]
selector = abjad.select().tuplets()[:-1]
se... | StarcoderdataPython |
12842004 | <filename>app/user/tests/test_user_api.py
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reve... | StarcoderdataPython |
207005 | from arm.logicnode.arm_nodes import *
class RandomColorNode(ArmLogicTreeNode):
"""Generates a random color."""
bl_idname = 'LNRandomColorNode'
bl_label = 'Random Color'
arm_version = 1
def init(self, context):
super(RandomColorNode, self).init(context)
self.add_output('NodeSocketC... | StarcoderdataPython |
4907431 | <gh_stars>0
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | StarcoderdataPython |
325819 | # Developed by Redjumpman for Redbot.
# Inspired by Spriter's work on a modded economy.
# Creates 1 json file, 1 log file per 10mb, and requires tabulate.
# STD Library
import asyncio
import gettext
import logging
import logging.handlers
import os
import random
from copy import deepcopy
from fractions impo... | StarcoderdataPython |
4916364 | # Import python modules
import readline
import sys
# Import core modules
from core.module_manager import ModuleManager
from core import colors
from core import command_handler
mm = ModuleManager
def run(scf):
global mm
scriptline = 0
ch = command_handler.Commandhandler(mm, False)
while True:
try:
if scrip... | StarcoderdataPython |
5192103 | from django.urls import reverse
from django.conf import settings
from django.test import TestCase
from rest_framework.test import APIClient
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.contrib.auth.tokens import default_token_generator
import json
import ... | StarcoderdataPython |
1635640 | from random import randint, seed
seed(10) # Set random seed to make examples reproducible
random_dictionary = {i: randint(1, 10) for i in range(5)}
print(random_dictionary) # {0: 10, 1: 1, 2: 7, 3: 8, 4: 10}
| StarcoderdataPython |
6536331 | #!/usr/local/bin/python3.6
import random
import time
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
from tqdm import tqdm
import os
os.environ["CUDA_VISIBLE_DEVICES"]="4"
tf.logging.s... | StarcoderdataPython |
5102674 | from django.db import models
from django.db.models.deletion import DO_NOTHING
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.search import index
from author.mo... | StarcoderdataPython |
9608725 | <reponame>ptracton/ExperimentalPython
import PyQt5
import PyQt5.QtWidgets
class UI_CommonInfo(PyQt5.QtWidgets.QDialog):
"""
Display Common Player Information
"""
def __init__(self, parent=None):
super(UI_CommonInfo, self).__init__(parent)
self.topLayout = PyQt5.QtWidgets.QVBoxLayout()... | StarcoderdataPython |
1709926 | from django.urls import path
from system.views import login_view, UserPasswordUpdateView, logout_view, UserInfo, UserLogout,Menu
app_name = "system"
urlpatterns = [
path('login', login_view, name="login"),
path('password_update', UserPasswordUpdateView.as_view(), name="password_update"),
path('logout', lo... | StarcoderdataPython |
11219109 | import signal
import asyncio
import logging
import aiohttp
class Client(object):
def __init__(self, loop, handler, max_connections=30):
self.loop = loop
self.handler = handler
self.sem = asyncio.Semaphore(max_connections)#For preventing accidental DOS
self.queue = asyncio.Priority... | StarcoderdataPython |
11221889 | <filename>deeplearning/data.py
#!/usr/bin/python
from __future__ import print_function
import os
import numpy as np
import random
import cv2
data_path = '/data/octirfseg/round3/final/'
image_rows = 432
image_cols = 32
batchsize = 149*8
def create_valid_data():
valid_data_path = os.path.join(data_path, 'valid... | StarcoderdataPython |
11386898 | """
This module provides a Python API to shell functions coming
from a sourced shell script.
"""
from .core import config
__version__ = '0.2.1'
# Expose only specific stuff
__all__ = ['config']
| StarcoderdataPython |
3377559 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup
VERSION = "0.1.10"
URL = "https://github.com/chainsquad/graphene-healthchecker"
setup(
name="graphene-healthchecker",
version=VERSION,
description="Python library for RPC-healthchecking for graphene blockchains",
download_url... | StarcoderdataPython |
388157 | <filename>notes/design/low-level/case-studies/parking-lot/parking_lot/commands/CommandStatus.py
from commands.AbstractCommand import AbstractCommand
class CommandStatus(AbstractCommand):
def execute(self):
return self.parking_lot.get_status() | StarcoderdataPython |
1996162 | <reponame>avineshpvs/vldb2018-sherlock
#!/usr/bin/python
# ---------------------------------------------------------------------------
# File: populate.py
# Version 12.8.0
# ---------------------------------------------------------------------------
# Licensed Materials - Property of IBM
# 5725-A06 5725-A29 5724-Y48 57... | StarcoderdataPython |
11295001 | # -*- coding: utf-8 -*-
import scrapy
from urllib import parse
import re
import json
import datetime
import logging
from w3lib.html import remove_tags
from items import WeiboVMblogsItem, WeiboVCommentsItem
class WeiboVSpider(scrapy.Spider):
name = 'weibo_v'
logger = logging.getLogger(name)
allowed_domain... | StarcoderdataPython |
94113 | import six
class InvalidPaddingError(Exception):
pass
class Padding(object):
"""Base class for padding and unpadding."""
def __init__(self, block_size):
self.block_size = block_size
def pad(self, value):
raise NotImplementedError('Subclasses must implement this!')
def unpad(se... | StarcoderdataPython |
248179 | import random
import argparse
import wordcloud
from wordcloud import WordCloud
def generate_background_image(words, out="output_image.png", layout_color="black", width=1200, height=800, step_size=50, bias=10):
'''
Generate an image of words in a given string using wordcloud module.
Argument:
word... | StarcoderdataPython |
3205474 | import django
from django.forms import MultiValueField, CharField
from attributesjsonfield.widgets import AttributesJSONWidget
class AttributesJSONField(MultiValueField):
""" """
widget = AttributesJSONWidget
def __init__(self, *args, attributes=None, require_all_fields=False, **kwargs):
self.... | StarcoderdataPython |
3548298 | <reponame>jabozzo/delta_sigma_pipe_lascas_2020
#! /usr/bin/env python
import parsec as psc
def lexme(parser):
return parser << psc.spaces()
def int_number(self):
'''Parse int number.'''
return psc.regex(r'-?(0|[1-9][0-9]*)').parsecmap(int)
def float_number(self):
'''Parse float number.'''
ret... | StarcoderdataPython |
101655 | import string
class Automata:
"""Class automaton"""
def __init__(self, filename=""):
if filename is "":
self.symboles = []
self.states = {}
self.initialStates = []
self.finalStates = []
else:
self.symboles = []
self.states... | StarcoderdataPython |
337768 | <reponame>OutHereVR/c4d-prototype-converter
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limi... | StarcoderdataPython |
3540554 | <filename>grid_cell_model_uniform.py
# Standard library imports
import errno
import os
import random
import time
import cPickle as pickle
import matplotlib.pyplot as plt
import numpy as np
import utilities as util
from pyNN.random import RandomDistribution, NumpyRNG
from pyNN.space import Grid2D
from pyNN.utility.plott... | StarcoderdataPython |
9715458 | import pandas as pd
import sklearn
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.decomposition import IncrementalPCA
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
... | StarcoderdataPython |
156844 | <filename>ChutesandLadders.py
import numpy as np
import copy
import time
# The dictionary of chutes and ladder.
chutes_ladders = {1: 38, 4: 14, 16: 6, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100, 98: 78, 95: 75, 93: 73, 87: 24, 64: 60, 62: 19, 56: 53, 49: 11, 48: 26}
cd_list = list(chutes_ladders.keys())
#... | StarcoderdataPython |
12836764 | import logging
import requests
from .config import MeshConfiguration, ChebiConfiguration, EntrezConfiguration
from .parser import BasicParser, ChebiObjectParser
from .objbase import MeshObject
from .sparql import SparqlQuery, QueryTerm2UI
__all__ = ['MeshURI', 'MeshRDFRequest', 'MeshRDFResponse', 'MeshSearchRequest', ... | StarcoderdataPython |
9795023 | # Snake.py
# By <NAME> <<EMAIL>>
# MIT License
import pygame
from pygame.locals import *
import random
FPS = 10
SCREEN_SIZE = (640, 480)
CELL_SIZE = 20
COLS = SCREEN_SIZE[0] / CELL_SIZE
ROWS = SCREEN_SIZE[1] / CELL_SIZE
# Set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Setup directions... | StarcoderdataPython |
6638491 | <filename>clsim/resources/plots/antares_om_angular_sensitivity.py
#!/usr/bin/env python
#--------------------------------------------
# plot_antares_om_angular_sensitivity
#
# A script to plot the 4 four possible angular
# acceptances for an ANTARES OM.
#
# Further a comparison plot is done to show
# the precision of... | StarcoderdataPython |
3411446 | import sys
layers = 12
delta = 0.00000000001
if len(sys.argv) < 3:
print 'Usage: python compare_layers.py <file> <reference>'
sys.exit(2)
with open(sys.argv[1], 'r') as fin:
indata = fin.readlines()
with open(sys.argv[2], 'r') as fref:
refdata = fref.readlines()
for i in range(layers):
invals = indata[i].spli... | StarcoderdataPython |
11225413 | import numpy as np
A = np.matrix([[1,0,0],
[0,1,0],
[0,0,1]]) #lattice
print("Direct Lattice:\n{}".format(A))
B = 2*np.pi*(np.linalg.inv(A)).H #recip lattice
print("Recip Lattice:\n{}".format(B))
rc = 0.5*np.min(np.sqrt(np.sum(np.square(A),1)))
lrdimcut = 40
kc = lrdimcut / rc
print("l... | StarcoderdataPython |
5065191 | <reponame>behdadahmadi/instamaker<gh_stars>10-100
#!/usr/bin/python
#Instagram Account Maker
#by <NAME>
#Twitter: behdadahmadi
#https://github.com/behdadahmadi
#https://logicalcoders.com
import requests
import hmac
import hashlib
import random
import string
import json
import argparse
def HMAC(text):
key = '3f0a... | StarcoderdataPython |
5063791 | <filename>caluma/form/tests/test_jexl.py
import pytest
from ..jexl import QuestionJexl
@pytest.mark.parametrize(
"expression,num_errors",
[
# correct case
('"question-slug"|answer|mapby', 0),
# invalid subject type
("100|answer", 1),
# two invalid subject types
... | StarcoderdataPython |
5178402 | import sys
import queue
import threading
import json
import collections
import time
from spirecomm.spire.game import Game
from spirecomm.spire.screen import ScreenType
from spirecomm.communication.action import Action, StartGameAction
def read_stdin(input_queue):
"""Read lines from stdin and write them to a queue
... | StarcoderdataPython |
8193208 | <filename>chapter_15/cgi-bin/badlink.py
import cgi, sys
form = cgi.FieldStorage() # print all inputs to stderr; stodout=reply page
for name in form.keys():
print('[%s:%s]' % (name, form[name].value), end=' ', file=sys.stderr)
'''
The moral of this story is that unless you can be sure that the names of all but the... | StarcoderdataPython |
1978295 | import sys
import os
filename = sys.argv[1]
filedir = sys.argv[2]
os.chdir(filedir)
os.system('touch ' + filename)
os.chdir('/Users/vipul/Documents/coding/cp')
file, extension = filename.split('.')
if(extension=="py"):
cp_file_path = './cp_python_template.py'
elif(extension=="cpp"):
cp_file_path = './cp_cpp_... | StarcoderdataPython |
5197004 | <reponame>CedarGroveStudios/AD9833_ADSR_FeatherWing
# The MIT License (MIT)
#
# Copyright (c) 2019 <NAME>
# Thanks to <NAME> for the driver concept inspiration
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal... | StarcoderdataPython |
271384 | <filename>tests/src/Exceptions_Reports/Teacher_Exception/regression_teacher_exception.py
# -*- coding: utf-8 -*-
import unittest
import time
from selenium.webdriver.support.select import Select
from Data.parameters import Data
from Exceptions_Reports.Teacher_Exception.teacher_exception_scripts import teacher_exceptio... | StarcoderdataPython |
1951650 | import hashlib
from tornado.web import RequestHandler
from tornado import gen
class Handler(RequestHandler):
@gen.coroutine
def post(self):
"""
修改密码
:return: if ok: '0' else '1'
"""
try:
username = self._get_cookie_username()
params = self._get_... | StarcoderdataPython |
374092 | <reponame>Bhaskers-Blu-Org1/text-oriented-active-learning<filename>toal/samplers/RandomSampler.py
from random import shuffle
import pandas as pd
from .AbstractSampler import AbstractSampler
from toal.stores import BasicStore
class RandomSampler(AbstractSampler):
def choose_instances(self, store: BasicStore, batc... | StarcoderdataPython |
4879217 | #!/usr/bin/python3
import time
import serial
from serial import Serial
from datetime import datetime
import struct
import sys
# from collections import namedtuple
import numpy as np
import mysql.connector as sql
from scipy import interpolate
from sys import argv
import gps
import requests
import socket
lat = 0
lon =... | StarcoderdataPython |
1745663 | # Generating fibonacci sequence
from typing import Generator
def fib6(n: int) -> Generator[int, None, None]:
yield 0
if n > 0:
yield 1
last: int = 0
next: int = 1
for _ in range(1, n):
last, next = next, last + next
yield next # main generation step
for i in fib6(20):
... | StarcoderdataPython |
225728 | # pyOCD debugger
# Copyright (c) 2015-2020 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | StarcoderdataPython |
6474786 | import logging
import os
from git import NoSuchPathError, GitCommandError, InvalidGitRepositoryError
from assigner.backends import RepoError
from assigner.backends.exceptions import RetryableGitError
from assigner import progress
from assigner.backends.decorators import requires_config_and_backend
from assigner.roste... | StarcoderdataPython |
11380203 |
import pyblish.api
class ValidateContextHasInstance(pyblish.api.ContextPlugin):
"""確認場景有物件需要發佈
如果這個檢查出現錯誤,請使用 Creator 工具創建 Subset Instance 再進行發佈
"""
"""Context must have instance to publish
Context must have at least one instance to publish, please create one
if there is none.
"""
... | StarcoderdataPython |
183380 | <filename>SSolver.py
board = [[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]]
def solve():
... | StarcoderdataPython |
6524862 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
from os import environ
environ['SDL_VIDEO_CENTERED'] = '1'
import os.path
thisrep = os.path.dirname(__file__)
imagesrep = os.path.join(thisrep,'images')
from pygame import *
font.init()
from subprocess import Popen,PIPE
from sys import stdout
import pickle
from Buttons i... | StarcoderdataPython |
1647053 | # twitter sentiment analysis
# (c) <NAME>, The Medusa's Cave Blog 2012
# Description: This file performs simple sentiment analysis on global twitter feeds
# Later versions may improve on the sentiment analysis algorithm
import os, sys, time; # import standard libraries
from twython import Twython; ... | StarcoderdataPython |
3210403 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the L... | StarcoderdataPython |
1820114 | <filename>Lib/color.py
import colorsys
import numpy as np
def generate_color(num_Color:int) -> list:
"""
https://github.com/qqwweee/keras-yolo3/blob/master/yolo.py
L82 - L91
"""
hsv_tuples = [(x / num_Color, 1., 1.) for x in range(num_Color)]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x... | StarcoderdataPython |
3566222 | from __future__ import division
from __future__ import print_function
import numpy as np
from numpy.random import rand
from numpy import linalg as LA
import matplotlib
import matplotlib.pyplot as plt
from scipy import interpolate
from matplotlib.patches import Arrow, Circle, Rectangle
from matplotlib.patches import Con... | StarcoderdataPython |
8069563 | class Solution:
#@param num: A list of non negative integers
#@return: A string
def largestNumber(self, num):
# write your code here
def quickSort(arr):
if (len(arr) <= 1):
return arr
mid = str(arr[0])
smaller = filter(lambda a: str(a) + mi... | StarcoderdataPython |
126830 | from django.urls import path, include, re_path
from . import views
app_name = 'accounts'
urlpatterns = [
re_path(r'^reachus', views.reachus, name='reachus'),
re_path(r'^login', views.login, name='login'),
re_path(r'^signup', views.signup, name='signup'),
re_path(r'^campus_signup', views.campus_signup, ... | StarcoderdataPython |
156135 | from io import StringIO
from django.core.management import call_command
from django.test import TestCase
class OutageTest(TestCase):
def test_command_output(self):
out = StringIO()
# call_command("playlists", stdout=out)
# self.assertIn("Expected output", out.getvalue())
| StarcoderdataPython |
5048826 | <filename>main.py
from hktm import create_app
app = create_app('prod.cfg')
#app.run(host='0.0.0.0')
| StarcoderdataPython |
1810268 | def copy(a):
"""
Returns a copy of a given Galois field array.
See: https://numpy.org/doc/stable/reference/generated/numpy.copy.html
Warning
-------
This function returns an :obj:`numpy.ndarray`, not an instance of the subclass. To return a copy of the subclass, pass
`subok=True` (for nump... | StarcoderdataPython |
11331476 | <filename>Infer.py<gh_stars>1-10
# Load and run neural network and make preidction
import numpy as np
import torchvision.models.segmentation
import torch
import torchvision.transforms as tf
width=height=900 # image width and height
modelPath="400.torch"
#---------------------create image ------------------------------... | StarcoderdataPython |
205778 | import cv2
import os
import sys
from scipy.io import loadmat
import os.path as osp
import numpy as np
import json
from PIL import Image
import pickle
from sklearn.metrics import average_precision_score
from sklearn.preprocessing import normalize
from iou_utils import get_max_iou, get_good_iou
def compute_iou(a, b):
... | StarcoderdataPython |
8084935 | from django.core.management.base import BaseCommand, CommandError
from memes.tasks.fetchmemes import RedditMemeFetcher, GiphyMemeFetcher
class Command(BaseCommand):
help = 'Fetch Memes from each reddit,instagram,giphy,facebook'
''' now only reddit and giphy '''
redditmeme = RedditMemeFetcher()
giphyme... | StarcoderdataPython |
9656096 | # -*- coding: utf-8 -*-
import pytest
from sktime.benchmarking.strategies import TSCStrategy
from sktime.benchmarking.tasks import TSCTask
from sktime.datasets import load_gunpoint
from sktime.datasets import load_italy_power_demand
from sktime.classification.compose import ComposableTimeSeriesForestClassifier
classif... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.