id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9655535 | <gh_stars>0
#!/usr/bin/env python
"""This file contains various utility classes used by GRR data stores."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import collections
import os
import re
import stat
from grr_response_core.lib import rdfvalue
from ... | StarcoderdataPython |
9647643 | # -*- coding: utf8 -*-
import unittest
import os
import sys
import mock
# Change path so we find sdk
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from sdk.api.resource import *
class TestResourcesAPI(unittest.TestCase):
__TEST_TOKEN = "test"
__USER_AGENT = "SDK v2"
__API_CLIENT = "6918a2e6-86e8-... | StarcoderdataPython |
6684663 | <gh_stars>0
"""
Django settings for test_opa project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE... | StarcoderdataPython |
6418887 | <gh_stars>0
# -*- coding:utf-8 -*-
import xmensur
men1 = xmensur.Men()
men2 = xmensur.Men(1)
men11 = men1
print(men1 == men2)
print(men1 == men11)
| StarcoderdataPython |
5152758 | <reponame>pawan3091/pawan
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def RK2(func, X0,tmin,tmax,h,cons):
N=int((tmax-tmin)/h)
t = np.linspace(tmin,tmax,N)
X = np.zeros([N, len(X0)])
X[0] = X0
for i in range(N-1):
k1 =h* func(t[i],X[i],cons)
k2... | StarcoderdataPython |
6684512 | """CLI command to run shell commands on a Lambda Function."""
import json
import os
import subprocess
from pprint import pformat
from typing import Any, Dict, List, Optional
import typer
from boto3 import Session
from .exceptions import LambdaInvocationFailed, ShellCommandFailed, UnexpectedResponse
from .helpers impo... | StarcoderdataPython |
279424 | <gh_stars>0
# Generated by Django 3.1.7 on 2021-03-20 17:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('integration', '0004_auto_20210320_1207'),
]
operations = [
migrations.CreateModel(
name='Broker',
fields... | StarcoderdataPython |
6573226 | <filename>pyGPs/GraphExtensions/__init__.py<gh_stars>100-1000
from __future__ import absolute_import
from . import graphKernels
from . import graphUtil
from . import nodeKernels
| StarcoderdataPython |
8156029 | from django.shortcuts import render
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.db import connection
from django.contrib.auth import authenticat... | StarcoderdataPython |
271205 | from __future__ import annotations
from typing import TYPE_CHECKING, Dict
import logging
import threading
from kubernetes import watch, client
import ipaddress
from k8s_netem.match import LabelSelector
from k8s_netem.resource import Resource
if TYPE_CHECKING:
from k8s_netem.direction import Rule
class Namespac... | StarcoderdataPython |
317767 | <gh_stars>1-10
# coding: utf-8
## pip install tabula-py
#
# Actually, it extracted the table in PDF by tabula-java commond line.
# dependences: java jdk >= v1.7.0
#
import tabula
import pandas as pd
# Convert to DataFrame.
# df = tabula.read_pdf("c.pdf")
# Convert to CSV.
tabula.convert_into("c.pdf", "c.csv", outpu... | StarcoderdataPython |
1631820 | # -*- coding: utf-8 -*-
import re
import json
from socialoauth.sites.base import OAuth2
from socialoauth.exception import SocialAPIError
QQ_OPENID_PATTERN = re.compile('\{.+\}')
class QQApp(OAuth2):
AUTHORIZE_URL = 'https://graph.qq.com/oauth2.0/authorize'
ACCESS_TOKEN_URL = 'https://graph.qq.com/oauth2.0/t... | StarcoderdataPython |
3571069 | from .models import *
from django import forms
class SearchForm(forms.Form):
"""Configure and return a search form."""
q = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'validate'}))
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
... | StarcoderdataPython |
1643362 | import struct
PROP_PAYLOAD_FORMAT_INDICATOR = 1
PROP_MESSAGE_EXPIRY_INTERVAL = 2
PROP_CONTENT_TYPE = 3
PROP_RESPONSE_TOPIC = 8
PROP_CORRELATION_DATA = 9
PROP_SUBSCRIPTION_IDENTIFIER = 11
PROP_SESSION_EXPIRY_INTERVAL = 17
PROP_ASSIGNED_CLIENT_IDENTIFIER = 18
PROP_SERVER_KEEP_ALIVE = 19
PROP_AUTHENTICATION_METHOD = 21
P... | StarcoderdataPython |
11350966 | #!/usr/bin/env python
"""
@package mi.dataset.parser.test
@file marine-integrations/mi/dataset/parser/test/test_flort_dj_sio.py
@author <NAME>, <NAME> (telemetered)
@brief Test code for a flort_dj_sio data parser
"""
import os
from nose.plugins.attrib import attr
from mi.core.exceptions import UnexpectedDataExcepti... | StarcoderdataPython |
3585539 | <filename>csv_specs_generator.py<gh_stars>1-10
import numpy as np
import pandas as pd
import torch
import random
import functools
import os
from trajectories_trans_tools import *
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--path_to_data", help="Path to the original Trajnet data")
parser.ad... | StarcoderdataPython |
122636 | <gh_stars>0
from game_states import *
pygame.init()
FPS = 60
DISPLAY_WIDTH = 600
DISPLAY_HEIGHT = 600
DISPLAY = pygame.display.set_mode([DISPLAY_WIDTH, DISPLAY_HEIGHT])
clock = pygame.time.Clock()
def main_loop():
# TODO: Add a dedicated state manager for this.
game_state = Game_State(DISPLAY_WIDTH, DISPLAY... | StarcoderdataPython |
3587615 | #!/usr/bin/env python2
"""
Reads PDFs in the parent directory, creates directories based on their
names, splits the PDFs and exports the pages into directories based on the original filename.
@Author: <NAME>
Required:
- pip install pyPdf
Inspired by:
- http://stackoverflow.com/questions/490195/split-a-multi... | StarcoderdataPython |
4871246 | <reponame>NeuroDataDesign/lids-bloby
import sys
import numpy as np
import matplotlib.pyplot as plt
import os
import progressbar
from image_processing import (
ImageStack,
read_tif
)
from detectors import (
DoG,
find_negative_curvative_points,
blob_descriptors,
post_prune,
is_well_connected
)... | StarcoderdataPython |
1688197 | <reponame>PwC-FaST/fast-webapp
# Generated by Django 2.1.2 on 2019-01-02 16:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0001_initial'),
('farming', '0001_initial'),
]
o... | StarcoderdataPython |
8041778 | <filename>src/smart_enums/option.py
"""The `Option` type represents an optional value. An Option is either Some, which contains a value or Nothing, which doesn't.
"""
from typing import Any
class Some:
content: str
def __init__(self, content: Any) -> None:
self.content: Any = content
class Noth... | StarcoderdataPython |
4847006 | from collections import OrderedDict
import numpy as np
from ..Operation import Operation
inputs = OrderedDict(x_y_arrays=[])
outputs = OrderedDict(x_ymean=None)
class ArrayYMean(Operation):
"""
Average the second column of one or more n-by-2 arrays
"""
def __init__(self):
super(ArrayYMean, ... | StarcoderdataPython |
4996463 | #!/usr/bin/env python
from argparse import ArgumentParser
from subprocess import Popen
app = "britecore-test"
def build(*args, **kwargs):
cmd = "docker build -t %s:latest ." % app
execute_cmd(cmd)
def start(*args, **kwargs):
cmd = "docker run --name %s --rm -p 8080:8080 %s:latest" % (app, app)
exec... | StarcoderdataPython |
225001 | <filename>get-of-metrics/usr/bin/get-of-metrics.py
#!/usr/bin/python3
import threading
import json
import logging
import paramiko
import argparse
from time import sleep
from prometheus_client import start_http_server
from prometheus_client.core import REGISTRY, CounterMetricFamily
from datetime import datetime
from re... | StarcoderdataPython |
1658851 | class range:
def __init__(self, a, b=None):
if b:
self.index = a
self.end = b
else:
self.index = 0
self.end = a
def __iter__(self):
return self
def __next__(self):
if self.index < self.end:
index = self.index
... | StarcoderdataPython |
8086375 | import requests
from bs4 import BeautifulSoup
import json
def get_pinned(github_user):
URL = f"https://github.com/{github_user}"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
pinned_data = soup.find_all("div", {"class": "pinned-item-list-item-content"})
pinned_posts = ... | StarcoderdataPython |
5036123 | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# <NAME>
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~... | StarcoderdataPython |
5193325 | from mountequist.impostors.http import Http
from mountequist.impostors.https import Https
| StarcoderdataPython |
1960892 | <filename>src/features/.ipynb_checkpoints/word2vec_features-checkpoint.py
import pickle
import numpy as np
from sklearn.preprocessing import MultiLabelBinarizer
from src.eval_metrics import *
from sklearn.model_selection import train_test_split
with open('data/processed/movies_with_overviews.pkl','rb') as f:
fina... | StarcoderdataPython |
6679747 |
global_context = {}
| StarcoderdataPython |
3342080 | <reponame>brightway-lca/brightway2-regional
from bw2data import geomapping
from voluptuous import Invalid
from bw2regional.intersection import Intersection
from bw2regional.tests import BW2RegionalTest
class IntersectionTestCase(BW2RegionalTest):
def test_add_geomappings(self):
inter = Intersection(("foo... | StarcoderdataPython |
5043240 | from subsystems.lightsubsystem import LightSubsystem
import typing
from commands2 import CommandBase
class RelayControl(CommandBase):
def __init__(self, controller: LightSubsystem,
controlPercent: typing.Callable[[], float]) -> None:
CommandBase.__init__(self)
self.control = contr... | StarcoderdataPython |
8037974 | <gh_stars>10-100
import json
import os
import shutil
from datetime import date
from pathlib import Path
import pytest
from ruamel.yaml import YAML
from typing import List, Dict, Any
from vcr import VCR
from vcr.persisters.filesystem import FilesystemPersister
from simple_smartsheet import Smartsheet, AsyncSmartsheet
... | StarcoderdataPython |
8194477 | <reponame>mycolab/ncbi-blast<gh_stars>0
#!/usr/bin/env python
# $Id: python-config.py 503831 2016-06-08 14:54:36Z ucko $
from distutils import sysconfig
import sys
def lookup(want):
if want == 'VERSION':
return sysconfig.get_config_var('VERSION')
elif want == 'INCLUDE':
return ('-I%s -I%s' % (... | StarcoderdataPython |
1870113 | # coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | StarcoderdataPython |
29087 | from django.core.serializers.json import DjangoJSONEncoder
class CallableJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if callable(obj):
return obj()
return super().default(obj)
| StarcoderdataPython |
1773680 | #!/usr/bin/env python
############################################
#
# Login to supercomputer and cd to current work directory
# Apr11 ; greatly simplified by using read_pm functions
# Apr4 ; add option for custom ip addr
# Mar19 ; translated to python by genki
# next logs will be on the git commits
#
##... | StarcoderdataPython |
1996783 | # #!/usr/bin/env python
#
# """
# @package ion.agents.platform.rsn.test.oms_simple
# @file ion/agents/platform/rsn/test/oms_simple.py
# @author <NAME>
# @brief Program that connects to the real RSN OMS endpoint to do basic
# verification of the operations. Note that VPN is required.
# Also, port... | StarcoderdataPython |
1765850 | import cv2
import numpy as np
img = cv2.imread("4.2 face.png")
# casede dosyamızı ekliyoruz
face_cascade = cv2.CascadeClassifier("4.3 frontalface.xml")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3,
7) # 1.3 ölçeklemek için ve 4 d... | StarcoderdataPython |
9739927 | """The Modified Differential Multiplier Method (MDMM) for PyTorch."""
from .mdmm import (ConstraintReturn, Constraint, EqConstraint, MaxConstraint, MaxConstraintHard,
MinConstraint, MinConstraintHard, BoundConstraintHard, MDMMReturn, MDMM)
__version__ = '0.1.3'
| StarcoderdataPython |
4870823 | from ..core.ControllerService import ControllerService
class GCPCredentialsControllerService(ControllerService):
def __init__(self, name=None, credentials_location=None, json_path=None, raw_json=None):
super(GCPCredentialsControllerService, self).__init__(name=name)
self.service_class = 'GCPCrede... | StarcoderdataPython |
1804461 | from django.db import models
from django.utils.translation import gettext_lazy as _
# class MyModel(models.Model):
#
# title = models.CharField(_('Title'), max_length=100, help_text=_('Description'))
#
# class Meta:
# verbose_name = _('Model')
# verbose_name_plural = _('Models')
#
# def __... | StarcoderdataPython |
8066411 | <reponame>git-wwts/pysyte
"""Some keyboard handling code"""
import sys
from pysyte.oss import getch
def _get_chosen_chars(chooser):
while True:
key = getch.get_as_key()
try:
if chooser(key):
return key
except AttributeError:
print(key)
... | StarcoderdataPython |
6448 | <gh_stars>0
# MINLP written by GAMS Convert at 01/15/21 11:37:33
#
# Equation counts
# Total E G L N X C B
# 1486 571 111 804 0 0 0 0
#
# Variable counts
# x b i s1s s2... | StarcoderdataPython |
3523684 | <filename>justree/bfs.py
from collections import deque
from typing import Iterable, List, Tuple, Deque, Optional, Union
from .tools import reversed_enumerate, T
from .tree_node import TreeNode
def non_recursive_tree_bfs_forward_original(self: T) -> Iterable[T]:
assert isinstance(self, TreeNode)
q: Deque[Tree... | StarcoderdataPython |
12839846 | # -*- coding: utf-8 -*-
"""Test functions that get data."""
import os
import unittest
from bio2bel_uniprot import get_mappings_df
HERE = os.path.abspath(os.path.dirname(__file__))
URL = os.path.join(HERE, 'test.tsv')
class TestGet(unittest.TestCase):
"""Test getting data."""
def test_get_mappings(self):
... | StarcoderdataPython |
3293728 | from hattori.base import BaseAnonymizer, faker
from users.models import User
class UserAnonimizer(BaseAnonymizer):
model = User
attributes = [
('first_name', faker.first_name),
('last_name', faker.last_name),
('email', faker.email),
('username', faker.ssn),
]
def run(... | StarcoderdataPython |
11373166 | <reponame>robashaw/basisopt
from basisopt import bse_wrapper as bsew
import basis_set_exchange as bse
from tests.data import shells as shell_data
import pytest
def test_make_bse_shell():
internal_vdz = shell_data.get_vdz_internal()
vdz_h = internal_vdz['h']
bse_s_shell = bsew.make_bse_shell(vdz_h[0])
... | StarcoderdataPython |
8100085 | # ---------------------------------------------------------------------------------------------------------------------
# lfsr_template.py
# ---------------------------------------------------------------------------------------------------------------------
# Generate Verilog LFSR module and testbench
# --------------... | StarcoderdataPython |
1670956 | <filename>py_hawkesn_sir/py_hawkesn_sir/hawkesn_seir_sympy.py
# from scipy.optimize import fmin_l_bfgs_b
import numpy as np
import matplotlib.pyplot as plt
from sympy import derive_by_array, exp, lambdify, log, Piecewise, symbols
class HawkesN:
def __init__(self, history):
"""
Parameters
... | StarcoderdataPython |
8183585 | """
MIT License
Copyright (c) 2018 <NAME> Institute of Molecular Physiology
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, co... | StarcoderdataPython |
1900081 | # -*- coding: UTF-8 -*-
import sys
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
from db.SaUsersDB import dbUsersHelper
"""
Set synology nas host ip and port to database
"""
def SetNasHostI... | StarcoderdataPython |
5079311 | <gh_stars>0
from ctypes import *
import time
msvcrt = cdll.msvcrt
counter = 0
while 1:
msvcrt.printf("Loop iteration %d!\n" % counter)
time.sleep(2)
counter += 1
| StarcoderdataPython |
8177402 | <gh_stars>1-10
#!/usr/bin/env python
from http.client import HTTPConnection
import json
import re
def parse_args(parts):
(typ, req) = ({}, set())
for i in range(2, len(parts), 2):
arg = re.sub(r'\W', '', parts[i+1])
typ[arg] = parts[i]
if arg == parts[i+1]:
req.add(arg)
return (typ, req)
def ... | StarcoderdataPython |
1832243 | <reponame>jorgemauricio/proyectoCaborca
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
"""
# librerías
import os
import urllib.request
import time
from time import gmtime, strftime
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
f... | StarcoderdataPython |
3549821 | <reponame>jacksonicson/paper.IS2015<filename>control/Control/src/balancer/placement_nextfit.py
from logs import sonarlog
import conf_domainsize as domainsize
import conf_nodes as nodes
import model
import placement
import conf_schedule
# Setup Sonar logging
logger = sonarlog.getLogger('placement')
class NextFit(place... | StarcoderdataPython |
5088177 | <filename>bokeh/protocol/messages/pull_doc_reply.py
from __future__ import absolute_import, print_function
from ..exceptions import ProtocolError
from ..message import Message
from . import register
import logging
log = logging.getLogger(__name__)
@register
class pull_doc_reply_1(Message):
''' Define the ``PULL-... | StarcoderdataPython |
5165271 | <filename>gibson/core/physics/robot_bases.py
## Author: pybullet, <NAME>
import pybullet as p
import gym, gym.spaces, gym.utils
import numpy as np
import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
os.sys.path.insert(0,paren... | StarcoderdataPython |
5191103 | #!/usr/bin/python
"""
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 limitation the rights
to use, copy, modify, merge, publish, ... | StarcoderdataPython |
4899242 | from __future__ import division, print_function
import numpy as np
import sys,os
sys.path.append("..")
import pyrads
from scipy.integrate import trapz,simps,cumtrapz
### -----------------------------------
### Helpers
class Dummy:
pass
### -----------------------------------
# ---
## setup thermodynamic param... | StarcoderdataPython |
3430040 | import datetime
from enum import Enum
from pydantic import BaseModel, Field
class SchoolDistricts(Enum):
davis_district = "Davis District"
alpine_district = "Alpine District"
canyons_district = "Canyons District"
granite_district = "Granite District"
jordan_district = "Jordan District"
nebo_d... | StarcoderdataPython |
9763199 | import torch
import numpy as np
import cv2
import os
class PawpularDataset(torch.utils.data.Dataset):
def __init__(self, csv, data_path, mode='train', augmentations=None, meta_features=None):
self.csv = csv
self.data_path = data_path
self.mode = mode
self.augmentations = augmentat... | StarcoderdataPython |
6677050 | <filename>utils/builder/register_builder/riscv/BootPriority.py
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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... | StarcoderdataPython |
3450821 | <filename>core/client.py
"""
Hbtn Module
"""
from typing import List, Dict, Union, Any
import requests
from bs4 import BeautifulSoup
JsonType = Dict[str, Union[List[Dict[str, Union[list, Any]]], Any]]
class Hbtn:
"""
Class that authenticates to the intranet website,
and fetches json data of a project re... | StarcoderdataPython |
3406737 | import fridge.Constituent.Smear as Smear
import fridge.utilities.mcnpCreatorFunctions as mcnpCF
class FuelCoolant(Smear.Smear):
"""Creates the coolant surrounding the fuel pin.
This coolant is a homogenized material consisting of the coolant material and the wirewrap."""
def __init__(self, unitInfo, voidM... | StarcoderdataPython |
322039 | import os
import base64
import requests
from io import BytesIO
from PIL import Image, ImageDraw, ImageOps, ImageColor
from abc import abstractmethod
from flask import request, abort
from flask_restful import Resource
class ImageFunctions(object):
@staticmethod
def get_color(color):
try:
... | StarcoderdataPython |
306157 | <reponame>brystmar/greeting-cards<filename>backend/config.py
"""Defines the object to configure parameters for our Flask app."""
from logging import getLogger
from os import environ, path
logger = getLogger()
class Config(object):
logger.debug("Start of the Config() class.")
# If the app is running locally,... | StarcoderdataPython |
393207 | <reponame>vadim-ivlev/STUDY
def twoStacks(x, a, b):
score = 0
total = 0
while total < x:
if a != [] and b != []:
if a[0] < b[0]:
if total+a[0] < x:
total += a.pop(0)
score += 1
else:
break
... | StarcoderdataPython |
1605795 | #----------------------------
# Author: <NAME>
#----------------------------
from collections import namedtuple
import numpy as np
import math
FILE_TYPE = "P2" # to verify the file type
PGMFile = namedtuple('PGMFile', ['max_shade', 'data']) # named tuple
# This function receives the name of a file, reads it in, v... | StarcoderdataPython |
203483 | import os
import importlib
from pathlib import Path
import getpass
import inspect
import pickle
from unittest.mock import Mock
import pytest
import yaml
import numpy as np
from ploomber.env.env import Env
from ploomber.env.decorators import with_env, load_env
from ploomber.env import validate
from ploomber.env.envdic... | StarcoderdataPython |
302561 | from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto import Random
import ast, os, random, struct, string
class AES_cipher():
def __init__(self, passcode):
self.passcode = passcode
self.iv = bytes(16*'\x00'.encode())
self._add_padding()
def _add_padding(self):
... | StarcoderdataPython |
9742508 | # Copyright 2016 Autodesk 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
#
# Unless required by applicable law or agreed to in writing... | StarcoderdataPython |
11299440 | <reponame>animator/orange3-scoring<gh_stars>1-10
import numpy as np
from AnyQt.QtWidgets import QGridLayout, QSizePolicy as Policy
from AnyQt.QtCore import QSize
from Orange.widgets.widget import OWWidget, Msg, Output
from Orange.data import Table, DiscreteVariable, Domain, ContinuousVariable
from Orange.widgets impo... | StarcoderdataPython |
11323393 | '''Implements the infrastructure to spread indexing tasks over a single
:class:`~.RandomAccessScanSource` across multiple processes for speed.
The primary function in this module is :func:`index`, which will perform
this dispatch.
'''
import multiprocessing
import logging
import dill
from .scan_index import Extended... | StarcoderdataPython |
11261382 | __all__ = ['pcap', 'logger'] | StarcoderdataPython |
1819330 | <filename>app/model.py
import json
class Post():
def __init__(self, title, image, summary, post, author, author_id):
self.summary = summary
self.image = image
self.post = post
self.title = title
self.author = author
self.author_id = author_id
def toJSON(self):
... | StarcoderdataPython |
1710933 | <filename>src/medius/mediuspackets/getallclanmessagesresponse.py
from enums.enums import MediusEnum, CallbackStatus
from utils import utils
from enums.enums import MediusIdEnum
class GetAllClanMessagesResponseSerializer:
data_dict = [
{'name': 'mediusid', 'n_bytes': 2, 'cast': None}
]
@classmetho... | StarcoderdataPython |
373607 | <gh_stars>1-10
from bs4 import BeautifulSoup
import pytest
import shutil
@pytest.mark.sphinx("html", testroot="hiddendirectives")
def test_warning(app, warnings):
"""Test warning thrown during the build"""
build_path = app.srcdir.joinpath("_build")
shutil.rmtree(build_path)
app.build()
assert (
... | StarcoderdataPython |
1686683 | <filename>spectrum/django/spectrum.py
FIRE_HOSE = {
'version': 1,
'disable_existing_loggers': False,
'root': {
'level': 'DEBUG',
'handlers': ['console', 'root']
},
'filters': {
'request_id': {
'()': 'spectrum.filters.RequestIdFilter'
}
},
'formatte... | StarcoderdataPython |
3594136 | # Here goes the ball class
import pygame
from config import BALL_VELOCITY, SCREEN_HEIGHT, SCREEN_WIDTH, colors
class Ball_1(pygame.sprite.Sprite):
def __init__(self, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.width = width
self.height = hei... | StarcoderdataPython |
9714762 | <reponame>LauraOlivera/gammapy<gh_stars>0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Spectral models for Gammapy."""
import operator
import numpy as np
import scipy.optimize
import scipy.special
import astropy.units as u
from astropy import constants as const
from astropy.table import Table
from... | StarcoderdataPython |
187895 | <filename>application/api/dashboard.py
from flask_restful import Resource, reqparse
from application.common.common_exception import ResourceNotAvailableException
from application.common.constants import APIMessages
from application.common.response import (api_response, STATUS_OK)
from application.common.token import t... | StarcoderdataPython |
78122 | <filename>enaml/qt/qt_label.py
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------... | StarcoderdataPython |
3523222 | from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(
User, null=True, blank=True, related_name='user_profile', on_delete=models.CASCADE)
def __str__(self):
return self.user.username if self.user else st... | StarcoderdataPython |
9677580 | <reponame>ilindrey/whatyouknow<filename>apps/comments/urls.py
from django.urls import path, include
from .views import CommentListView, CreateCommentView, EditCommentView
urlpatterns = [
path('ajax/', include([
path('load_comment_list', CommentListView.as_view(), name='comment_list'),
path('create... | StarcoderdataPython |
1726150 | import re
from mongoframes.factory import blueprints
from mongoframes.factory import makers
from mongoframes.factory import quotas
from mongoframes.factory.makers import selections as selection_makers
from mongoframes.factory.makers import text as text_makers
from tests.fixtures import *
def test_maker():
"""
... | StarcoderdataPython |
6682917 | from typing import Optional
from .base import Base
class TzInfo(Base):
# Time zone in seconds from UTC
offset: int
# Name of the time zone
name: str
# Abbreviated name of the time zone
abbr: Optional[str]
# Daylight saving time
dst: Optional[bool]
class Info(Base):
# The latitud... | StarcoderdataPython |
135206 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
from typing import Any, Callable, Dict, List, Optional
import torch.nn as nn
from pytext.contrib.pytext_lib.data.datasets.batchers import Batcher
from pytext.contrib.pytext_lib.data.datasets.pytext_dataset impo... | StarcoderdataPython |
8070877 | <reponame>zhnlks/ShiPanE-Python-SDK
# -*- coding: utf-8 -*-
import codecs
import os
import unittest
import six
from six.moves import configparser
if six.PY2:
ConfigParser = configparser.RawConfigParser
else:
ConfigParser = configparser.ConfigParser
from shipane_sdk.joinquant.client import JoinQuantClient
c... | StarcoderdataPython |
87548 | <gh_stars>1-10
from typing import Dict
import numpy as np
from qulacs import QuantumCircuit
from qulacs.gate import CNOT, TOFFOLI, DenseMatrix, to_matrix_gate
def load_circuit_data() -> Dict[str, QuantumCircuit]:
circuits = {}
circuits["empty_circuit"] = empty_circuit()
circuits["x_gate_circuit"] = x_gat... | StarcoderdataPython |
288669 | <gh_stars>100-1000
class Tape:
"""
Allows writing to end of a file-like object while maintaining the read pointer accurately.
The read operation actually removes characters read from the buffer.
"""
def __init__(self, initial_value:str=''):
"""
:param initial_value: initialize the T... | StarcoderdataPython |
3273137 | <reponame>YoungxHelsinki/GoldenRatio
import csv_lab
csv_path = '/Users/young/datahackathon/vuokraovi_retrieve/no_decimal.csv'
csv_list = csv_lab.csv_to_list(csv_path)
pos = 5
columns = ['image']
new_path = 'no_decimal_imgage.csv'
csv_lab.insert_column(csv_list, columns, 5, new_path)
| StarcoderdataPython |
396027 | <reponame>daobook/myst-parser
"""Uses sphinx's pytest fixture to run builds.
see conftest.py for fixture usage
NOTE: sphinx 3 & 4 regress against different output files,
the major difference being sphinx 4 uses docutils 0.17,
which uses semantic HTML tags
(e.g. converting `<div class="section">` to `<section>`)
"""
i... | StarcoderdataPython |
3543717 | import warnings
from dataclasses import dataclass
from pathlib import Path
from typing import List, Union, Dict
from unittest import main, TestCase
from openmaptiles.sql import collect_sql, sql_assert_table, sql_assert_func
from openmaptiles.tileset import ParsedData, Tileset
@dataclass
class Case:
id: str
q... | StarcoderdataPython |
1957278 | <reponame>qianchilang/learning-pytest
def test_option1(pytestconfig):
print('host: %s' % pytestconfig.getoption('host'))
print('port: %s' % pytestconfig.getoption('port'))
def test_option2(config):
print('host: %s' % config.getoption('host'))
print('port: %s' % config.getoption('port'))
| StarcoderdataPython |
5019614 | <reponame>nickgaya/acsearch<gh_stars>0
"""
Implementation of the Aho-Corasick string search algorithm.
See https://en.wikipedia.org/wiki/Aho-Corasick_algorithm
"""
from collections import deque
from functools import wraps
def cached_property(method):
""" Decorator to create a lazy property that is cached on fir... | StarcoderdataPython |
11245901 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2015-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the Licen... | StarcoderdataPython |
130677 | """
implementation of criteo dataset
"""
# pylint: disable=unused-argument,missing-docstring
import os
import sys
import re
import random
import numpy as np
from intel_pytorch_extension import core
import inspect
# pytorch
import torch
from torch.utils.data import Dataset, RandomSampler
import os
# add dlrm code pa... | StarcoderdataPython |
317937 | <gh_stars>0
from setuptools import setup, find_packages
requirements = ['cycler==0.10.0',
'future==0.15.2',
'geopy==1.11.0',
'isodate==0.5.4',
'nose==1.3.7',
'numpy==1.14.4',
'pandas==0.20.2',
'patsy==0.4.1'... | StarcoderdataPython |
3312223 | from abaqusConstants import *
from .ConstrainedSketchGeometry import ConstrainedSketchGeometry
class getPointAtDistance(ConstrainedSketchGeometry):
def __init__(self, point: tuple[float], distance: str, percentage: Boolean = OFF):
"""This method returns a point offset along the given ConstrainedSketchGeo... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.