id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1856724 | <filename>python/tests/tests_api_client/testSelection.py
import unittest
import sys
import os
sys.path.append(os.path.abspath('../..'))
import api_example
from api_client import Client, StagingClient
from requests import exceptions
import json
import time
SELECTION_ID = api_example.SELECTION_ID
class TestCase(unittes... | StarcoderdataPython |
12819429 | <reponame>MonolithAILtd/caching
"""this file defines the worker for managing local cache directories"""
import datetime
import os
import shutil
from typing import Optional
from uuid import UUID
from .errors import WorkerCacheError
from .register import Register
class Worker:
"""
This is a class for managing ... | StarcoderdataPython |
1870268 | <filename>tests/sync/conftest.py
import os
import pytest
import dotenv
from codingame import Client
dotenv.load_dotenv()
@pytest.fixture(name="client", scope="function")
def create_client() -> Client:
with Client() as client:
yield client
@pytest.fixture(name="auth_client")
def create_logged_in_clien... | StarcoderdataPython |
1896241 | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2009 <NAME> All rights reserved.
#
"""
"""
#end_pymotw_header
import abc
from abc_base import PluginBase
import abc_subclass
import abc_register
for sc in PluginBase.__subclasses__():
print sc.__name__
| StarcoderdataPython |
9618160 | <reponame>lorycontixd/LiteBIRD-inclination-analysis
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from __future__ import print_function
import math
import models
import importlib
from tabulate import tabulate
from dataclasses import dataclass
import json
import time
import os,sys
from pathlib import Path
from shutil... | StarcoderdataPython |
1618327 | import numpy as np
from pylab import sqrt,linspace,array,argmax
from scipy.interpolate import RegularGridInterpolator, RectBivariateSpline
import math
from constants import *
'''
colorToProj: color -> projected
dataToProj: data -> projected
colorCoord: data, projected -> color
dataToColor: data -> color
colorToD... | StarcoderdataPython |
3253248 | # Copyright (c) 2004 Divmod.
# See LICENSE for details.
from twisted.internet import defer
from nevow import context, inevow
from nevow import testutil
from nevow.flat import twist
from nevow.util import Deferred
from nevow import rend, loaders, tags
def deferit(data):
return data.d
def deferdot(data):
... | StarcoderdataPython |
3259011 | from __future__ import division
def diff_percentage(max_count, min_count, **kwargs):
difference_count = int(max_count) - int(min_count)
if difference_count == 0:
return 0
variation = int(difference_count/int(min_count))*100
return variation
| StarcoderdataPython |
6568893 | import os
import re
import argparse
import csv
import numpy as np
import pandas as pd
from AnalyzeMotionThroughTime import analyze_motion as analyze_motion_through_time
from AnalyzeMotionThroughTime import get_baseline
def parse_arguments():
parser = argparse.ArgumentParser("Analyzes the predictions across all m... | StarcoderdataPython |
8036653 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 10:17:32 2020
@author: briere
"""
import argparse
import logging
from GraphMetrics import *
from neo4j import GraphDatabase
descr = '''This script computes the optimal number of supports to cluster the IntegrationGraph.
Once filtered, the graph... | StarcoderdataPython |
340029 | from fastapi.testclient import TestClient
from app.core.config import settings
def test_hello_world(client: TestClient) -> None:
resp = client.get("/hello-world")
data = resp.json()
assert data["msg"] == "Hello world!"
| StarcoderdataPython |
1737656 | <reponame>snoopyjc/pythonizer
def _caller(expr=None):
""" Implementation of caller function in perl"""
try:
fr = sys._getframe(2 if expr is None else (max(int(expr),0)+1))
package = 'main'
if hasattr(fr.f_builtins, '__PACKAGE__'):
package = fr.f_builtins.__PACKAGE__
... | StarcoderdataPython |
3476187 | """
Author: <NAME>
Date: Today
This file is some simple calculations for Tom
"""
import numpy as np
import scipy.linalg as la
from hk_price_optimisticbeliefs import price_optimisticbeliefs
from hk_price_singlebeliefs import price_singlebeliefs
from hk_price_pessimisticbeliefs import price_pessimisticbeliefs
# ------... | StarcoderdataPython |
224517 | <filename>black_list/black_list/middlewares.py
# -*- coding: utf-8 -*-
class ProxyMiddleware(object):
def __init__(self, proxy_url):
self.proxy_url = proxy_url
def process_request(self, request, spider):
request.meta['proxy'] = self.proxy_url
@classmethod
def from_crawler(cls, crawle... | StarcoderdataPython |
6662608 | from scrapy import cmdline
name = '../spiders/itacasaCatalogSpider.py'
cmd = 'scrapy runspider {0}'.format(name)
cmdline.execute(cmd.split())
| StarcoderdataPython |
8122414 | <reponame>Cogito2012/DEAR
from ..registry import RECOGNIZERS
from .recognizer3d import Recognizer3D
@RECOGNIZERS.register_module()
class Recognizer3DRPL(Recognizer3D):
"""3D recognizer model framework."""
def forward_train(self, imgs, labels, **kwargs):
"""Defines the computation performed at every c... | StarcoderdataPython |
1706940 | <reponame>h-terao/hazuchi<gh_stars>0
from __future__ import annotations
import jax
import jax.numpy as jnp
from flax import struct
import chex
@struct.dataclass
class Observation:
"""An immutable class to summarize metrics.
Attributes:
values (dict of str: tuple[array, array]): Accumulated metrics to... | StarcoderdataPython |
4949579 | import unicodedata
from .models import *
from django import forms
from django.contrib.auth import (
authenticate, get_user_model, password_validation,
)
from django.contrib.auth.hashers import (
UNUSABLE_PASSWORD_PREFIX, identify_hasher,
)
from django.contrib.auth.models import User
from django.contrib.auth.t... | StarcoderdataPython |
1702178 | <reponame>ronekko/differential_geometry
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 17 20:58:03 2021
@author: ryuhei
"""
import matplotlib.pyplot as plt # type: ignore
import numpy as np # type: ignore
import open3d as o3d # type: ignore
import torch
def spherical_to_cartesian(u, radius=1.0):
theta = u.T[... | StarcoderdataPython |
1763562 | <reponame>Gothingbop/JT_AWS
import pip
def InstallRequirements(requirements_path, target_path):
"""
Installs all the packages for an AWS Lambda function.
This function tries to install the version of a package built for the specific operating system that AWS Lambda functions run on
:param requiremen... | StarcoderdataPython |
1877886 | """
training_dataset.py
"""
# 3rd party imports
import os
import pickle
import numpy as np
class TrainingDataset:
"""Training dataset for machine learning."""
def __init__(self, train_geochem_index, x_train, y_train, hole_id_train, depth_train, train_holes,
test_geochem_index, x_test, y_te... | StarcoderdataPython |
87736 | # following PEP 386
__version__ = "1.0b1"
# Do some sane version checking
import django
import mptt
if django.VERSION < (1,3,0):
raise ImportError("At least Django 1.3.0 is required to run this application")
if mptt.VERSION < (0,5,1):
raise ImportError("At least django-mptt 0.5.1 is required to run this appl... | StarcoderdataPython |
4807282 | def register_blueprint(app):
from apps.schedule import job
from apps.schedule import history
app.register_blueprint(job.blueprint, url_prefix='/schedule/jobs')
app.register_blueprint(history.blueprint, url_prefix='/schedule/histories')
| StarcoderdataPython |
4979514 | # -*- coding:utf-8 -*-
import codecs
import os
import jieba
stopwords_path = "./setting/stop_words.txt"
synonyms_path = "./setting/synonyms_words.txt"
user_dicts = "./setting/user_defined_dicts.txt"
def is_instr(str):
if "一" in str or \
"二" in str or \
"三" in str or \
... | StarcoderdataPython |
1733807 | """
Tests for magic imports.
"""
import os
import time
import pandas as pd
from six import string_types
from quilt.nodes import GroupNode, DataNode
from quilt.tools import command
from quilt.tools.const import PACKAGE_DIR_NAME
from quilt.tools.package import Package, PackageException
from quilt.tools.store import Pa... | StarcoderdataPython |
8089216 | '''
Atomix project, orapp.py, (TODO: summary)
Copyright (c) 2015 Stanford University
Released under the Apache License v2.0. See the LICENSE file for details.
Author(s): <NAME>
'''
import abc
INFINITY = 999999
class OrApp:
__metaclass__ = abc.ABCMeta
def __init__(self):
self.states = []
self.blocksUsed ... | StarcoderdataPython |
4931999 | <filename>notebook/so.py
# ref: https://stackoverflow.com/a/46901839/4886384
# code by <NAME>
import numpy as np
def align_yaxis_np(axes):
"""Align zeros of the two axes, zooming them out by same ratio"""
axes = np.array(axes)
extrema = np.array([ax.get_ylim() for ax in axes])
# reset for divide by ... | StarcoderdataPython |
6506199 | <gh_stars>0
from pangea.AST import Case, Property, Concat, When
class Pangea(object):
"""
singleton to help with building Pangea ADTS
"""
@classmethod
def Case(cls, *args, **kwargs):
return Case(*args, **kwargs)
def __call__(self, *args, **kwargs):
return Property(*args, **kw... | StarcoderdataPython |
8039513 | import matplotlib.pyplot as plt
import numpy as np
from bandit import Bandit
from rpp import RelativePayoffProcedure
"""
Comparison of the Bandit Algorithm with and without inference.
"""
if __name__ == '__main__':
k = 5
iterations = 20
avg_reward1 = np.zeros((20, 5000))
avg_reward2 = np.zeros((20, 5... | StarcoderdataPython |
4945785 | # -*- Mode: Python -*-
import re
import coro
import coro.read_stream
from protocol import http_file, header_set, latch
W = coro.write_stderr
class HTTP_Protocol_Error (Exception):
pass
class Bad_Response (HTTP_Protocol_Error):
pass
# viewed at its core, HTTP is a two-way exchange of messages,
# some of w... | StarcoderdataPython |
8095724 | from contextlib import contextmanager
from unittest.mock import patch
import pytest
from progress_interface.base import default_config, progress_config, get_progress, iter_progress, \
NullProgressMonitor, REGISTRY
from progress_interface.test import TestProgressMonitor
from progress_interface.monitors import TqdmPro... | StarcoderdataPython |
1856218 | <reponame>YTRedstone/Autoclicker-CPS-Tester<gh_stars>0
from tkinter import *
import mouse
import datetime
#############################################
#############################################
end = 0
lt55s = "False"
endtimesecond = "-1"
endtimeminute = "-1"
endtimehour = "-1"
endtimeday = "-1"
endtimem... | StarcoderdataPython |
1937296 | import gevent
from gevent.pywsgi import WSGIServer
from gevent.lock import Semaphore
from geventwebsocket.handler import WebSocketHandler, WebSocketError
from datetime import datetime
def websocket_app(environ, start_response):
if environ["PATH_INFO"] == '/ws/echo':
ws = environ["wsgi.websocket"]
print ... | StarcoderdataPython |
6611215 | <reponame>alexanders0/farm-management
"""User views."""
# Django
from django.conf import settings
# Django REST Framework
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser
# ... | StarcoderdataPython |
3394031 | #Задача № 6. Вариант 28
#Создайте игру, в которой компьютер загадывает название одного из шести континентов Земли, а игрок должен его угадать.
# <NAME>
#25.05.2016
import random
print("Компьютер загадывает название одного из шести континентов Земли, а игрок должен его угадать.")
kontinents=('Евразия','Африка','Австр... | StarcoderdataPython |
8069410 | """Loads reference data to memory."""
import pkg_resources
import ujson
def load_dict() -> dict:
"""
Loads reference data to dictionary.
:return: dictionary of the syllable reference data
"""
file_name = "data.json"
file_path = pkg_resources.resource_filename(__name__, file_name)
with ope... | StarcoderdataPython |
1647169 | import pygame as pyg
import math
pyg.init()
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
LIGHT_BLUE = (128, 191, 255)
LEFT = 1
FILE = "tree-diagram.txt"
tree_file = open(FILE, "w")
# Window size
SIZE = (1121, 485)
# Font info
FONT = pyg.font.SysFont('Calibri', 22, True, F... | StarcoderdataPython |
11321974 | n = int(input())
l = list(map(int,input().split()))
ans = n-1
while ans>0 and l[ans-1]<l[ans]:
ans-=1
print(ans)
| StarcoderdataPython |
8160925 | # Presenter layer responsibility
# 1. define presenter class which depends on output interface and it has emit method to call outputPort.emit()
# 2. define outputPort interface
from .output_port import DataSourceUseCaseOutputPort
| StarcoderdataPython |
9761029 | <filename>neural_net/neural_net.py
"""
Author: <NAME>
Neural Network Model
"""
import math
class NeuralNetwork(object):
"""
Neural Network Library
"""
def dot(v, w):
"""
v_1 * w_1 + ... + v_n * w_n
"""
return sum(v_i * w_i for v_i, w_i in zip(v, w))
def sigmoid(sel... | StarcoderdataPython |
9650331 | <reponame>kanishkan/tce
# Copyright 2004 <NAME>.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""This package defines all user messages (warnings + errors), which will be
reported to user.
"""
class m... | StarcoderdataPython |
6670969 | <reponame>egonw/scheduled-bots
## Bot for adding Prop65 ID
from wikidataintegrator import wdi_core, wdi_login, wdi_helpers
from wikidataintegrator.ref_handlers import update_retrieved_if_new_multiple_refs
import pandas as pd
from pandas import read_csv
import requests
import time
from datetime import datetime
import c... | StarcoderdataPython |
3270567 | from .base_test import TestDDNSUpdaterConfigHelper
from .google_synthetic_ddns_test import TestGoogleSyntheticDDNSConfigHelper
| StarcoderdataPython |
1959466 | # Helper functions for easy saving and loading of named results
import os
import pickle
import gzip
import errno
import inspect
import time
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICKLES_PATH = os.path.join(CURRENT_DIR, 'pickles')
def _pickled_name(name):
return os.path.join(PICKLES_PATH, na... | StarcoderdataPython |
3377643 | <reponame>dyens/sdk-python
""" Audit.
Do not edit this file by hand.
This is generated by parsing api.html service doc.
"""
from ambra_sdk.exceptions.service import FilterNotFound
from ambra_sdk.exceptions.service import InvalidBucket
from ambra_sdk.exceptions.service import InvalidCondition
from ambra_sdk.exceptions.... | StarcoderdataPython |
9604958 | <gh_stars>1-10
import json
import boto3
import sys
import os
def upload_to_s3(file):
with open("crds.json") as f:
setup = json.load(f)
f.close()
AWS_ACCESS_KEY_ID = setup["AWS_ACCESS_KEY_ID"]
AWS_SECRET_ACCESS_KEY = setup["AWS_SECRET_ACCESS_KEY"]
session = boto3.Session(
... | StarcoderdataPython |
11361393 | <filename>object_detection/utils/ssd/ssd512_config_resnet.py<gh_stars>1-10
import numpy as np
import collections
from .ssd_utils import generate_ssd_priors
SSDBoxSizes = collections.namedtuple('SSDBoxSizes', ['min', 'max'])
SSDSpec = collections.namedtuple('SSDSpec', ['feature_map_size', 'shrinkage', 'box_sizes', 'asp... | StarcoderdataPython |
63300 | # Generated by Django 4.0 on 2021-12-16 19:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("episodes", "0021_auto_20210922_1012"),
]
operations = [
migrations.AddField(
model_name="episode",
name="link",
... | StarcoderdataPython |
339802 | #
# Copyright (C) 2019 Databricks, 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 i... | StarcoderdataPython |
80502 | <filename>bcbio/pipeline/datadict.py
"""
functions to access the data dictionary in a clearer way
"""
import toolz as tz
from bcbio.utils import file_exists
from bcbio.log import logger
import sys
LOOKUPS = {
"gtf_file": {"keys": ['genome_resources', 'rnaseq', 'transcripts'],
"checker": file_exis... | StarcoderdataPython |
1928319 | #!/usr/bin/env python
__author__ = '<EMAIL>'
import os
import sys
from common import Smali
from common import Java
from common import File
from common import DataFile
from common import AccessSmali
class NameToNum:
def __init__(self, name, path, smaliList):
self.name = name
self.path = path
... | StarcoderdataPython |
9790067 | from django.db import migrations, models
import mayan.apps.documents.models.document_version_models
import mayan.apps.storage.classes
class Migration(migrations.Migration):
dependencies = [
('documents', '0047_auto_20180917_0737'),
]
operations = [
migrations.AlterField(
model... | StarcoderdataPython |
11234964 | from django.db import models
# Create your models here.
class Book(models.Model):
pass
class Shelf(models.Model):
pass
| StarcoderdataPython |
8186249 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 15:43:09 2020
@author: meco
"""
import sys
import unittest
import inspect
import io
import pep8
from datetime import datetime
from contextlib import redirect_stdout
from models.user import User
class TestUser(unittest.TestCase):
"""
class fo... | StarcoderdataPython |
1879523 | """
Copyright (C) 2018-2020 Intel Corporation
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 i... | StarcoderdataPython |
4981929 | <reponame>roemmele/answerquest<filename>qna_server/server.py
import sys
import os
root_dir = os.path.realpath('../')
sys.path.insert(0, root_dir)
import warnings
warnings.filterwarnings('ignore')
import argparse
import json
from flask import Flask, request, render_template, jsonify
from answerquest import QnAPipelin... | StarcoderdataPython |
8080140 | <reponame>LXie502/point_based_pcgc
import math
import torch.nn as nn
import torch
import torch.nn.functional as F
class HyperEncoder(nn.Module):
def __init__(self, input_dim):
super(HyperEncoder, self).__init__()
self.input_dim = input_dim
self.fc1 = nn.Linear(input_dim, input_dim)... | StarcoderdataPython |
1638608 | import random
import numpy as np
from sum_tree import SumTree
class Memory:
def __init__(self, tree_memory_length, error_multiplier=0.01, alpha=0.6, beta=0.4, beta_increment_per_sample=0.001):
self.tree = SumTree(tree_memory_length)
self.tree_memory_length = tree_memory_length
self.error_m... | StarcoderdataPython |
6529847 | <filename>gradchange.py
import argparse
__author__ = 'MattC'
parser = argparse.ArgumentParser(description= \
'Script to batch plot all Itime plots, keyword time')
parser.add_argument('-path', help='Path where files to be plotted are', required=True)
args = parser.parse_args()
print ("The path you want to use... | StarcoderdataPython |
3332348 | <reponame>dylanlee101/leetcode
'''
根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/dai... | StarcoderdataPython |
3228307 | <filename>main.py
# Copyright Amazon.com, Inc. or its affiliates. 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
#
# Unles... | StarcoderdataPython |
1973115 | <reponame>adamwojt/ur_l<gh_stars>1-10
import pytest
from django.core.cache import cache
from ..apps import ApiConfig
from ..models import CollisionLog, Url
class TestURLWithoutDB:
def test_get_random_url_token(self):
""" Test _get_random_url_token"""
token = Url.objects._get_random_url_token()
... | StarcoderdataPython |
9668980 | from django.contrib import admin
from .models import *
class FileInline(admin.StackedInline):
model = File
extra = 3
class PostAdmin(admin.ModelAdmin):
inlines = [FileInline]
admin.site.register(Post, PostAdmin)
admin.site.register(File) # 一応、ファイル単体の管理画面も作っておく
| StarcoderdataPython |
8054560 | """
Shared utilities for the patch drawings.
"""
import numpy as np
def rotmat(rot):
d = 2 * np.pi / 360.0 # assume input in degree
return np.array([[np.cos(d * rot), -np.sin(d * rot)], [np.sin(d * rot), np.cos(d * rot)]])
| StarcoderdataPython |
6467790 | <filename>src/scene_layouts/evaluator.py<gh_stars>1-10
import numpy as np
import torch
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from scene_layouts.datasets import SCENE_HEIGHT_TEST, SCENE_WIDTH_TEST
class Evaluator:
def __init__(self, total_elements):
self.total_element... | StarcoderdataPython |
261465 | <reponame>nathanielsimard/improving-fs-ssl
from copy import deepcopy
from time import time as time
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
from mcp.data.dataset.transforms import KorniaTransforms, TransformType
from mcp.model.base import freeze_weight... | StarcoderdataPython |
3378954 | <reponame>riccardobernardi/MLL-machine-learning-language
new_revision = """
//////////////PARSER RULES
// | macro_exp | macro_mod | macro_pip
mll : ( model | macro | parmac | comment | summa )+
model : ID COLON [_rc] [PI] e (_nn)*
_rc.2 : RR | CC
_nn : ( PI e )
pyt : "!" (W | NUM | "," | " " | ":" | "+" | "=" |... | StarcoderdataPython |
6406129 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#
# 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 wit... | StarcoderdataPython |
3279345 | <reponame>elexis-eu/word-game
import mysql.connector
import csv
from decimal import *
import os
import time
from config import DBconfig, CronRoot
if CronRoot.path is not None:
os.chdir(CronRoot.path)
mydb = mysql.connector.connect(
host=DBconfig.host,
port=DBconfig.port,
user=DBconfig.user,
passw... | StarcoderdataPython |
3390887 | <reponame>dmccloskey/listDict
# system
from copy import copy
# Calculate utilities
from .listDict_dependencies import *
# Resources
from io_utilities.base_importData import base_importData
from io_utilities.base_exportData import base_exportData
class listDict():
'''Utility functions for converting and extracting a... | StarcoderdataPython |
4998153 | # Generated by Django 3.1.3 on 2020-11-28 23:26
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('registry', '0016_auto_20200115_1212'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
11322873 | import time
import memcache_manager
from connection import Connection, ConnectionError
from connection_manager import ConnectionManager, NotConnectedError, SessionAttrError
class MemcacheConnectionManager(ConnectionManager, memcache_manager.MemcacheManager):
"""Manages connections stored by Memcache."""
CONN... | StarcoderdataPython |
6688537 | <filename>src/z3c/password/tests.py
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should acc... | StarcoderdataPython |
5051336 | <gh_stars>1-10
from molly.molly import Molly
import pytest
@pytest.fixture(scope='function')
def _molly():
molly = Molly(
target='scanme.nmap.org',
mode='common',
workers=4
)
yield molly
| StarcoderdataPython |
1720460 | import numpy as np
import scipy.linalg as sl
import jax.numpy as np
from jax import grad, jit, vmap, jacfwd, jacrev
from jax import random
def log_likelihood(x, mu, Sigma):
x = np.atleast_2d(x)
mu = np.atleast_2d(mu)
Sigma = np.atleast_2d(Sigma)
sign, Slogdet = sl.slogdet(Sigma)
Sinv = sl.inv(Sigma)
return... | StarcoderdataPython |
4878969 | <reponame>KnowEnG-Research/Gene_Prioritization_Pipeline
"""
Created on Fri Sep 23 16:39:35 2016
@author: The KnowEnG dev team
"""
def correlation(run_parameters):
""" gene prioritization """
from gene_prioritization_toolbox import run_correlation
run_correlation(run_parameters)
def net_correlation(run_par... | StarcoderdataPython |
5146744 | <gh_stars>1-10
from functools import reduce
from django.db.models import Q
from django.shortcuts import reverse, get_object_or_404
from django.views.generic.list import ListView
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from django.contrib.auth import get_user_mod... | StarcoderdataPython |
9742415 | #coding:utf-8
#author:<EMAIL>
import re
import urllib2
def check(host,port,timeout):
try:
url = "http://%s:%d"%(host,int(port))
res = urllib2.urlopen(url+'/axis2/services/listServices',timeout=timeout)
res_code = res.code
res_html = res.read()
if int(res_code) == 404:
... | StarcoderdataPython |
3432427 | <reponame>socrateslee/hostsed
'''
Utilities for adding or deleting entries on hosts file
as /etc/hosts.
'''
import os
import sys
import json
import subprocess
import socket
import argparse
def is_valid_ip_address(ip):
'''
Check whether an ip address is valid, both for ipv4
and ipv6.
'''
try:
... | StarcoderdataPython |
1838219 | <reponame>GambitResearch/capnpy
# -*- encoding: utf-8 -*-
import pytest
import six
from capnpy.compiler.util import as_identifier
def test_as_identifier():
assert as_identifier(b'hello') == 'hello'
t = type(as_identifier(b'hello'))
assert t is str # bytes on Py2, unicode on Py3
with pytest.raises(Type... | StarcoderdataPython |
3224439 | <reponame>Rimuwu/Ranga<filename>Cog/moderation.py<gh_stars>1-10
import nextcord as discord
from nextcord.ext import tasks, commands
from nextcord.utils import utcnow
from datetime import timedelta
import sys
import random
from random import choice
import asyncio
import time
import datetime
import pymongo
sys.path.appe... | StarcoderdataPython |
3497247 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import configparser
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formatdate
import json
import urllib3
from app import redis_store, logger
import logging
from OpenSSL import crypto... | StarcoderdataPython |
12843502 | <gh_stars>0
# https://docs.microsoft.com/en-us/windows/python/beginners
# https://developers.google.com/identity/protocols/oauth2/service-account#python
from __future__ import print_function
from pathlib import Path
from googleapiclient.discovery import build
from google.oauth2 import service_account
SCOPES = ['ht... | StarcoderdataPython |
3366661 | <filename>app/models.py
from app import create_app,db
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class Us... | StarcoderdataPython |
19204 | import torch
import hcat.lib.functional
from hcat.lib.functional import IntensityCellReject
from hcat.backends.backend import Backend
from hcat.models.r_unet import embed_model as RUnet
from hcat.train.transforms import median_filter, erosion
import hcat.lib.utils
from hcat.lib.utils import graceful_exit
import os.pat... | StarcoderdataPython |
3587244 | <reponame>marcosolvr/Uri-Problem-Solutions<filename>Python/1003 - Soma Simples.py
a = int(input())
b = int(input())
operation = a + b
print('SOMA = %i' %operation) | StarcoderdataPython |
1882677 | <filename>tests/test_models.py
from typing import OrderedDict
import pytest
from pygitguardian.models import (
Document,
DocumentSchema,
HealthCheckResponseSchema,
Match,
MatchSchema,
MultiScanResult,
MultiScanResultSchema,
PolicyBreak,
PolicyBreakSchema,
Quota,
QuotaRespon... | StarcoderdataPython |
4927765 | <reponame>abhinavkbij/machine_flow
# *************** MODEL BUILDING FUNCTIONS *******************
# add libraries
import json
from Python_Scripts.utility_functions import *
from sklearn import linear_model
def run_linear_regression(read_path, write_path):
X_train, X_test, Y_train, Y_test = read_split_sets(read_pat... | StarcoderdataPython |
11219922 | # coding: utf-8
import random
import time
import json
import requests
from db import REDIS
import pymysql
REPO_SHOW = '1'
REPO_HIDDEN = '0'
SEARCH_API = 'https://api.github.com/search/repositories?q=%s&sort=updated&order=desc&page=%s'
def LoadUserAgents(uafile):
uas = []
with open(uafile, 'rb') as uaf:
... | StarcoderdataPython |
8031597 | # -*- coding:utf-8 -*-
# author : gfjiangly
# time : 2019/5/17 10:17
# e-mail : <EMAIL>
# software : PyCharm
import os
import json
from tqdm import tqdm
import numpy as np
import cv2
from cvtools.utils.file import get_files_list
class BDD2COCO:
def __init__(self, bdd_root, phase, save_name='custom', path... | StarcoderdataPython |
357438 | from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class BackupStorage(S3BotoStorage):
access_key = getattr(settings, 'BACKUP_BUCKET_AWS_ACCESS_KEY_ID')
secret_key = getattr(settings, 'BACKUP_BUCKET_AWS_SECRET_ACCESS_KEY')
bucket_name = getattr(settings, 'BACKUP_BUCKET_BUC... | StarcoderdataPython |
11302717 | <reponame>cyberworm/ircbot
import socket
import unittest
from mock import Mock
from ircbot.ircsocket import IrcSocket
from ircbot.exceptions import TimeoutError
class TestIrcSocket(unittest.TestCase):
def setUp(self):
self.__socketMock = Mock(socket.socket())
self.__ircSocket = IrcSocket(self.__so... | StarcoderdataPython |
318605 | <reponame>isudox/leetcode-solution
"""1007. Minimum Domino Rotations For Equal Row
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/
"""
from typing import List
class Solution:
def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
def rotate(l1: List[int], x: int, i... | StarcoderdataPython |
164543 | <gh_stars>100-1000
# Copyright 2017 Google 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 |
11364219 | <filename>admin_panel/api/serializers.py
from rest_framework import serializers
from admin_panel.models import Category, Highlights
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ['title', 'img']
class HighlightsSerializer(serializers.ModelSerialize... | StarcoderdataPython |
3320693 | from mindpile.Mapping.types import OutPort
from mindpile.Mapping.utils import MethodCall, Requires, Setup
@Setup
def largeMotorSetup():
return '''
from ev3dev2.motor import LargeMotor
'''
@MethodCall(target="MotorStop.vix", MotorPort=OutPort, BrakeAtEnd=bool)
@Requires(largeMotorSetup)
def largeMotorS... | StarcoderdataPython |
3444413 | <gh_stars>1-10
# didn't use debayan's code as base so i reimplemented the example triangle for reference
def triangle_example(total_lines):
for current_line in range(total_lines):
for space in range(0, current_line, 1):
print(" ", end="")
for number in range(total_lines - current_line... | StarcoderdataPython |
3329314 | # -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TaxReportTest(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_tem... | StarcoderdataPython |
9742101 | <reponame>danielSbastos/understanding-tests
from unittest import TestCase
from understanding_tests.user import User
class UserTestCase(TestCase):
def test_user_sets_email_and_username(self):
user = User('Daniel', 'Bastos', '18')
self.assertEqual(user.email(), '<EMAIL>')
self.assertEqual(... | StarcoderdataPython |
8017399 | """Bite 130. Analyze some basic Car Data."""
from collections import Counter
from typing import Set
import requests
CAR_DATA = "https://bites-data.s3.us-east-2.amazonaws.com/cars.json"
# pre-work: load JSON data into program
with requests.Session() as session:
data = session.get(CAR_DATA).json()
# TODO: writ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.