id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
4873479 | import asyncio
from datetime import datetime
from typing import Callable, Awaitable, List, Union
from temporalcache.utils import should_expire # type: ignore
class Periodic(object):
def __init__(
self,
loop: asyncio.AbstractEventLoop,
last_ts: datetime,
function: Callable[..., Awa... | StarcoderdataPython |
189155 | <gh_stars>1-10
def swap_case(s):
t=""
for i in s:
if i.isalpha():
if i.isupper():
t=t+i.lower()
else:
t=t+i.upper()
else:
t=t+i
return (t)
| StarcoderdataPython |
378762 | <filename>JavaScripts/Image/PixelArea_qgis.py
import ee
from ee_plugin import Map
# Displays the decreasing area covered by a single pixel at
# higher latitudes using the Image.pixelArea() function.
# Create an image in which the value of each pixel is its area.
img = ee.Image.pixelArea()
Map.setCenter(0, 0, 3)
Map... | StarcoderdataPython |
11265313 | <gh_stars>0
"""Contains geographic mapping tools."""
from delphi_utils import GeoMapper
DATE_COL = "timestamp"
DATA_COLS = ['totalTest', 'numUniqueDevices', 'positiveTest', "population"]
GMPR = GeoMapper() # Use geo utils
GEO_KEY_DICT = {
"county": "fips",
"msa": "msa",
"hrr": "hrr",
"... | StarcoderdataPython |
4945301 | class SpireError(Exception):
"""..."""
class ConfigurationError(SpireError):
"""..."""
class LocalError(SpireError):
"""..."""
@classmethod
def construct(cls, name):
return cls('a value for %r is not available in the local context' % name)
class TemporaryStartupError(SpireError):
"""... | StarcoderdataPython |
1953534 | # -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# MAIN - Load configs, initialize logging and database
# ยฉ 2017 - 2020 February - 1200 Web Development <http://1200wd.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affer... | StarcoderdataPython |
6491703 | from bs4 import BeautifulSoup
import requests, dbconfig
db_Class = dbconfig.DataBase()
Cube_Option_Grade_List = {
"๋ ์ด": "Rare",
"์ํฝ": "Epic",
"์ ๋ํฌ": "Unique",
"๋ ์ ๋๋ฆฌ": "Legendary"
}
Cube_Option_Item_Type_List = {
"๋ฌด๊ธฐ": "Weapon",
"์ ๋ธ๋ ": "Emblem",
"๋ณด์กฐ๋ฌด๊ธฐ (ํฌ์ค์ค๋, ์์ธ๋ง ์ ์ธ)": "SubWeapon",
"ํฌ์ค์ค... | StarcoderdataPython |
4806812 | <reponame>yatao91/learning_road
# -*- coding: utf-8 -*-
from celery import Celery
app = Celery("demo", broker='redis://127.0.0.1:6379/4', backend='redis://127.0.0.1:6379/5')
| StarcoderdataPython |
8195333 | from django.apps import AppConfig
class TTestConfig(AppConfig):
name = 'ttest'
| StarcoderdataPython |
3324086 | import unittest
from .utilities import get_vault_object, generate_random_uuid, get_parameters_json
from vvrest.services.group_service import GroupService
class GroupServiceTest(unittest.TestCase):
vault = None
@classmethod
def setUpClass(cls):
if not cls.vault:
cls.vault = get_vault_o... | StarcoderdataPython |
6448601 | #Import the library needed
import pyautogui as p
import webbrowser as w
import time
#Taking input from user
x = input("Type whatever you want to search: ")
link = 'https://www.google.com/search?q={}'.format(x)
w.open(link)
#Delay for stability
time.sleep(1)
#Delay to let the page load
time.sleep(5)
#Moves... | StarcoderdataPython |
1822677 | <reponame>rsadaphule/nlp
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License
import random
import pytest
import numpy as np
import torch
from torch import nn
from utils_nlp.interpreter.Interpreter import (
Interpreter,
calculate_regularization,
)
def fixed_length_P... | StarcoderdataPython |
6441589 | <gh_stars>10-100
import http.client
import hashlib
import urllib
import random
import json
import nltk
from nltk.tokenize import sent_tokenize
from BackTranslation.translated import Translated
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
class BackTranslation_Baidu(obje... | StarcoderdataPython |
12845109 | <reponame>IntelLabs/OSCAR<gh_stars>10-100
#
# Copyright (C) 2020 Intel Corporation
#
# SPDX-License-Identifier: BSD-3-Clause
#
import logging
from collections import Counter
import torch
from torch.utils.data import DataLoader
from torchvision.transforms import transforms as T
from torchvision.transforms import funct... | StarcoderdataPython |
5128902 | """
Base class for ensemble models
Based on: https://github.com/yzhao062/combo/blob/master/combo/models/base.py
and extended for distributed incremental models
"""
import warnings
from collections import defaultdict
from abc import ABC, abstractmethod
from sklearn.utils import column_or_1d
from sklearn.utils.multiclas... | StarcoderdataPython |
4909835 | <reponame>Kymartin45/twitter-oauth2
from dotenv import dotenv_values
import base64
import requests
import json
config = dotenv_values('.env')
CLIENT_ID = config.get('TWITTER_CLIENT_ID')
CLIENT_SECRET = config.get('TWITTER_CLIENT_SECRET')
REDIRECT_URI = config.get('TWITTER_REDIRECT_URI')
# Authorize user account
def ... | StarcoderdataPython |
3556179 | <gh_stars>0
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import account_chart_template
from . import account_invoice
from . import account_move
from . import account_reconciliation_widget
from . import product
from . import stock
from . import res_config_set... | StarcoderdataPython |
9779822 |
import urllib.request,json
from .models import news
News = news.News
Sources = news.Sources
# getting api key
api_key = None
# getting the news base url
base_url = None
def configure_request(app):
global api_key, base_url
api_key = app.config["NEWS_API_KEY"]
base_url = app.config["NEWS_API_BASE_URL"]
... | StarcoderdataPython |
6675969 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import getdate, nowdate
no_cache = 1
no_sitemap = 1
def get_context(context):
result = []
return {"rowContent" ... | StarcoderdataPython |
11230850 | <reponame>invinst/CPDB<gh_stars>10-100
from django.http.response import HttpResponse
from django.views.generic import View
from common.models import OfficerAllegation
from common.json_serializer import JSONSerializer
from allegation.services.outcome_analytics import OutcomeAnalytics
from allegation.query_builders impo... | StarcoderdataPython |
3344769 | import requests
import time
url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson"
def load_json_data(json_url):
"""
:param json_url: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson"
:return: Earthquakes json data
"""
data = requests.get(j... | StarcoderdataPython |
6539838 | <reponame>techsaphal/NEPSE_ShareCalculator<gh_stars>0
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request,'share_buy_form.html')
def buy_calculate(request):
buy_price =int( request.GET["buy_price"])
share_number = i... | StarcoderdataPython |
1698401 | import os
import sys
if getattr(sys, 'frozen', False):
directory_containing_script = os.path.dirname(sys.executable)
else:
directory_containing_script = sys.path[0]
CACHE_TIME_TO_LIVE = 60
CACHE_WAIT_TIME = 3
CHANNEL_ICONS_DIRECTORY_PATH = os.path.join(
directory_containing_script, 'resources', 'icons', '... | StarcoderdataPython |
9695927 | <filename>demo/demo/urls.py
from django.conf.urls import url
from .views import index, listing, detailed
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^articles/$', listing, name='articles-listing'),
url(r'^articles/(?P<article_id>\d+)/$', detailed, name='articles-detailed'),
]
| StarcoderdataPython |
3271141 | #!/usr/bin/env python
from pyspark.sql import SparkSession
import sys, time
disabled = sys.argv[1]
spark = SparkSession.builder.appName('query1-sql').getOrCreate()
if disabled == "Y":
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
#set("spark.sql.cbo.enabled", "False")
elif disabled == 'N':
p... | StarcoderdataPython |
1614347 | <filename>upsampling/utils/__init__.py
from .dataset import Sequence
from .upsampler import Upsampler
from .utils import get_sequence_or_none
| StarcoderdataPython |
3344638 | <gh_stars>1-10
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
out = 0
for i in range(32):
bit = (n & (1 << i)) >> i
new_place = 32 - i - 1
out |= (bit << new_place)
return out
| StarcoderdataPython |
46900 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-11 22:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('history', '0004_history_prev_quantity'),
]
operations = [
m... | StarcoderdataPython |
11284341 | """
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublic... | StarcoderdataPython |
11369120 | <filename>MAC/mathapp/urls.py<gh_stars>1-10
from django.urls import path
from django.urls.conf import include
from mathapp import views as mathapp_views
urlpatterns = [
path('', mathapp_views.index, name='teste'),
path('special/<str:param>', mathapp_views.view_dinamica_str, name='dinamica_str'),
path('spe... | StarcoderdataPython |
1780876 | """First Migration
Revision ID: 523c20aa695
Revises:
Create Date: 2015-11-04 12:15:36.577201
"""
# revision identifiers, used by Alembic.
revision = '523c20aa695'
down_revision = None
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('companie... | StarcoderdataPython |
303563 | <filename>Codes/model_cal.py
import os
import glob
import pandas as pd
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d
from datetime import timedelta
# import matplotlib.pyplot as plt
# import warnings
from keras.preprocessing import sequence
import tensorflow as tf
from keras... | StarcoderdataPython |
4886857 | <filename>examples/control.py
# pylint: disable=W0621
"""Asynchronous Python client for the Fumis WiRCU API."""
import asyncio
from fumis import Fumis
async def main(loop):
"""Show example on controlling your Fumis WiRCU device."""
async with Fumis(mac="AABBCCDDEEFF", password="<PASSWORD>", loop=loop) as fu... | StarcoderdataPython |
6452455 | # coding=utf-8
class SpatialOrientation(object):
'''Spatial Orientation facade.
Computes the device's orientation based on the rotation matrix.
.. versionadded:: 1.3.1
'''
@property
def orientation(self):
'''Property that returns values of the current device orientation
as a... | StarcoderdataPython |
11272782 | <filename>exercicio7.py
filmes = ["forrest gump","fight club"]
jogos = ["mario","minecraft"]
livros = ["O senhor dos aneis","game of thrones"]
Esportes = ["basquete","futebol"]
#A
filmes.insert(1,"piratas do caribe")
filmes.insert(2,"velozes e furiosos")
jogos.insert(1,"sonic")
jogos.insert(2,"cs")
l... | StarcoderdataPython |
51863 | <gh_stars>0
from scitwi.users.user_entities import UserEntities
from scitwi.users.user_profile import UserProfile
from scitwi.utils.attrs import bool_attr, datetime_attr, str_attr, obj_attr
from scitwi.utils.attrs import int_attr
from scitwi.utils.strs import obj_string
class User(object):
"""
Users can be an... | StarcoderdataPython |
5132018 | # Copyright (c) 2013, Techlift and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import calendar
def execute(filters=None):
columns, data = [], []
data = prepare_data(filters)
columns = get_columns(filters)
return columns, data
... | StarcoderdataPython |
1956675 | #!/usr/bin/env python
# ENCODE annot_enrich (fraction of reads in annotated regions) wrapper
# Author: <NAME>, <NAME> (<EMAIL>)
import sys
import os
import argparse
from encode_lib_common import (
run_shell_cmd, strip_ext_ta,
ls_l, get_num_lines, log)
import warnings
warnings.filterwarnings("ignore")
def pa... | StarcoderdataPython |
12851895 | """This program first reads in the sqlite database made by ParseAuthors.py.
Then, after just a little data cleaning, it undergoes PCA decomposition.
After being decomposed via PCA, the author data is then clustered by way of a
K-means clustering algorithm. The number of clusters can be set by changing
the value of n_cl... | StarcoderdataPython |
1983476 | <reponame>zishun/Poisson-EVA2019
import numpy as np
import time
import util
fn_input = './data/anom.training.npy'
fn_output = './data/X_min_flip.npy'
data = -np.load(fn_input)
neighbors = np.load('./data/neighbor.npy').astype(np.int32)
start = time.time()
X_min = util.X_min_A_compute(data, neighbors)
print('compute X... | StarcoderdataPython |
1713852 | <reponame>RudSmith/netconf<gh_stars>10-100
# -*- coding: utf-8 -*-
# Copyright (C) 2018 Nippon Telegraph and Telephone 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
#
# htt... | StarcoderdataPython |
5013981 | <reponame>rgooler/comix
from flask import render_template
from app import app
import os
from flask import send_from_directory
from app.comicbook import comicbook
from natsort import natsorted
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
... | StarcoderdataPython |
1615291 | <filename>fluxture/structures.py
import asyncio
import itertools
from abc import ABCMeta
from collections import OrderedDict
from typing import Generic, Iterator, KeysView
from typing import OrderedDict as OrderedDictType
from typing import Tuple, Type, TypeVar
from typing import ValuesView
from typing import ValuesVie... | StarcoderdataPython |
12807534 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List
import dataclasses
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.animation import FuncAnimation
from .draw_obj import DrawObj
@dataclasses.dataclass
class ShipObj3dof:
"""Ship 3DOF class just for drawing.... | StarcoderdataPython |
5030524 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | StarcoderdataPython |
6557268 | from typing import List
# ้็บใขใธใฅใผใซ
from app.infra.db.base_repo import BaseRepo
from app.models.pets import PetSummary
class PetsRepo():
def __init__(self):
self.base_repo = BaseRepo()
def get_pets(self) -> List[PetSummary]:
sql = """
SELECT pet_id, name, type FROM pets;
""... | StarcoderdataPython |
1849856 | <filename>Python/067.py
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 67
Date: 16 Apr 2015
This code is the same as for problem 18, with a slight difference in the way
file is read.
Author: <NAME>
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
# Read data file
data = []
... | StarcoderdataPython |
5045216 | <reponame>proteneer/timemachine
# tests for parallel execution
import numpy as np
import random
from tempfile import NamedTemporaryFile
import parallel
from parallel import client, worker
from parallel.utils import get_gpu_count
import os
import unittest
from unittest.mock import patch
import grpc
import concurren... | StarcoderdataPython |
3323194 | <gh_stars>10-100
# Generated by Django 2.2.13 on 2020-07-28 20:28
from django.db import migrations
UPDATE_INTENDED_WATER_USE_CODES = """
UPDATE well SET intended_water_use_code = 'NA'
WHERE well_class_code = 'MONITOR' and intended_water_use_code = 'UNK';
UPDATE well SET
intended_water_use_code ... | StarcoderdataPython |
4944991 | <gh_stars>0
import time
import os
import requests
import json
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from intruo import Intruo, IntruoConfiguration, IntruoModules
from flask import Flask, render_template, jsonify, request, send_file
from nanoid import generate
DEBUG_INTRUO = True
templa... | StarcoderdataPython |
5029443 | <filename>tensorflow_addons/losses/sparsemax_loss_test.py<gh_stars>0
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... | StarcoderdataPython |
4804268 | print("Hola xd") | StarcoderdataPython |
5082240 | from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.x509.oid import ExtensionOID, NameOID
def is_ca(certificate):
# TODO: test self signed if no extensions found
extensions = certificate.extensions
try:
... | StarcoderdataPython |
12856526 | <filename>apps/goods/migrations/0063_auto_20200108_1555.py
# Generated by Django 2.1.8 on 2020-01-08 07:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('goods', '0062_auto_20191205_1656'),
]
operations = [
migrations.RenameField(
... | StarcoderdataPython |
3461336 | <filename>prometheus_adaptive_cards/config/logger.py
"""
Copyright 2020 <NAME>. Licensed under the Apache License 2.0
Configures Loguru by adding sinks and makes everything ready to be used for
logging with FastAPI and Uvicorn. Opinionated. Importing alone is not enough.
"""
import json
import logging
import sys
imp... | StarcoderdataPython |
104000 | class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
| StarcoderdataPython |
5081194 | <gh_stars>10-100
#!/usr/bin/env python3
import sys
import platform
def getinfo(name):
if name == "OS":
val = platform.system().lower()
if "msys" in val or "mingw" in val:
return "windows"
return val
elif name == "ARCH":
is64bit = platform.architecture()[0] == "64bit... | StarcoderdataPython |
6554679 | <reponame>lethain/phabulous
"""
Inspect the status of a given project.
"""
import phabulous
phab = phabulous.Phabulous()
project = phab.project(id=481)
# print out some stuff
print "%s\b" % project
for attr in ('name', 'date_created', 'phid', 'id'):
print "%s: %s" % (attr.capitalize(), getattr(project, attr))
p... | StarcoderdataPython |
159251 | <reponame>berleon/seqgan
import re
import numpy as np
from keras.utils.data_utils import get_file
class TextSequenceData:
def __init__(self, fname, origin, inlen=100, outlen=50,
step=10, strip_ws=True):
self.inlen = inlen
self.outlen = outlen
self.step = step
sel... | StarcoderdataPython |
6632912 | import sys
import weakref
import pydoc
from jfx_bridge import bridge
from .server.ghidra_bridge_port import DEFAULT_SERVER_PORT
from .server.ghidra_bridge_host import DEFAULT_SERVER_HOST
""" Use this list to exclude modules and names loaded by the remote ghidra_bridge side from being loaded into namespaces (they'll ... | StarcoderdataPython |
5115915 | import NodeDefender
fields = {'type' : 'value', 'readonly' : True, 'name' : 'Celsius', 'web_field'
: True}
info = {'number' : '1', 'name' : 'AirTemperature', 'commandclass' : 'msensor'}
def event(payload):
data = {'commandclass' : NodeDefender.icpe.zwave.commandclass.msensor.info,
'command... | StarcoderdataPython |
1673697 | <filename>Azure Microservices/CosmosDBTest/__init__.py
import logging
import azure.functions as func
import pymongo
from bson.json_util import dumps
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
if not... | StarcoderdataPython |
11305222 | <gh_stars>1-10
# DSMR P1 uitlezen
# (c) 10-2012 - GJ - gratis te kopieren en te plakken
versie = "1.0"
import sys
import serial
##############################################################################
#Main program
##############################################################################
print ("DSMR P1 uit... | StarcoderdataPython |
9799796 | <filename>packages/core/minos-microservice-aggregate/minos/aggregate/transactions/repositories/memory.py<gh_stars>100-1000
from datetime import (
datetime,
)
from typing import (
AsyncIterator,
Optional,
)
from uuid import (
UUID,
)
from minos.common import (
current_datetime,
)
from ...exceptions... | StarcoderdataPython |
175287 | <filename>src/modules/ArpFilter.py
from impacket import ImpactDecoder
import inspect
def dump(obj):
for name, data in inspect.getmembers(obj):
if name == '__builtins__':
continue
print '%s :' % name, repr(data)
class ArpFilter():
attributes = None
myIpAddresses = None
logger = None
def __init_... | StarcoderdataPython |
5183031 | <reponame>ningyixue/AIPI530_Final_Project
from abc import ABCMeta, abstractmethod
from typing import Optional
import torch
from ..encoders import Encoder, EncoderWithAction
class QFunction(metaclass=ABCMeta):
@abstractmethod
def compute_error(
self,
obs_t: torch.Tensor,
act_t: torch.... | StarcoderdataPython |
1884549 | import bokego.go as go
import os
from math import sqrt
from tqdm import trange
import numpy as np
import pandas as pd
import torch
from torch.distributions.categorical import Categorical
from torch.utils.data import Dataset, DataLoader
from torch.nn.modules.utils import _pair
from torch.nn.parameter import Parameter
im... | StarcoderdataPython |
193384 | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | StarcoderdataPython |
1820089 | # Copyright 2019 the ProGraML authors.
#
# Contact <NAME> <<EMAIL>>.
#
# 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 a... | StarcoderdataPython |
96063 | import os
from catalog import app
app.run(debug=True, host=os.environ.get('CATALOG_HOST'), port=os.environ.get('CATALOG_PORT'))
| StarcoderdataPython |
9603122 | <reponame>kevin0120/onesphere
# -*- coding: utf-8 -*-
{
'name': "onesphere_spc",
'summary': """
้็จSPCๆจกๅ""",
'description': """
้็จSPCๆจกๅ
""",
'author': "ไธๆตทๆไบซๆฐๆฎ็งๆๆ้ๅ
ฌๅธ",
'website': "http://www.oneshare.com.cn",
'category': 'Manufacturing/Manufacturing',
'version': '192.16... | StarcoderdataPython |
6512527 | <filename>examples/example_13.py<gh_stars>1-10
# SymBeam examples suit
# ==========================================================================================
# <NAME> <<EMAIL>> 2020
# Features: 1. Symbolic length
# 2. Fixed
# 3. Symbolic poi... | StarcoderdataPython |
1726953 | <gh_stars>1-10
"""
Make graphs (lifecycles, ...)
"""
from __future__ import absolute_import, division, print_function
import os
import sys
import json
from collections import OrderedDict
try:
import pygraphviz as pgv
except ImportError:
print('(optional) install pygraphviz to generate graphs')
... | StarcoderdataPython |
8138662 | <gh_stars>1-10
from django.contrib import admin
from pinax.apps.account.models import Account, PasswordReset
class PasswordResetAdmin(admin.ModelAdmin):
list_display = ["user", "temp_key", "timestamp", "reset"]
admin.site.register(Account)
admin.site.register(PasswordReset, PasswordResetAdmin) | StarcoderdataPython |
5017990 | # -*- coding: utf-8 -*-
def break_text(sentence, k):
words = sentence.split()
broken_text = []
char_count = -1
current_words = []
idx = 0
while idx < len(words):
word = words[idx]
if len(word) > k:
return None
if char_count + len(word) + 1 <= k:
... | StarcoderdataPython |
3580856 | <gh_stars>0
from __future__ import print_function
import cv2 as cv
import numpy as np
import time
from rect_selector import RectSelector
from processor import Processor
from play import Play
class App:
def __init__(self, camera):
self.cap = cv.VideoCapture(camera)
# run `ffmpeg -f v4l2 -list_form... | StarcoderdataPython |
6407277 | """
biped
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from mcedit2.rendering.chunkmeshes.entity.modelrenderer import ModelRenderer
log = logging.getLogger(__name__)
class ModelBiped(object):
textureWidth = 64
textureHeight = 32
def __init__(se... | StarcoderdataPython |
8113896 | from __future__ import print_function, division
import signal, importlib, sys, logging, os
import click
from .version import __version__
logLevels = ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET']
@click.group()
@click.version_option(version=__version__)
def cli():
# to make this script/module behav... | StarcoderdataPython |
9721995 | <reponame>ViolaBuddy/EscapeFromPlegia
import logging
import math
from app.data.database import DB
from app.engine import (action, combat_calcs, engine, equations, evaluate,
item_funcs, item_system, line_of_sight, pathfinding,
skill_system, target_system)
from app.engine.... | StarcoderdataPython |
3381413 | <reponame>JIABI/GhostShiftAddNet
import torch
try:
import unoptimized_cuda
except:
print("Unable to import CUDA unoptimized kernels")
def linear(input, weight, bias):
out = torch.zeros([input.size(0), weight.size(0)], dtype=torch.float, device=torch.device('cuda:0'))
if bias is not None:
unopti... | StarcoderdataPython |
1978335 | # -*- coding: utf-8 -*-
import glob, os, json, pickle
import pandas as pd
import numpy as np
from scipy import ones,arange,floor
from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.grid_search import... | StarcoderdataPython |
188169 | <filename>models/search_result.py
# coding: utf-8
from __future__ import absolute_import
from .base_model_ import Model
from . import util
class SearchResult(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, n... | StarcoderdataPython |
3316719 | import re
subst = re.compile("(%\((\w+)\))")
def substitute_str(text, vars):
out = []
i0 = 0
for m in subst.finditer(text):
name = m.group(2)
if name in vars:
out.append(text[i0:m.start(1)])
out.append(str(vars[name]))
i0 = m.end(1)
out.append(text[i... | StarcoderdataPython |
3296111 | import time
from .utils import make_graph, preprocess_features, run_pic
class PIC:
"""Class to perform Power Iteration Clustering on a graph of nearest neighbors.
Args:
args: for consistency with k-means init
sigma (float): bandwith of the Gaussian kernel (default 0.2)
... | StarcoderdataPython |
11325239 | from django.conf import settings
from django.shortcuts import render
def home(request):
context = {
'google_street_view_api_key': settings.GOOGLE_STREET_VIEW_API_KEY
}
return render(request, 'layers/home.html', context=context)
| StarcoderdataPython |
164374 | # this file is required to get the pytest working with relative imports
| StarcoderdataPython |
1633682 | import asyncio
import logging
import sys
import asynctnt
logging.basicConfig(level=logging.DEBUG)
async def main():
c = asynctnt.Connection(
host='localhost',
port=3305,
connect_timeout=5,
request_timeout=5,
reconnect_timeout=1/3,
)
async with c:
while Tru... | StarcoderdataPython |
3304066 | import abc
import asyncio
import logging
from types import MethodType
from typing import List, Optional
from pydantic import BaseSettings
from arrlio.models import Message, TaskInstance, TaskResult
from arrlio.serializer.base import Serializer
from arrlio.tp import AsyncCallableT, SerializerT, TimeoutT
logger = log... | StarcoderdataPython |
115703 | <gh_stars>1-10
import numpy as np
import pandas as pd
import random
import pickle
import os
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from pipelitools.models import metrics as m
def test_models():
""" """
print('test_models: ok')
class Model:
"""Runs a model, plots confusion... | StarcoderdataPython |
1666479 | <reponame>VlachosGroup/PythonGroupAdditivity
import os
from warnings import warn
from collections import Mapping
from .. import yaml_io
import numpy as np
from .. Error import GroupMissingDataError
from . Group import Group, Descriptor
from . Scheme import GroupAdditivityScheme
from . DataDir import get_data_dir
cla... | StarcoderdataPython |
8092325 | <reponame>dearith/mfadmin
#!/usr/bin/env python3
import argparse
import requests
import os
import sys
from mflog import get_logger
DESCRIPTION = "export a kibana dashboard on stdout"
KIBANA_PORT = int(os.environ['MFADMIN_KIBANA_HTTP_PORT'])
KIBANA_PATTERN = \
"http://127.0.0.1:%i/api/kibana/" \
"dashboards/ex... | StarcoderdataPython |
369428 | #!/usr/bin/env python3
import argparse
from datetime import datetime
import json
from pathlib import Path
import logging
import sys
import hpc_submit
import mgm_utils
import kaldi_transcript_to_amp_transcript
def main():
"""
Submit a job to run ina speech segmenter on HPC
"""
parser = argparse.Argume... | StarcoderdataPython |
343669 | """Dataset with 'Variola virus' sequences.
A dataset with 51 'Variola virus' genomes.
THIS PYTHON FILE WAS GENERATED BY A COMPUTER PROGRAM! DO NOT EDIT!
"""
import sys
from catch.datasets import GenomesDatasetSingleChrom
ds = GenomesDatasetSingleChrom(__name__, __file__, __spec__)
ds.add_fasta_path("data/variola.... | StarcoderdataPython |
1865034 | <reponame>JainSamyak8840/deepchem<gh_stars>0
class Loss:
"""A loss function for use in training models."""
def _compute_tf_loss(self, output, labels):
"""Compute the loss function for TensorFlow tensors.
The inputs are tensors containing the model's outputs and the labels for a
batch. The return valu... | StarcoderdataPython |
288708 | import os
import sys
import pickle
from typing import List
import numpy as np
import pandas as pd
from scipy.optimize import minimize_scalar
os.environ["OPENBLAS_NUM_THREADS"] = "1"
sys.path.append("../../")
from environments.Settings.EnvironmentManager import EnvironmentManager
from environments.Settings.Scenario i... | StarcoderdataPython |
3267186 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import logging
import shutil
from datetime import datetime, timedelta
from multiprocessing import Process, Queue
from time import sleep
from configuration import (
data_dir,
download_file,
env_bin,
output_dir,
processed_file,
temporary_dir,
)
from wildfir... | StarcoderdataPython |
1851179 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.DeliveryActivityContentInfo import DeliveryActivityContentInfo
class DeliveryContentInfo(object):
def __init__(self):
self._delivery_activity_content = None
s... | StarcoderdataPython |
4919034 | <gh_stars>0
#
# Copyright (c) 2018 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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 ... | StarcoderdataPython |
9716837 | <filename>train_model.py
import numpy as np
import tensorflow
from tensorflow.keras import Sequential, Model, Input
from tensorflow.keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectional
from tensorflow.keras.utils import plot_model
from numpy.random import seed
from read_data import read_d... | StarcoderdataPython |
1906255 | #!/usr/bin/env python3
# vim: sta:et:sw=4:ts=4:sts=4
"""
NAME
fermi_helper.py - Build and run Fermi HEP workflow using Docker/Singularity
SYNOPSIS
python3 fermi_helper.py build-docker-image [--tag TAG]
[--only-dependencies] [--pull-dependencies TAG] [--decaf-root ROOT]
[--decaf-repo REPO] [--de... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.