id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3280828 | <gh_stars>1000+
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Kyoto University (<NAME>)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import codecs
import re
import regex
parser = argparse.ArgumentParser()
parser.add_argument("text", type=str, help="text file")
args =... | StarcoderdataPython |
3482755 | from rest_framework import generics
from rest_framework.generics import get_object_or_404
from .models import Course, Evaluate
from .serializers import CourseSerializer, EvaluateSerializer
# ListApiView - Get
# ListCreateApiView - Get / Post
class CourseApiView(generics.ListCreateAPIView):
queryset = Course.obje... | StarcoderdataPython |
5083656 | <gh_stars>0
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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/licens... | StarcoderdataPython |
61520 | """
Class to crawl answers mail.ru
"""
import sqlite3
import requests
import re
from bs4 import BeautifulSoup as bs
class Crawler(object):
def __init__(self, categories='all', timeline = 'all', verbose=True,
schema_name='schema.sql', db_name='q_database.sqlt',
bs_features='lxml'... | StarcoderdataPython |
9755943 | # Generated by Django 2.1.1 on 2019-07-16 00:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blackswan', '0008_auto_20190716_0044'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='first_name... | StarcoderdataPython |
1623332 | <filename>shift_detector/precalculations/binning_precalculation.py
import pandas as pd
from pandas import DataFrame
from shift_detector.precalculations.precalculation import Precalculation
from shift_detector.utils.column_management import ColumnType, is_categorical
class BinningPrecalculation(Precalculation):
... | StarcoderdataPython |
4838535 | <reponame>0x8b/HackerRank
#!/usr/bin/env python
import fileinput
import re
from collections import Counter, defaultdict
from operator import itemgetter
c = re.compile(r"(\w+)")
values = {}
children = defaultdict(list)
lines = [line for line in fileinput.input()]
head = Counter(re.compile(r"([a-z]+)").findall("\n".... | StarcoderdataPython |
5199441 | <reponame>cfpb/regulations-parser
# vim: set encoding=utf-8
from regparser.tree.appendix.tree import trees_from as appendix_trees
from regparser.tree.interpretation import build as build_interp_tree
from regparser.tree.reg_text import build_reg_text_tree
from regparser.tree.supplement import find_supplement_start
impor... | StarcoderdataPython |
3561412 | <filename>nara/parse_diff.txt.py<gh_stars>0
import os
from shutil import copyfile
with open("new_csv.txt") as f:
for l in f.readlines():
filename = os.path.join(
"/Users/matt.mcgrattan/Documents/Github/ida-treaty-explorer-data/nara/new_csvs",
l.replace("Only in new_csvs: ", "").stri... | StarcoderdataPython |
6629750 | <gh_stars>1000+
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as publi... | StarcoderdataPython |
6525315 | n = int(input('Input the length of the list: '))
numbers = [int(input(f'Input {i} index number: ')) for i in range(n)]
print("Our manual entered list %s " % numbers)
print("The sum of numbers %d" % sum(numbers))
total = 1
for i in numbers:
total *= i
print("The mult of numbers %d" % total)
| StarcoderdataPython |
6468085 | <gh_stars>0
from typing import Optional
from tortoise.contrib.pydantic import PydanticModel
from db.base.schemas import GetFile
from db.project.models import Project
class CreateProject(PydanticModel):
name: str
city: str
address: str
title: str
description: str
type: str
square: float
... | StarcoderdataPython |
3458012 | <gh_stars>1-10
"""
(c) ΔQ Programming LLP, 2021
This program is free software; you may redistribute and/or modify
it under the terms of the Apache License v2.0.
"""
import os
import pathlib
import requests
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
A management comman... | StarcoderdataPython |
5153523 | <filename>ressources/migrations/0008_auto_20200914_0007.py<gh_stars>0
# Generated by Django 3.0.3 on 2020-09-13 23:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ressources', '0007_auto_20200909_1811'),
]
operations = [
migrations.A... | StarcoderdataPython |
5046551 | import os
import unittest
import random
from src.hash import Hasher
from src.enums import CryptoSrcEnum
class TestEncryption(unittest.TestCase):
def test_valid_scrypt_hash(self):
for _ in range(10):
salt = os.urandom(32)
message = os.urandom(32)
hasher = H... | StarcoderdataPython |
1816989 | <reponame>darrencheng0817/AlgorithmLearning
'''
Created on 2016年2月16日
@author: Darren
'''
'''
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.
Here's an example:
1... | StarcoderdataPython |
5078669 | import requests
import pandas as pd
import util
currency_symbols = {
'bitcoin': 'BTC',
'SuperNET': 'KMD',
'eos': 'EOS',
'cardano-sl': 'ADA',
'lisk': 'LSK',
'0x.js': 'ZRX',
'skycoin': 'SKY'
}
def parse_contributors(data):
contributor_number_list = [0] * 52
for i in range(0, len(da... | StarcoderdataPython |
3425233 | #!/usr/bin/env python3
""" Testing suite to validate the analysis """
import unittest
import os
import numpy as np
from sauron import saruman
class TestCellFinder(unittest.TestCase):
""" Class to test the analysis of the image """
def setUp(self):
data_dir = os.path.abspath(os.path.join(__file__, '..... | StarcoderdataPython |
12802831 | <reponame>jpegbert/pycorrector
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE... | StarcoderdataPython |
6643056 | <reponame>zhangzhenqiqi/ActionCLIP
import torch
from ActionNet.action import Action
import pickle
import pandas as pd
def test():
torch.randint()
input = torch.randn(8 * 8, 64, 10, 10) # (N*T,C_in,H_in,W_in)
print(input.size())
net = torch.nn.Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1)... | StarcoderdataPython |
4997696 | from flask_login import UserMixin
from harperdb.exceptions import HarperDBError
from db import db
from db import schema
table = "accounts"
class Accounts:
@staticmethod
def create(username: str, password: str, superuser: bool):
payload = dict(
username=username,
password=pass... | StarcoderdataPython |
296450 | from __future__ import absolute_import
import numpy as np
from .Node import Op, NAME_RULE, PROFILING_MODE
from .. import profiler
from .._base import get_array_memory
class Conv2dOp(Op):
# nodeA : x nodeB : filter
def __call__(self, node_A, node_B, padding=0, padding2 = None, stride=1, For_ResNet = False):
... | StarcoderdataPython |
6485091 | #!/usr/bin/env python3
"""Noma [node management]
Usage: noma start
noma stop
noma check
noma logs
noma info
noma lnd create
noma lnd backup
noma lnd autounlock
noma lnd autoconnect [<path>]
noma lnd savepeers
noma lnd connectapp
n... | StarcoderdataPython |
1948608 | """
Module: 'ntptime' on esp32 3.0.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='3.0.0', version='v3.0.0 on 2020-01-29', machine='ESP32 module with ESP32')
# Stubber: 1.3.2
NTP_DELTA = 3155673600
host = 'pool.ntp.org'
def settime():
pass
socket = None
struct = None
def time():
pass
| StarcoderdataPython |
3261657 | <reponame>TomMalkin/Sqema
# -*- coding: utf-8 -*-
"""Defines the Sqema class."""
import pathlib
import simqle
import pandas as pd
class DatabaseRoot:
def __init__(self, database_directory: str, con_name: str):
"""
:type con_name: str
:type sqema_directory: str
"""
self.co... | StarcoderdataPython |
9623224 | import numpy as np
import glob
import torch.utils.data
class SLPWeightDataset(torch.utils.data.Dataset):
def __init__(self, cfg, phase):
position = cfg.SLP_DATASET.POSITION
cover_cond = cfg.SLP_DATASET.COVER_CONDITION
val_split = cfg.SLP_DATASET.VAL_SPLIT
if position == 'all':
... | StarcoderdataPython |
6505730 | __version__ = '0.0.1'
import pyperclip
def get_clipboard_data():
return pyperclip.paste()
def set_clipboard_data(data):
return pyperclip.copy(data)
| StarcoderdataPython |
106539 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Flask-Script subclasses."""
from flask import g, json, _request_ctx_stack, current_app, request
from flask_principal import identity_changed, Identity
from flask_script import (Command as BaseCommand, Manager as BaseManager,
Shell)
from werkzeug.data... | StarcoderdataPython |
6589615 | <filename>recipes/Python/475113_HTML_Help/recipe-475113.py
================================================================================
html_help.py
================================================================================
import time
import Zam
class html_table:
def __init__(self, rows, columns, inden... | StarcoderdataPython |
12808643 | from django import forms
from .models import Resource
class AddNewResourceForm(forms.ModelForm):
"""
"""
class Meta:
model = Resource
fields = ("type", "link")
# fields = ("name", "type", "description", "link")
def __init__(self, *args, **kwargs):
"""
@param a... | StarcoderdataPython |
311353 | <gh_stars>10-100
import pathlib
import requests
import zipfile
URL = "https://web.archive.org/web/20200318000445/http://archive.ics.uci.edu/ml/machine-learning-databases/00388/data.csv"
def download(from_path, to_path):
if not to_path.exists():
try:
r = requests.get(url=from_path)
... | StarcoderdataPython |
6564497 | from __future__ import print_function
import numpy as np
import os
import glob
import six
from .image import *
class NpzGeneratorDataset(object):
'''
Get the list of objects from a folder full of NP arrays.
'''
def __init__(self, name, split=0.1, preload=False):
'''
Set name of direc... | StarcoderdataPython |
11305423 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# flake8: noqa
from qiniu import Auth, put_file, etag, urlsafe_base64_encode
access_key = '<KEY>'
secret_key = '<KEY>'
# 初始化Auth状态å
q = Auth(access_key, secret_key)
# 你要测试的空间, 并且这个key在你空间中存在
bucket_name = 'crawler-pub'
key = 'mov/crawler.mov'
# 指定转码使用的队列名称
pipeline = ''
# ... | StarcoderdataPython |
3416658 | <filename>opentnsim/core.py
"""Main module."""
# package(s) related to time, space and id
import json
import logging
import uuid
# you need these dependencies (you can get these from anaconda)
# package(s) related to the simulation
import simpy
import random
import networkx as nx
import numpy as np
import math
import... | StarcoderdataPython |
1725016 | # ----------------------------------------------------
# Copyright The IETF Trust 2018-9, All Rights Reserved
# ----------------------------------------------------
import coverage
coverage.process_startup()
| StarcoderdataPython |
206040 | from sampleMangler.__main__ import main
def test_main():
assert main([]) == 0
| StarcoderdataPython |
3355600 | <reponame>mhp/del-plkr
#!/usr/bin/env python
# Heavily based on http://notes.natbat.net/2007/03/06/delicioussnaflr/
import urllib2, urllib, time, datetime
from xml.dom import minidom
deliciousUsername = 'xxxx'
deliciousPassword = '<PASSWORD>'
tag = 'plkr'
class DeliciousAccount():
apiRoot = 'https://api.del.icio.us... | StarcoderdataPython |
4842936 | from censusreporter.config.base.urls import urlpatterns, handler500
| StarcoderdataPython |
11214910 | from untwisted.network import *
from untwisted.event import *
from untwisted.utils.stdio import *
from untwisted.utils.shrug import *
from untwisted.task import *
from socket import *
from struct import pack
from socket import inet_aton
from re import finditer, compile, DOTALL
from UserDict import UserDict
DONE = get_... | StarcoderdataPython |
5081872 | from __future__ import print_function, division
from PIL.Image import NONE
import warnings
warnings.filterwarnings("ignore")
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
im... | StarcoderdataPython |
11309507 | from ctrlibrary.core.utils import get_observables
from ctrlibrary.threatresponse.enrich import enrich_observe_observables
from tests.functional.tests.constants import (
MODULE_NAME,
HIBP_URL,
CTR_ENTITIES_LIMIT
)
def test_positive_sighting_email(module_headers):
"""Perform testing for enrich observe o... | StarcoderdataPython |
6611247 | from headless_mju_crawler import *
options = webdriver.ChromeOptions()
options.binary_location='/usr/bin/google-chrome-unstable'
options.add_argument('headless')
options.add_argument('window-size=1200x800')
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://myiweb.mju.ac.kr')
mju_id = driver.find_elem... | StarcoderdataPython |
1696570 | <reponame>cjsteel/python3-venv-ansible-2.10.5
#!/usr/bin/python
# (c) 2020, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
'''
Element Software Info
'''
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {... | StarcoderdataPython |
1832685 | <filename>apf/core/step.py
from abc import abstractmethod
from apf.producers import GenericProducer
from apf.core import get_class
from apf.consumers import KafkaConsumer
import logging
import datetime
class GenericStep:
"""Generic Step for apf.
Parameters
----------
config : dict
Dictionar... | StarcoderdataPython |
276746 |
# Adding Frames to Video
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
from tkinter import filedialog
from PIL import ImageTk, Image
import cv2
from moviepy.editor import *
# Main Window & Configuration
window = tk.Tk() # created a tkinter g... | StarcoderdataPython |
6514203 | <reponame>X-rayLaser/multi-directional-mdrnn
import tensorflow as tf
from mdrnn._util.directions import Direction
class MultiDirectional(tf.keras.layers.Layer):
def __init__(self, rnn, **kwargs):
super(MultiDirectional, self).__init__(**kwargs)
self._original_rnn = rnn
directions = Direc... | StarcoderdataPython |
3595841 | from src.EthLeverageWallet import EthLeverage
from web3 import Web3
http_rpc = None # https://mainnet.infura.io/v3/...
# Automatically takes `w3.eth.accounts[0]` as the main account
i_EthLW = EthLeverage().init(http_rpc)
i_EthLW.buildContract()
value = 50 # 50 Ether
gasPrice = 100 # 100 Gwei
maxGas = 300... | StarcoderdataPython |
3592974 | <reponame>MatKie/SGTPy
from __future__ import division, print_function, absolute_import
import numpy as np
def g2mca(xhi00, khs, xm, da2new, suma_g2, eps, a1vdw_cte):
g2 = 3 * da2new / eps
g2 -= khs * suma_g2 / xhi00
g2 /= xm
g2 /= - a1vdw_cte
return g2
def dg2mca_dxhi00(xhi00, khs, dkhs, xm, ... | StarcoderdataPython |
8064941 | <gh_stars>100-1000
import logging
import struct
from enum import Enum
from typing import Optional, Tuple, Iterator, List
import lief # type: ignore
from .opcodes import OPCODES
from .utils import BitStream, crc_data, decrypt_lame, decrypt_mt, filetime_to_dt
EA05_MAGIC = bytes.fromhex("a3484bbe986c4aa9994c530a86d648... | StarcoderdataPython |
8149351 | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.bases.organization import OrganizationEndpoint
from sentry.api.serializers import serialize
from sentry.models import OrganizationMember
class OrganizationMemberIndexEndpoint(OrganizationEndpoint):
def get(self, ... | StarcoderdataPython |
6426158 | from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.home, name='home'),
path('list', views.post_list, name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:slug>/',views.post_detail,name='post_detail'),
] | StarcoderdataPython |
5197803 | <filename>tests/test_gist_comment.py<gh_stars>1000+
from tests.base import TestCase
from vilya.models.gist_comment import GistComment
from nose.tools import eq_
class TestGistComment(TestCase):
def test_gist_comment(self):
gist = self._add_gist()
user_id = 'testuser'
content = 'xxoo'
... | StarcoderdataPython |
1648728 | <gh_stars>0
import requests
from urllib3.exceptions import InsecureRequestWarning
from pprint import pprint
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
if __name__ == "__main__":
url = "https://netbox.lasthop.io/api/dcim"
http_headers = {}
http_headers["accept"] = "... | StarcoderdataPython |
3236692 | <reponame>jzcruiser/doltpy
import atexit
import logging
from typing import List
import psutil # type: ignore
HANDLERS: List[str] = []
SQL_LOG_FILE = None
def cleanup():
logger = logging.getLogger(__name__)
logger.info("Before exiting cleaning up child processes")
all_processes = psutil.Process().childr... | StarcoderdataPython |
8148351 | #!/usr/bin/env python
class IRCMessageBuilder(object):
MAX_MESSAGE_LENGTH = 80 * 4
MAX_NUM_PROJECTS = 4
COLORS = {
'white': "00", 'black': "01", 'blue': "02", 'green': "03", 'red': "04",
'brown': "05", 'purple': "06", 'orange': "07", 'yellow': "08", 'lime': "09",
'teal': "10", 'cy... | StarcoderdataPython |
1653750 | <filename>03_NonLinearRegression_Curve/main.py
import nonLinearRegressionCurve as R
R.clearScreen()
dataTraining= R.loadData("dataTraining.txt")
X=dataTraining[:,0:1]
y=dataTraining[:,1:2]
degree=3
theta =R.initTheta(X,degree)
theta = R.optimizedGradientDescent(X, y, theta,degree)
R.plotHypothesis(theta,X,y)
... | StarcoderdataPython |
8146151 | <reponame>harnitsignalfx/tf-synthetics<filename>python-syn/tests/test__histogram.py
from tests import TimedTestCase
from pyformance.meters import Histogram
class HistogramTestCase(TimedTestCase):
def test__a_sample_of_100_from_1000(self):
hist = Histogram(100, 0.99)
for i in range(1000):
... | StarcoderdataPython |
11397820 | import os
from setuptools import setup
NAME = "easyprocess"
# get __version__
__version__ = None
exec(open(os.path.join(NAME, "about.py")).read())
VERSION = __version__
PYPI_NAME = "EasyProcess"
URL = "https://github.com/ponty/easyprocess"
DESCRIPTION = "Easy to use Python subprocess interface."
LONG_DESCRIPTION = ... | StarcoderdataPython |
5139252 | <filename>core/algorithm/ppo.py
import torch
from torch.optim.adam import Adam
from core.model.policy_with_value import PolicyWithValue
from core.common import SampleBatch, ParamDict
import torch.nn.functional as F
def get_tensor(batch, device):
states = torch.as_tensor(batch["states"], dtype=torch.float32, devic... | StarcoderdataPython |
4800334 | #!/usr/bin/env python
# Copyright 2017 F5 Networks 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... | StarcoderdataPython |
8022434 | <filename>scr/Analysis/dbsnp_mapping/00-parse-gencode-gff3.py
import re,json,sys
def takeFirst(elem):
return elem[1]
def transfer_binary(seqlen,start,end):
bseq='0'+'0'*int(start)+'1'*(int(end)-int(start))+'0'*(int(seqlen)-int(end))
return bseq
def fix_position(pos_list):
pos_fina=[]
f... | StarcoderdataPython |
11248534 | from pymongo import MongoClient
import pickle
import os
import sys
_current_dir = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.normpath(os.path.join(_current_dir, ".."))
sys.path.append(PROJECT_ROOT)
from lib.config import config
ADDR = config.get('detector_agent', 'mongodb_uri')
DB_NAME = config... | StarcoderdataPython |
11273292 | # Created by Plutoberth
import subprocess, sys
from pathlib import Path
def enter_to_exit():
input("Enter to exit...")
sys.exit()
def ask_for_file():
file_name = input("filename: ")
print("-------------------------------------------------")
return file_name
def add_headers(fu... | StarcoderdataPython |
11350070 | #import ssubmit
import core
import sys
if __name__ == "__main__":
core.main('status', *sys.argv) | StarcoderdataPython |
3230454 | from client_sdk_python.module import (
Module,
)
import json
import rlp
from hexbytes import HexBytes
from client_sdk_python.utils.transactions import send_obj_transaction
class Debug(Module):
need_analyze = True
need_quota_gas = True
def economicConfig(self):
return json.loads(self.web3.man... | StarcoderdataPython |
319485 | # -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# PROJECT_NAME: design_pattern
# Name: builder.py
# Author: 9824373
# Date: 2020-08-15 16:49
# Contact: <EMAIL>
# Version: V1.0
# Des... | StarcoderdataPython |
6693492 | # -*- coding: utf-8 -*-
'''
Use three emotional dimensions - valence, arousal and dominance - to describe human perceptions of physical environments.
Interpretations of pleasure: Positive versus negative affective states (e.g. excitement, relaxation, love, and
tranquility versus cruelty, humiliation, disinterest, and ... | StarcoderdataPython |
3524368 | <gh_stars>1-10
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
# This is a simple example for a custom action which utters "Hello World!"
from typing import Any, Te... | StarcoderdataPython |
191766 | <filename>fv3config/config/__init__.py
from .namelist import (
config_to_namelist,
config_from_namelist,
)
from .rundir import write_run_directory
from .alter import enable_restart, set_run_duration
from .derive import get_n_processes, get_run_duration, get_timestep
from .nudging import get_nudging_assets, enab... | StarcoderdataPython |
9657277 | from ..core import Session, RequestError, const
import traceback
import json
import pandas as pd
class League(object):
version = const.VERSIONS['league']
@classmethod
def get_challenger_league(cls, session, queue, params={}):
r = None
try:
r = session.request(
url = const.URLS_LEAGUE['challenger leag... | StarcoderdataPython |
4906424 | <reponame>ROBACON/mobspy<filename>example_models/application_models/donor_receptor.py
import sys, os
from mobspy import *
"""
Here we have a model with a Phage, Donor and Receptor with resources being considered
Both the Donor and Receptor can reproduce with resources
The Donor can produce Phages with reso... | StarcoderdataPython |
8043004 | <reponame>petewasher/performance-comparisons<gh_stars>0
#! /usr/bin/python
import timeit
import msgpack
import umsgpack
import json
my_object = {"array":[1,2,3],"boolean":True,"null":None,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}
packed = msgpack.packb(my_object)
upacked = umsgpack.packb... | StarcoderdataPython |
1695222 | # flake8: noqa: W293
import logging
import textwrap
from typing import Optional
from irrd.utils import email
from .handler import ChangeSubmissionHandler
logger = logging.getLogger(__name__)
def handle_email_submission(email_txt: str) -> Optional[ChangeSubmissionHandler]:
handler = None
try:
msg = e... | StarcoderdataPython |
9772689 | <gh_stars>0
# <NAME>
# ADS UNIFIP
# Estrutura de Repetição
# 25/03/2020
'''
32- Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário.
Ex.: 5!=5.4.3.2.1=120. A saída deve ser conforme o exemplo abaixo:
Fatorial de: 5
5! = 5 . 4 . 3 . 2 . 1 = 120
'''
print('=' * 40)
print('{:=^4... | StarcoderdataPython |
3545204 | from rest_framework import viewsets
from user import serializers, models, filters
class UserView(viewsets.ModelViewSet):
queryset = models.User.objects.all()
serializer_class = serializers.UserSerializer
filter_class = filters.UserFilter
| StarcoderdataPython |
312767 | #!/usr/bin/env python
"""
Wrapper to ROS subscriber.
Author: <NAME>
Date: 05/18
"""
import rospy
class ROSSubscriber(object):
def __init__(self, _topic, _message_type):
"""
ROSSubscriber constructor.
:param _topic: string, ROS topic to publish on
:param _message_type: custom me... | StarcoderdataPython |
1964823 | <filename>slides/code/interlude_02_2.py
from datetime import datetime, timedelta
from pathlib import Path
files: list[Path] = []
for p in Path("/tmp").glob("*"):
timestamp = p.stat().st_mtime
ts_date = datetime.fromtimestamp(timestamp)
delta_max = timedelta(days=1)
if datetime.now() - ts_date < delta_... | StarcoderdataPython |
307272 | <reponame>politbuero-kampagnen/onegov-cloud<gh_stars>0
import hashlib
from onegov.activity.models import Activity, Attendee, Booking, Occasion
from onegov.user import User
from sqlalchemy import func
class Scoring(object):
""" Provides scoring based on a number of criteria.
A criteria is a callable which ta... | StarcoderdataPython |
11236958 | <reponame>ensoft/leap
# -----------------------------------------------------------------
# stackplot.py - Creates a stackplot from labelled coordinate data.
# June - September 2018 - <NAME>, Hrutvik
# -----------------------------------------------------------------
"""
Class that interacts with the flamegraph tool.
... | StarcoderdataPython |
9727036 | <filename>molecularsentry_match_mutant_position.py<gh_stars>0
import sys
import glob
file1= sys.argv[1] # list of the variants file
fh = open(file1.strip(),"r")
file2= sys.argv[2] # output from the epitope.js having epitopes-paratopes information from PDB
eph = open(file2.strip(),"r")
z=fh.readline()
import itertools
f... | StarcoderdataPython |
11312111 | # -*- coding: utf-8 -*-
from flask import Flask, request, render_template
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
app = Flask(__name__, static_folder='static', static_url_path='')
workspaces = {}
logfile = ""
config_task = {}
config_repo = {}
@app.route('/')
def index():
log_info = open... | StarcoderdataPython |
11364119 | # 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 applicable law or a... | StarcoderdataPython |
11354804 | from django.dispatch import receiver
from django.db.models.signals import post_save, pre_delete
from django.contrib.sessions.models import Session
from .models import CustomUser
from primaseru.models import StudentProfile, FatherStudentProfile, MotherStudentProfile, StudentGuardianProfile, PhotoProfile, MajorStudent,... | StarcoderdataPython |
6667980 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayCommerceEducateStudentIdentityQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceEducateStudentIdentityQueryResponse, self).__init__()
self.... | StarcoderdataPython |
1856989 | REGISTRY = {}
from .q_learner import QLearner
from .cql_learner import CQLLearner
REGISTRY["simple"] = QLearner
REGISTRY["cql"] = CQLLearner | StarcoderdataPython |
6689657 | """
29. Many-to-many and many-to-one relationships to the same table
Make sure to set ``related_name`` if you use relationships to the same table.
"""
from django.db import models
class User(models.Model):
username = models.CharField(max_length=20)
class Issue(models.Model):
num = models.IntegerField()
... | StarcoderdataPython |
11310871 | <gh_stars>0
from django.db import models
from datetime import date
# Create your models here.
from django.urls import reverse #Used to generate URLs by reversing the URL patterns
from datetime import date
from django.contrib.auth.models import User
class Review(models.Model):
""" Model representing a comment"""... | StarcoderdataPython |
1614306 | <filename>tests/python/gaia-unit-tests/gaia_unit_test/reporters/tbpl.py
from base import Base
class TBPLLogger(Base):
def __init__(self, *args, **kwargs):
self.logger = kwargs['logger']
del kwargs['logger']
Base.__init__(self, *args, **kwargs)
def on_pass(self, data):
self.log... | StarcoderdataPython |
1973389 | <filename>src/xp_elems.py
# Yahoo Finance frequently changes class names, use 'contains' for fuzzy matches
XP_ELEMS = {
"top_react" : "//span[text()[contains(.,'Top Reactions')]]",
"newest" : "//span[text()[contains(.,'Newest Reactions')]]",
"old_time_stamp" : "//li//div//div//span//span[t... | StarcoderdataPython |
3486619 | #!/usr/bin/env python3
# -*- coding: utf-8 -*
#/// DEPENDENCIES
import typing, os, aiofiles
import PIL #Image Conversion
import ffmpy3 as FIL #Sound and Video Conversion
import discord, pandas as pd
from discord.ext import commands
from discord.ext.commands import Bot, MissingPermissions, has_permissions
from chk.enbl... | StarcoderdataPython |
9743109 | # https://leetcode.com/problems/binary-tree-maximum-path-sum
# https://leetcode.com/problems/binary-tree-maximum-path-sum/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solut... | StarcoderdataPython |
81590 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Update cbpf
------------
"""
from hdx.data.resource import Resource
from hdx.utilities.dictandlist import write_list_to_csv
from src.helpers import cannonize_name
def update_cbpf(base_url, downloader, poolfundabbrv, today, valid_names, replace_values, resource_updates):... | StarcoderdataPython |
8160812 | from django.shortcuts import render
from django.db.models import Q
from api.v1.tools.paginator import customPagination
# serializers imports
from .serializers import NotificationSerializer
# rest_frameworks imports
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.permiss... | StarcoderdataPython |
11214550 | <filename>networking_cisco/plugins/cisco/cfg_agent/device_status.py
# Copyright 2014 Cisco Systems, 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
#
# ... | StarcoderdataPython |
9769553 | from functools import lru_cache
import numpy as np
__all__ = ['my_sum', 'factorial', 'trig_function']
def my_sum(iterable):
tot = 0
for i in iterable:
tot += i
return tot
@lru_cache(maxsize=None) # Note: -> @cache in python >= 3.9
def factorial(n):
return n * factorial(n-1) if n else 1
def... | StarcoderdataPython |
251710 | <reponame>invisprints/flyai_match
# -*- coding: utf-8 -*
from flyai.processor.base import Base
from flyai.processor.download import check_download
from path import DATA_PATH
from PIL import Image
from flyai.processor.base import Base
import cv2
from path import DATA_PATH
import os
import numpy as np
from albumentations... | StarcoderdataPython |
3392318 | <gh_stars>0
import logging
import telegram
from telegram import Bot
from telegram.ext import Updater, CommandHandler
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
API_TOKEN = None # Bot API TOKEN
ibot=Bot(token=API_TO... | StarcoderdataPython |
6488175 | import unittest
import uuid
from time import sleep
from forge_sdk import rpc
from event_chain.application import controllers
from event_chain.application import models
class SimpeFlowTest(unittest.TestCase):
def setUp(self):
self.alice = rpc.create_wallet(moniker='lily1', passphrase='<PASSWORD>')
... | StarcoderdataPython |
8135157 | #!/usr/bin/env pipenv-python
import sys
import os
import getopt
import base64
import ujson
import foolaunch
def usage(*args):
if args:
print("{0}: {1}".format(os.path.basename(sys.argv[0]), args[0]), file=sys.stderr)
print("usage: {0} [option]* <cfg>".format(os.path.basename(sys.argv[0])), file=sys.... | StarcoderdataPython |
4833050 | <filename>rendezvous/LineBot/admin.py<gh_stars>0
from django.contrib import admin
from .models import Reservation, Location, User, Announcement, Report
admin.site.register(Reservation)
admin.site.register(Location)
admin.site.register(User)
admin.site.register(Announcement)
admin.site.register(Report) | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.