id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3378208 | from meteor_reasoner.graphutil.temporal_dependency_graph import *
from meteor_reasoner.graphutil.topological_sort import *
class Graph:
def __init__(self, program):
self.program = program
self.head2rule = defaultdict(list)
self.initialize()
def initialize(self):
self.build_hea... | StarcoderdataPython |
165352 | EMBED_SIZE = 200
NUM_LAYERS = 2
LR = 0.0001
MAX_GRAD_NORM = 5.0
PAD_ID = 0
UNK_ID = 1
START_ID = 2
EOS_ID = 3
CONV_SIZE = 3
# sanity
# BUCKETS = [(55, 50)]
# BATCH_SIZE = 10
# NUM_EPOCHS = 50
# NUM_SAMPLES = 498
# HIDDEN_SIZE = 400
# test
BUCKETS = [(30, 30), (55, 50)]
BATCH_SIZE = 20
NUM_EPOCHS = 3
NUM_SAMPLES = ... | StarcoderdataPython |
1738899 | import unittest
from myhdl_lib import *
from t_hsd_custom import t_hsd_custom
class Test_hsd_custom(t_hsd_custom):
'''|
| The main class for unit-testing. Add your tests here.
|________'''
def __init__(self):
# call base class constructor
t_hsd_custom.__init__(self)
# Automatical... | StarcoderdataPython |
3333309 | <reponame>aglines/gympopulation
import unittest
from secrets import *
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import... | StarcoderdataPython |
4801549 | <filename>Scripts/simulation/reputation/reputation_tuning.py
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\reputation\reputation_tuning.py
# Compi... | StarcoderdataPython |
1635848 | <filename>src/reparsec/core/sequence.py<gh_stars>1-10
from typing import Callable, Optional, Sequence, Sized, TypeVar
from .parser import ParseFn
from .repair import make_insert, make_pending_skip, make_skip
from .result import Error, Ok, Recovered, Result
from .types import Ctx, RecoveryMode
T = TypeVar("T")
def e... | StarcoderdataPython |
3399454 | <reponame>elfgzp/leetCode<gh_stars>1-10
#
# @lc app=leetcode.cn id=485 lang=python3
#
# [485] 最大连续1的个数
#
# https://leetcode-cn.com/problems/max-consecutive-ones/description/
#
# algorithms
# Easy (51.75%)
# Total Accepted: 8.7K
# Total Submissions: 16.7K
# Testcase Example: '[1,0,1,1,0,1]'
#
# 给定一个二进制数组, 计算其中最大连续1的... | StarcoderdataPython |
187028 | <reponame>rundhall/ESP-LEGO-SPIKE-Simulator
from spike import ForceSensor, Motor
# Initialize the Force Sensor, a motor, and a variable
force_sensor = ForceSensor('B')
motor = Motor('C')
count = 0
# You can press the Force Sensor 5 times
motor.set_default_speed(25)
while count < 5:
force_sensor.wait_until_pressed()
... | StarcoderdataPython |
26682 | <reponame>zzztimbo/dagster
import sys
from dagster_graphql.schema.pipelines import DauphinPipeline, DauphinPipelineSnapshot
from graphql.execution.base import ResolveInfo
from dagster import check
from dagster.core.definitions.pipeline import ExecutionSelector
from dagster.core.errors import DagsterInvalidDefinitionE... | StarcoderdataPython |
1704284 | import os
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
import copy
import logging
import pandas as pd
import multiprocessing as mp
from ..orbit import TestOrbit
from ... | StarcoderdataPython |
3222173 | from denodoclient.dataframes.denododataframeclient import DenodoDataFrameClient
DenodoDataFrameClient = DenodoDataFrameClient
| StarcoderdataPython |
3235788 | import numpy as np
import cmath
from math import sqrt
def pau_x():
p_x=np.array([[0,1],[1,0]])
return p_x
def pau_y():
p_y=np.array([[0,-(cmath.sqrt(-1))],[(cmath.sqrt(-1)),0]])
return p_y
def pau_z():
p_z=np.array([[1,0],[0,-1]])
return p_z
def hada():
h=(1/sqrt(2))*(np.array(... | StarcoderdataPython |
1610252 | # This file defines how PyOxidizer application building and packaging is
# performed. See PyOxidizer's documentation at
# https://pyoxidizer.readthedocs.io/en/stable/ for details of this
# configuration file format.
def make_exe():
# Obtain the default PythonDistribution for our build target. We link
# this di... | StarcoderdataPython |
87950 | <reponame>Sirruthf/stuff<gh_stars>0
from django.shortcuts import render, redirect
from django.http import HttpRequest, HttpResponse
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import Passwo... | StarcoderdataPython |
3391571 | <reponame>conao3/coder
a, op, b = input().split()
a, b = int(a), int(b)
if op == '+':
print(a + b)
elif op == '-':
print(a - b)
| StarcoderdataPython |
72008 | #!/usr/bin/python3
from hub import HubBot
import traceback
import itertools
import sys
import os
import select
import threading
import subprocess
import tempfile
import logging
import calendar
import abc
import smtplib
import sleekxmpp.exceptions
from datetime import datetime, timedelta
import email.message
import em... | StarcoderdataPython |
3294041 |
def has_automation(filename):
"""Decorator that adds the automation_file attribute to a test function.
When present, this filename will be used as the --automation file when creating the speculos fixture.
"""
def decorator(func):
func.automation_file = filename
return func
return d... | StarcoderdataPython |
67548 | from lithopscloud.modules.config_builder import ConfigBuilder, update_decorator, spinner
from typing import Any, Dict
from lithopscloud.modules.utils import find_obj, find_default
class ImageConfig(ConfigBuilder):
def __init__(self, base_config: Dict[str, Any]) -> None:
super().__init__(base_config)
... | StarcoderdataPython |
82514 | import json
import pytest
from stix2 import TAXIICollectionSource
from test_data.mitre_test_data import ATTACK_PATTERN, COURSE_OF_ACTION, INTRUSION_SET, MALWARE, TOOL, ID_TO_NAME, \
RELATION, STIX_TOOL, STIX_MALWARE, STIX_ATTACK_PATTERN
class MockCollection:
def __init__(self, id_, title):
self.id = i... | StarcoderdataPython |
3344227 | import numpy as np
import functools
import traittypes
import traitlets
from itertools import tee
import pythreejs
from plyfile import PlyData, PlyElement
from .traits_support import check_shape, check_dtype
cached_property = getattr(functools, "cached_property", property)
# From itertools cookbook
def pairwise(iter... | StarcoderdataPython |
4825620 | <filename>Other Trials/sentiment_input.py<gh_stars>0
from nltk.classify import NaiveBayesClassifier
#from nltk.corpus import posectivity
from nltk.sentiment import SentimentAnalyzer
from nltk.sentiment.util import *
import os
from textblob import TextBlob
##
##neg_docs = []
##with open("C:/Users/ShravanJagadish/Desktop... | StarcoderdataPython |
1701425 | <reponame>kadamkaustubh/Countdown<filename>WordGame.py
import random
def sorted_word_list(file_name):
with open(file_name, 'r') as fileopen:
words = [line.strip() for line in fileopen]
sorted_list = sorted(words, key=len)
rev_list = reversed(sorted_list)
with open('words/SortedWords', 'w') as ... | StarcoderdataPython |
12762 | <filename>src/config.py<gh_stars>10-100
import yaml
import os
def parse_config(args):
"""
prepare configs
"""
file_dir = os.path.dirname(os.path.realpath('__file__'))
messytable_dir = os.path.realpath(os.path.join(file_dir, '..'))
config_pathname = os.path.join(messytable_dir,'models',args.conf... | StarcoderdataPython |
1636299 | <filename>gradschool/fs/utility.py
import os
import pathlib
def as_uri(path):
"""
Converts the supplied path to file URI
:param path: Path to be converted
:return: Path as a fille URI
"""
p = pathlib.Path(path)
return p.as_uri()
def as_pathlib(path):
"""
Converts the supplied pat... | StarcoderdataPython |
3283360 | # Copyright (C) 2021 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import os
import ctypes
from collections import namedtuple
from pcieparser.header import header
from pcieparser.caps import capabilities
from pcieparser.extcaps import extended_capabilities
class PCIConfigSpace(n... | StarcoderdataPython |
1665353 |
"""
Based on this example -> https://github.com/open-power/pdbg/blob/master/.build.sh
TEMPDIR=`mktemp -d ${HOME}/pdbgobjXXXXXX`
RUN_TMP="docker run --rm=true --user=${USER} -w ${TEMPDIR} -v ${HOME}:${HOME} -t ${CONTAINER}"
${RUN_TMP} ${SRCDIR}/configure --host=arm-linux-gnueabi
${RUN_TMP} make
rm -rf ${TEMPDIR}
"... | StarcoderdataPython |
1761069 | <filename>part-data/test-sqlite.py
import sqlite3
if __name__ == "__main__":
data = [
(1, 2, 3),
(2, 3, 4),
]
s = sqlite3.connect('database.db')
# 给数据库建立游标,就可以执行sql查询语句了
db = s.cursor()
db.execute('create table wulj (name, number, rate)')
print(db)
s.commit()
db.exe... | StarcoderdataPython |
15664 | import pandas as pd
import re
import os
from tqdm import tqdm
## Cleaning train raw dataset
train = open('./data/raw/train.crash').readlines()
train_ids = []
train_texts = []
train_labels = []
for id, line in tqdm(enumerate(train)):
line = line.strip()
if line.startswith("train_"):
train_ids.append... | StarcoderdataPython |
132932 | <reponame>bozhikovstanislav/Python-Fundamentals
string_to_revers = input()
for x in string_to_revers[::-1]:
print(x, end='')
| StarcoderdataPython |
26336 | # -*- coding: utf-8 -*-
"""Example 1: Load and plot airfoil coordinates
"""
import os
import matplotlib.pyplot as plt
from mypack.utils.io import read_selig
from mypack.utils.plotting import plot_airfoil
def example_1():
"""Run example 1"""
# script inputs
mod_path = os.path.dirname(os.path.abspath(__fi... | StarcoderdataPython |
29374 | from flask_wtf import FlaskForm
from wtforms import PasswordField, SubmitField, StringField
from wtforms.validators import DataRequired, Length
class InstagramLoginForm(FlaskForm):
username = StringField('Instagram Username', validators=[DataRequired(),
... | StarcoderdataPython |
1622475 | # https://www.hackerrank.com/challenges/30-testing/problem
def minimum_index(seq):
if len(seq) == 0:
raise ValueError("Cannot get the minimum value index from an empty sequence")
min_idx = 0
for i in range(1, len(seq)):
if seq[i] < seq[min_idx]:
min_idx = i
return min_idx
... | StarcoderdataPython |
3243125 | <reponame>patryk-tech/Friendo_Bot
import os
TOKEN = os.environ.get("FRIENDO_TOKEN")
MEME_USERNAME = os.environ.get("MEME_USERNAME")
MEME_PASSWORD = os.environ.get("MEME_PASSWORD")
COMMAND_PREFIX = "."
VERSION = "1.2.8"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_GITHUB_REPO = "https://github.com/f... | StarcoderdataPython |
1722197 | <filename>app/categories/controller.py
from flask import abort
from sqlalchemy import asc
from .models import Category
from app.recipes.models import Recipe
from app.user.models import User
# Returns all categories
def categoryList():
return Category.getCategories()
# Returns 1 category
def currentCategory(cate... | StarcoderdataPython |
3316809 | <reponame>christabor/plantstuff<gh_stars>1-10
"""OCR conversion for generating data from images."""
from pprint import pprint as ppr
try:
import Image
except ImportError:
from PIL import Image
import pytesseract
from plantstuff.scraper_utils.decorators import cached
# E.g. `which tesseract`
pytesseract.pytes... | StarcoderdataPython |
142327 | # -*- coding: utf-8 -*-
import click
import logging
from pathlib import Path
import os,glob
# from dotenv import find_dotenv, load_dotenv
import process_rna as process_rna
import process_hichip as process_hichip
import process_atac as process_atac
import process_bedtools as process_bedtools
import process_crms as proce... | StarcoderdataPython |
1601632 | <reponame>devesh-todarwal/web-dev
import os
import requests
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup as soup
from difflib import SequenceMatcher
import numpy as np
def search_from(lst,name,max_results=10):
n = min(max_results,len(lst))
sim = [get_similarity(name,l) for l in lst]
lst... | StarcoderdataPython |
3220742 | <reponame>Sagarikanaik96/Test2<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright (c) 2020, veena and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Quotation(Document):
pass
def auto_create_supplier_q... | StarcoderdataPython |
3237808 | <reponame>bopopescu/pythonlib<gh_stars>0
#!/usr/bin/env python
# cardinal_pythonlib/sqlalchemy/merge_db.py
"""
===============================================================================
Original code copyright (C) 2009-2020 <NAME> (<EMAIL>).
This file is part of cardinal_pythonlib.
Licensed under t... | StarcoderdataPython |
1785096 | <reponame>kdar/rust-python-static-example<filename>src/main.py
import sysconfig
print(sysconfig.get_config_var('LDVERSION')
or sysconfig.get_config_var('py_version_short'))
| StarcoderdataPython |
1778233 | # -*- coding: utf-8 -*-
#
# Dell EMC OpenManage Ansible Modules
# Version 4.0.0
# Copyright (C) 2021 Dell Inc. or its subsidiaries. All Rights Reserved.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
from __future__ import (absolute_import, division, print_function)
_... | StarcoderdataPython |
1678133 | <reponame>CrankySupertoon01/Toontown-2<filename>dev/tools/leveleditor/direct/showbase/ShowBaseGlobal.py
"""instantiate global ShowBase object"""
__all__ = []
from ShowBase import *
# Create the showbase instance
# This should be created by the game specific "start" file
#ShowBase()
# Instead of creating a show base,... | StarcoderdataPython |
1742954 | <gh_stars>1-10
import os
import time
import numpy as np
import tensorflow as tf
from .li import LatentVariable
from .gaminet import GAMINet
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.cluster import KMeans
from copy import deepcopy
import networkx as nx
import matplotlib.pyplot as plt
from .uti... | StarcoderdataPython |
1609812 | """
MyToolBox is a collection of reusable tools.
Author: <EMAIL>
Copyright (C) CERN 2013-2021
"""
import sys
AUTHOR = "<NAME> <<EMAIL>>"
COPYRIGHT = "Copyright (C) CERN 2013-2021"
VERSION = "0.1.0"
DATE = "01 Mar 2013"
__author__ = AUTHOR
__version__ = VERSION
__date__ = DATE
PY2 = sys.hexversion < 0x03000000
PY3... | StarcoderdataPython |
4814759 | <gh_stars>1-10
class Chef:
def make_chicken(self):
print("The chef makes chicken")
def make_salad(self):
print("The chef makes salad")
def make_special_dish(self):
print("The chef makes make special dish")
class ChineseChef():
def make_chicken(self):
print("T... | StarcoderdataPython |
1680165 | # -*- coding: utf-8 -*-
"""
celery.worker.state
~~~~~~~~~~~~~~~~~~~
Internal worker state (global)
This includes the currently active and reserved tasks,
statistics, and revoked tasks.
:copyright: (c) 2009 - 2012 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
from __future__... | StarcoderdataPython |
3245452 | from aqt import *
def getQIcon(name):
"Convenience method for getting a QIcon from this add-on's icon directory."
here = os.path.dirname(os.path.realpath(__file__))
iPath = os.path.join(here, "icons", name)
return QIcon(iPath) | StarcoderdataPython |
3233636 | #Twin protocol definitions
#<NAME>
#27-Sep-2021
#//state of Twin, {"state"={}}
TWINSTATE = "state"
##delta of Twin change, {"delta"={}}
TWINDELTA = "delta"
###
###Message structure - MSG
###
#//TOPIC, {"topic"="....", "data"="..."}
TWINTOPIC = "topic"
#//DATA, {"topic"="....", "data"="..."}
TWINDATA = "data"
##... | StarcoderdataPython |
3337326 | """The fitting module contains the code for fitting the experimental data."""
from __future__ import annotations
from pathlib import Path
from rich.progress import track
from chemex.configuration.methods import Methods
from chemex.configuration.methods import Statistics
from chemex.containers.experiments import Expe... | StarcoderdataPython |
1660498 | from django.db import models
# Create your models here.
class Task(models.Model):
title = models.CharField(max_length = 200)
complete = models.BooleanField(default = False)
created = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.title
| StarcoderdataPython |
51569 | <filename>src/conformal_methods/utils.py
import numpy as np
import pandas as pd
from src.config import SRC
from numba import jit
from scipy.stats import norm
from scipy.stats import skewnorm
from sklearn.preprocessing import StandardScaler
def init_scoring_object(method, quantile=0.9):
def scoring_object(estim... | StarcoderdataPython |
3263602 | class Calculator:
"""
A calculator that support polish notation.
"""
def __init__(self):
pass
| StarcoderdataPython |
1766283 | from src.main.managers.items.item_manager import ItemManager
class HardCodedAliceItemManager(ItemManager):
def __init__(self, items):
ItemManager.__init__(self, items)
self.first_run = True
def get_spook_rate_and_power(self):
power = 0
if self._HAT_BAG:
hat = self.... | StarcoderdataPython |
8420 | """Define the aiolookin package."""
from .device import async_get_device # noqa
| StarcoderdataPython |
1653895 | from foreman import get_relpath, rule
from garage import scripts
from templates import common
common.define_git_repo(
repo='https://github.com/capnproto/capnproto.git',
treeish='v0.6.1',
)
common.define_distro_packages([
'autoconf',
'automake',
'g++',
'libtool',
'pkg-config',
])
@rul... | StarcoderdataPython |
121412 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/20 13:34
# @Author : Tao.Xu
# @Email : <EMAIL>
"""
Some own/observed great lib/ideas,common useful python libs.
"""
import sys
from tlib import version
if sys.version_info < (2, 6):
raise ImportError('tlib needs to be run on python 2.6 and ab... | StarcoderdataPython |
3393849 | <reponame>jorisfa/gcpdiag
# Copyright 2022 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... | StarcoderdataPython |
1763215 | """Configurations and utilities for model building and training."""
import json
import yaml
import torch
import wandb
import argparse
import numpy as np
from pathlib import Path
from pydantic import BaseSettings as _BaseSettings
from typing import TypeVar, Type, Union, Optional, Dict, Any
PathLike = Union[str, Path]
_... | StarcoderdataPython |
4829599 | # Copyright 2020 The DDSP 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | StarcoderdataPython |
97423 | """
Name : __init__.py
boxes module
This import path is important to allow importing correctly as package
"""
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '.')))
| StarcoderdataPython |
3268310 | from django.core.management.base import BaseCommand
from django.utils.six.moves import input
from instagram.client import InstagramAPI
from mezzanine.conf import settings
def get_auth_tokens(stdout):
stdout.write('Please enter the following Instagram client details\n\n')
print('lol' + settings.INSTAGRAM_CLIENT... | StarcoderdataPython |
168209 | from .default import _C as cfg
from .default import update_config | StarcoderdataPython |
30323 | <reponame>shootsoft/practice
class Solution:
# @param {integer} k
# @param {integer} n
# @return {integer[][]}
def combinationSum3(self, k, n):
nums = range(1, 10)
self.results = []
self.combination(nums, n, k, 0, [])
return self.results
def combination(self, nums, ... | StarcoderdataPython |
1793020 | <reponame>arccode/factory<gh_stars>1-10
# Copyright 2016 The Chromium OS 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 factory test to check if the components can be probed successfully or not.
Description
-----------
Uses prob... | StarcoderdataPython |
1799355 | from django.conf.urls import url
from .views import *
app_name = 'forum'
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^(?P<page_number>[0-9]+)$', index, name='index'),
url(r'^topic/(?P<pk>[0-9]+)/(?P<page_number>[0-9]+)', topic, name='topic'),
url(r'^login/', log_in, name='log_in'),
url(... | StarcoderdataPython |
1798371 | #!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of t... | StarcoderdataPython |
1698377 | <reponame>stepanandr/taf
# Copyright (c) 2011 - 2017, 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 ... | StarcoderdataPython |
74996 | <reponame>sgondala/Automix<filename>yahoo_with_mixtext/hyperopt_eval_single.py<gh_stars>1-10
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import numpy as np
from FastAutoAugment.read_data import *
from FastAutoAugment.classification_models.MixText import *
import pickle
import ... | StarcoderdataPython |
96770 | <filename>brainreg/backend/niftyreg/utils.py
import imio
import numpy as np
def save_nii(stack, atlas_pixel_sizes, dest_path):
"""
Save self.target_brain to dest_path as a nifti image.
The scale (zooms of the output nifti image) is copied from the atlas
brain.
:param str dest_path: Where to save ... | StarcoderdataPython |
182611 | import torch
import torch.nn as nn
import math
# wildcard import for legacy reasons
if __name__ == '__main__':
import sys
sys.path.append("..")
from models.blocks import *
from models.wide_resnet import compression, group_lowrank
# only used in the first convolution, which we do not substitute by convention
... | StarcoderdataPython |
1648939 | from learner import Learner
from imgur import Imgur
from meme import Memer
import logging
doom_img_key = "__doomimg__"
doom_quote_key = "__doomquote__"
class Doom():
def memify(self, image, content):
memer = Memer()
parts = [x.strip() for x in content.encode('utf-8').split(",")]
top = p... | StarcoderdataPython |
1615563 | <reponame>mmaysami/azure-functions-python<gh_stars>0
import logging
import json
import time
import azure.functions as func
from . import toolsA_F1 as tools
def main(req: func.HttpRequest) -> func.HttpResponse:
start = time.time()
logging.info('Python HTTP trigger function processed a request.')
try:
... | StarcoderdataPython |
3324095 | <gh_stars>0
from .base_token_test import TestToken
from ..entity_objects.authentication_object import AuthenticationObject
class TestAuthentication(TestToken):
"""
Implements the authentication test routines
"""
_entity_object_class = AuthenticationObject
""" An object for a testing entity """
... | StarcoderdataPython |
1712567 | <reponame>dextar1/image-classifier<filename>test.py
from PIL import Image, ImageFilter
def imageprepare(argv):
"""
This function returns the pixel values.
The imput is a png file location.
"""
im = Image.open(argv).convert('L')
width = float(im.size[0])
height = float(im.size[1])
newIm... | StarcoderdataPython |
3253249 | <filename>bin/smartstreamingcommand.py<gh_stars>0
#!/usr/bin/env python
from splunklib.searchcommands import StreamingCommand
import sys
import select
import os
import gzip
import re
import csv
import math
import time
import logging
try:
from collections import OrderedDict # must be python 2.7
except ImportError... | StarcoderdataPython |
3291800 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-06-14 10:22:21
# @Author : <NAME>
# @Version : 1.0
import pprint
def functionTest():
pass
class ClassTest(object):
"""docstring for ClassTest"""
def __init__(self,):
super(ClassTest, self).__init__()
def selfMethodTest(self)... | StarcoderdataPython |
3311483 | # coding: utf-8
import datetime
import unittest
from mock import Mock, patch
import pyslack
class ClientTest(unittest.TestCase):
token = "my token"
@patch('requests.post')
def test_post_message(self, r_post):
"""A message can be posted to a channel"""
client = pyslack.SlackClient(self.... | StarcoderdataPython |
1695412 | <filename>src/cloudservice/azext_cloudservice/manual/custom.py
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by M... | StarcoderdataPython |
78221 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
import math
def A(m ,n):
ret = math.factorial(n) / math.factorial(n-m)
return ret
def C(m, n):
ret = A(m, n) / math.factorial(m)
return ret
def cell(i, n, count):
ret = (-1 ** i) * C(i, count) * ((1 - float(i) / count) ** n)
print ret
return ... | StarcoderdataPython |
1604996 | #!/usr/bin/env python
from __future__ import print_function
from LifeCycleTests.LifeCycleTools.PayloadHandler import PayloadHandler
from LifeCycleTests.LifeCycleTools.OptParser import get_command_line_options
import random, os, sys
def change_cksums(block_dict, file_dict):
file_dict['check_sum'] = str(random.rand... | StarcoderdataPython |
3308276 | <filename>Model/login_screen.py
# The model implements the observer pattern. This means that the class must
# support adding, removing, and alerting observers. In this case, the model is
# completely independent of controllers and views. It is important that all
# registered observers implement a specific method that w... | StarcoderdataPython |
3384837 | from django.conf.urls import url
from article.views.oj import ArticleAPI
urlpatterns = [
# 文章
url(r"^article/?$", ArticleAPI.as_view(), name="articel_view_api"),
]
| StarcoderdataPython |
3384713 | import pymongo
import mysql
'''
This module performs the subscriber information processing
1. Gets the existing subscriber list from MongoDB
2. Gets the live subscriber list from the MySQL DB
3. Compares the two lists and returns ONLY anything that has changed
4. Updates any changes to the live subscriber list colle... | StarcoderdataPython |
4803181 | from dataclasses import dataclass
from piate.api.resources.collections import Collections
from piate.api.resources.domains import Domains
from piate.api.resources.entries import Entries
from piate.api.resources.institutions import Institutions
from piate.api.resources.inventories import Inventories
from piate.api.sess... | StarcoderdataPython |
3249346 | <reponame>nthacker/learnAnalytics-DeepLearning-Azure<gh_stars>10-100
# Hyperparams LSTM
EPOCHS=3
BATCHSIZE=64
EMBEDSIZE=125
NUMHIDDEN=100
DROPOUT=0.2
LR=0.001
BETA_1=0.9
BETA_2=0.999
EPS=1e-08
MAXLEN=150
MAXFEATURES=20000
GPU=True | StarcoderdataPython |
61424 | <reponame>jol79/LiveChat
from django.urls import path
from . import views
urlpatterns = [
path('', views.chat, name='chat'),
path('login', views.login, name='login'),
path('users', views.users, name='users_list'),
path('users/edit/<id>', views.edit_user, name='edit_user')
]
| StarcoderdataPython |
36655 | <filename>authors/apps/profiles/migrations/0022_auto_20190123_1211.py
# Generated by Django 2.1.4 on 2019-01-23 12:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0021_auto_20190122_1723'),
]
operations = [
migrations.Alt... | StarcoderdataPython |
15963 | <filename>handlers/_my.py
import model
sticker_storage = model.get_storage()
def my(_, update):
"""Prints stickers added by user"""
message = update.message
user_id = update.message.from_user.id
stickers = sticker_storage.get_for_owner(user_id, max_count=20, tagged=True)
text = '\n\n'.join(
... | StarcoderdataPython |
191929 | <reponame>visualsnoop/visualsnoop-client-python
__version__ = '0.2'
DEFAULT_ENDPOINT='http://visualsnoop.com/api/v1'
| StarcoderdataPython |
3303026 | <gh_stars>1000+
from ..base.twilltestcase import common, ShedTwillTestCase
column_repository_name = 'column_maker_0080'
column_repository_description = "Add column"
column_repository_long_description = "Compute an expression on every row"
convert_repository_name = 'convert_chars_0080'
convert_repository_description =... | StarcoderdataPython |
3325997 | <filename>rasa/nlu/featurizers/bert_featurizer.py<gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import logging
import typing
from typing import Any
from typing import List
from typing... | StarcoderdataPython |
1797435 | <reponame>quocodile/auto_correct
import csv
def calc_edit_dist(word1, word2):
'''
First, create a 2D array to enable dynamic programming.
Then, use dynamic programming to alculate
edit distance between two words.
'''
#this method needs fixing
comparison_matrix = create_comparision_matrix(word1, word2)
... | StarcoderdataPython |
1692916 | from django.conf import settings
from django.urls import URLResolver, URLPattern
from django.urls.base import resolve, reverse_lazy
__author__ = 'Ashraful'
URL_NAMES = []
def get_view_by_url(url_name=None):
"""
**view generator**
:param url_name: get url_name as string
:return: view function (Though... | StarcoderdataPython |
3265539 | from typing import Type, TypeVar
from ssz.hashable_container import HashableContainer
from .block_headers import SignedBeaconBlockHeader, default_signed_beacon_block_header
TProposerSlashing = TypeVar("TProposerSlashing", bound="ProposerSlashing")
class ProposerSlashing(HashableContainer):
fields = [
... | StarcoderdataPython |
1760207 | <filename>example/sample/models.py<gh_stars>1-10
from django.db import models
from lazydrf.models import LDRF
class Record(models.Model, metaclass=LDRF):
"""
Defines a key/value record model.
"""
#: Defines the key of the record.
key = models.CharField(max_length=16, unique=True, blank=False, nu... | StarcoderdataPython |
4916 | '''
Created on Mar 6, 2014
@author: tharanga
'''
import unittest
from time import sleep
import EventService as es
from EventService import WebSocketServer as ws
from EventService import EventManager as em
import socket
from base64 import b64encode
import struct
import MySQLdb
import json
import EventService
import fl... | StarcoderdataPython |
3206985 | import pytest
from .context import gatherers # noqa
from gatherers import rdns
@pytest.mark.parametrize("data,expected", [
(
[
'{"value": "18f.gov"}',
'{"value": "123.112.18f.gov"}',
'{"value": "172.16.17.32"}',
'{"value": "u-123.112.23.23"}',
'... | StarcoderdataPython |
3213654 | <filename>tests/test_templater.py
# coding: utf-8
from unittest import TestCase
import templater
import sys
class Silence:
def __init__(self):
self.__log = []
return
def __call__(self):
return self.__log
def write(self, x):
self.__log.append(x)
return
class TestFakeMustaches(TestCase):
d... | StarcoderdataPython |
3230696 | <reponame>SimonSchubotz/Electronic-Laboratory-Notebook<gh_stars>0
import json
import glob, os
import dash
import plotly.io as pio
import datetime
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
from django_plotly_dash import ... | StarcoderdataPython |
3351291 | <filename>lnt/server/reporting/summaryreport.py<gh_stars>10-100
import re
import lnt.testing
import lnt.util.stats
###
# Aggregation Function
class Aggregation(object):
def __init__(self):
self.is_initialized = False
def __repr__(self):
return repr(self.getvalue())
def getvalue(self):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.