id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1808992 | <filename>emumbaproject/middleware.py<gh_stars>0
"""
Contains all custom middleware classes written for todofehrist app.
"""
import logging
class LoggingRequestResponse:
"""
This class is implements functionality to log all requests
and responses to/from todofehrist RESTful endpoints.
"""
... | StarcoderdataPython |
3398369 | <reponame>pavva94/DeepLearningProject
# -*- coding: utf-8 -*-
"""DeepComedy.ipynb
Automatically generated by Colaboratory.
# DeepComedy: AI Generated Divine Comedy
Author: **<NAME>, <NAME>**
This Notebook contains a **text generator RNN** that was trained on the **Divina Commedia** (the *Divine Comedy*) by **<NAME>... | StarcoderdataPython |
6532904 | from pyexlatex.models.item import SimpleItem
from pyexlatex.models.section.base import TextAreaMixin
from pyexlatex.typing import PyexlatexItems
class Closing(TextAreaMixin, SimpleItem):
name = 'closing'
def __init__(self, closing: PyexlatexItems):
self.closing = closing
super().__init__(self... | StarcoderdataPython |
6435604 | from .api_exception import APIException
from .response_handler import ResponseHandler
from .response_wrapper import ResponseWrapper
from .body_wrapper import BodyWrapper
from .query_operations import QueryOperations
| StarcoderdataPython |
9795100 | <filename>blotter/blotter.py<gh_stars>10-100
import pandas as pd
import numpy as np
import json
import re
from collections import namedtuple
from array import array
from . import marketdata
class _Event():
# this class manages the actions which are performed on the Holdings class
# and encapsulates all the da... | StarcoderdataPython |
9701370 | coating_2500 = "An ultra-low DFT advanced coating system targeted for refinery crude unit and FCC slurry fouling by enhancing tube lubricity and reducing surface tension. Curran 2500 is designed for high temperature DCU, VDU and FCCU crude services, and can be applied to tube exchangers, P&F exchangers and distillation... | StarcoderdataPython |
6524258 | '''
Changes in sales over time:
Line plots are designed to visualize the relationship between two numeric variables,
where each data values is connected to the next one. They are especially useful for
visualizing the change in a number over time since each time point is naturally connected
to the next time point. In... | StarcoderdataPython |
1778862 | <filename>testing/procedure_409_test.py
# This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
# Load data
import datetime
import json
from mldb import mldb
datasetConfig = {
"type": "sparse.mutable",
"id": "iris_dataset"
}
dataset = mldb.create_dataset(datasetConfig)
ts =... | StarcoderdataPython |
4880130 | from collections import deque
from itertools import chain, islice
def chunks(items, chunksize):
"""Turn generator sequence into sequence of chunks."""
items = iter(items)
for first in items:
chunk = chain((first,), islice(items, chunksize - 1))
yield chunk
deque(chunk, 0)
| StarcoderdataPython |
1833121 | import os
import sys
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath('.')
from flask import Flask, render_template
from flask_cors import CORS
from controllers.clipboard_history_controller import clipboard_history_controller
PREFIX = '/api/v1'
template_folder = os.path.join(base... | StarcoderdataPython |
5029764 | import enum
class EventType(enum.Enum):
EVENT_TYPE_UNKNOWN = 0
EVENT_TYPE_REGULAR_CHAT_MESSAGE = 1
EVENT_TYPE_SMS = 2
EVENT_TYPE_VOICEMAIL = 3
EVENT_TYPE_ADD_USER = 4
EVENT_TYPE_REMOVE_USER = 5
EVENT_TYPE_CONVERSATION_RENAME = 6
EVENT_TYPE_HANGOUT = 7
EVENT_TYPE_PHONE_CALL = 8
... | StarcoderdataPython |
1821321 | from pycwr.io import read_auto
import matplotlib.pyplot as plt
import numpy as np
from pycwr.draw.RadarPlot import Graph
file = r"C:\Users\zy\Desktop\HID\NUIST.20160707.001054.AR2"
NRadar = read_auto(file)
num = 3
NRadar.fields[num]['dBZ'][:] = np.where(NRadar.fields[num].CC>0.9, NRadar.fields[num].dBZ, np.nan)
NRada... | StarcoderdataPython |
1645981 | import sys
import os
def greeting(name):
print('Hi,', name)
def test_greeting(capfd):
greeting('Brian')
out, err = capfd.readouterr()
assert out == 'Hi, Brian\n'
def test_multiline(capfd):
greeting('Brian')
greeting('Nerd')
out, err = capfd.readouterr()
assert out == 'Hi, Bria... | StarcoderdataPython |
1882107 | <filename>bot/database.py
# -*- coding: utf-8 -*-
import logging
import logging.config
import random
import sqlite3
from enum import Enum
import phrases
logging.config.fileConfig("logging.ini")
logger = logging.getLogger("database")
## === Classes === ##
class Category(Enum):
"""Categories in the d... | StarcoderdataPython |
9601915 | import json
""" Sorts and prints in descending order by duration function call
execution times in execution-times.log.
BrowserLibrary debug option needs to be True to record times to the logfile.
"""
with open("Browser/wrapper/execution-times.log") as log_file:
data = [json.loads(row) for row in log_file... | StarcoderdataPython |
9641232 | import unittest
import io
import os
from os.path import join as pjoin
import shutil
from base64 import encodebytes
from nbformat import write
from nbformat.v4 import (
new_notebook, new_markdown_cell, new_code_cell, new_output,
)
from offlineslides import export_to_offline_slides
png_green_pixel = encodebytes(b'... | StarcoderdataPython |
1754618 | <gh_stars>1-10
import argparse
import csv
import json
import os
import shlex
import shutil
import sys
import tempfile
from unittest.mock import MagicMock, patch
import pandas as pd
from . import REPO_ROOT, TEST_DATA
from .helpers import ChDir, mock_worksheet_helper
try:
PATH = sys.path
sys.path.append(REPO_R... | StarcoderdataPython |
1976249 | <gh_stars>100-1000
import base64
from pprint import pprint
import redis
import json
from django.conf import settings
from config.celery import app
"""
Helpers to inspect and edit the celery job queue.
Called from `fab celery_*`.
"""
def jobs_pending():
"""List all jobs not yet claimed by a worker."""
... | StarcoderdataPython |
6426001 | from flask import render_template
import connexion
app = connexion.App(__name__, specification_dir="config")
app.add_api("swagger.yml")
@app.route("/")
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True)
| StarcoderdataPython |
1804100 | from django.core.mail import send_mail
from django.conf import settings
import logging
logger = logging.getLogger('django')
from celery_tasks.main import celery_app
# 定义一个发送函数, 发送 email:
@celery_app.task(name='send_verify_email')
def send_verify_email(to_email, verify_url):
# 标题
subject = "商城邮箱验证"
# 发送内容... | StarcoderdataPython |
5014958 | <filename>pymic/loss/cls/nll.py
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import torch
import torch.nn as nn
class NLLLoss(nn.Module):
def __init__(self, params):
super(NLLLoss, self).__init__()
self.nll_loss = nn.NLLLoss()
def forward(self, loss_input_dict):... | StarcoderdataPython |
3581994 | <filename>maptapp/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-19 14:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
mig... | StarcoderdataPython |
1894377 | # -*- coding: utf-8 -*-
"""
/dms/webquest/views_add.py
.. enthaelt den View zum Ergaenzen eines Webquests
Django content Management System
<NAME>
<EMAIL>
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 30.04.2008 Beginn der Arbeit
... | StarcoderdataPython |
5152070 | # Copyright (C) 2017-2019 New York University,
# University at Buffalo,
# Illinois Institute of Technology.
#
# 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 th... | StarcoderdataPython |
154816 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... | StarcoderdataPython |
1678815 | <reponame>GuyTeichman/RNAlysis
# -*- coding: utf-8 -*-
"""Top-level package for sRNA analysis pipeline."""
__all__ = ['general', 'filtering', 'enrichment']
__name__ = "rnalysis"
__author__ = """<NAME>"""
__email__ = "<EMAIL>"
__version__ = "1.3.4"
__license__ = "MIT"
__attr_file_key__ = "attribute_reference_table"""
... | StarcoderdataPython |
6441328 | from django.shortcuts import render
import shopify
from shopify_app.decorators import shop_login_required
@shop_login_required
def index(request):
products = shopify.Product.find(limit=3)
return render(request, 'home/index.html', {'products': products})
| StarcoderdataPython |
6605190 | <filename>app/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQL_ACLHEMY_DB = 'mysql+pymysql://dzhonpetrus:root@localhost/treatment_management'
engine = create_engine(SQL_ACLHEMY_DB)
SessionLocal = sessionmaker(bind=eng... | StarcoderdataPython |
3552887 | import tensorflow as tf
def my_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(1, 3, input_shape=[28,28,1]),
tf.keras.layers.Conv2D(1, 3),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.... | StarcoderdataPython |
5034375 | <reponame>yuta0306/notion-extensions
from typing import Dict, Union
from .block import Block
__all__ = [
"Divider",
]
class Divider(Block):
"""
Divider
Divider property values of block
Attributes
----------
Methods
-------
clear()
Clear data of title
json()
... | StarcoderdataPython |
1778737 | <reponame>attesch/webbreaker
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from webbreaker.threadfix.common.helper import ThreadFixHelper
from webbreaker.threadfix.common.loghelper import ThreadFixLogHelper
threadfixloghelper = ThreadFixLogHelper()
class ThreadFixTeams(object):
def __init__(self):
self.... | StarcoderdataPython |
1951736 | from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING, Callable, List, Optional
from rotkehlchen.types import ChecksumEthAddress
if TYPE_CHECKING:
from rotkehlchen.accounting.structures.balance import AssetBalance
class EthereumModule(metaclass=ABCMeta):
"""Interface to be followed by all... | StarcoderdataPython |
12816661 | from sqlalchemy import (
Column,
Index,
Integer,
Text,
TIMESTAMP,
Boolean
)
from .meta import Base
import datetime
class Login(Base):
__tablename__ = 'login'
id = Column(Integer, primary_key=True)
email = Column(Text, nullable=False)
password = Column(Text, nullable=False)
cl... | StarcoderdataPython |
8084783 | <gh_stars>1-10
import os, sys
import zipfile
import subprocess
from shutil import copyfile
# Define the path to love-android-sdl2 here:
path_to_love_android = "C:/Android/love-android-sdl2"
#Record the current working directory at the beginning:
start_directory = os.path.realpath(__file__)
def zipgame(path, loveZip)... | StarcoderdataPython |
6474188 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2016 PPMessage.
# @author <EMAIL>
#
#
from ppmessage.db.models import MessagePushTask
from ppmessage.db.models import ConversationUserData
from ppmessage.core.redis import redis_hash_to_dict
from ppmessage.core.constant import CONVERSATION_STATUS
def get_app_conversati... | StarcoderdataPython |
6493347 | <reponame>Narendra-Git-Hub/website
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-08-24 10:37
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('organisation', '0014_auto_20200824_1033'),
]
operations... | StarcoderdataPython |
3225361 | # coding: utf-8
from flask_login import login_required
from flask import Blueprint, request
from marshmallow import Schema, fields
from app.libs.http import jsonify, error_jsonify
from app.model.data_collection import DataCollection
from app.model.corporate_Info import Info
from app.model.report_time import ReportTi... | StarcoderdataPython |
11359506 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
class Explosion():
posX = 0
posY = 0
stage = [[]]
stages = [[[]]]
i = 0
def __init__(self, posX, posY):
stageOne = [["E"]]
stageTwo = [["E","E","E"],["E"," ","E"],["E","E","E"]]
stageThree = [[" ","E","E","E"," "],["E"," ... | StarcoderdataPython |
6652025 | import os
import sys
import ast
import functools
import torch
import numpy as np
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
def get_PointNet_train_valid_test_loader(root, target, max_Miller, diffraction, cell_type,
... | StarcoderdataPython |
8014236 | from functools import wraps
from flask import current_app, abort, request
def requires_debug(view):
@wraps(view)
def _(*args, **kwargs):
strict = not current_app.config.get('FLASK_DEBUG_DISABLE_STRICT',
False)
if not current_app.debug:
i... | StarcoderdataPython |
12802113 | <reponame>mfbsouza/PID-Rocket
from rocket import Rocket
from pid import PID
import matplotlib.pylab as plt
def main():
kp = 1.5
kd = 2.7
ki = 0.007
height_vals = []
speed_vals = []
accel_vals = []
pid_output = []
setpoint = []
x_vals = []
time = 0.01
simulation_time = 90.0 # 90 seconds
rocket_mass = 10 ... | StarcoderdataPython |
3518130 | <reponame>Twente-Mining/tezos-reward-distributor
import json
from util.client_utils import clear_terminal_chars
def parse_json_response(client_response, verbose=None):
client_response = clear_terminal_chars(client_response)
# because of disclaimer header; find beginning of response
idx = client_response... | StarcoderdataPython |
9632172 | import logging
from collections.abc import Sequence
from contextlib import AsyncExitStack
from typing import Optional
import aiohttp
from .cluster import Cluster
from .cluster_config import ClusterConfig
from .config import RegistryConfig, StorageConfig
from .orchestrator.kube_client import KubeClient, NodeWatcher, P... | StarcoderdataPython |
305390 | <gh_stars>0
import rvo2
import numpy as np
import matplotlib.pyplot as plt
sim = rvo2.PyRVOSimulator(1/100., 1, 5, 1.5, 1.5, 0.5, 5)
# Pass either just the position (the other parameters then use
# the default values passed to the PyRVOSimulator constructor),
# or pass all available parameters.
a0 = sim.addAgent((0, ... | StarcoderdataPython |
12822421 | # coding: utf-8
from typing import Dict, List # noqa: F401
from fastapi import ( # noqa: F401
APIRouter,
Body,
Cookie,
Depends,
Form,
Header,
Path,
Query,
Request,
Response,
Security,
status,
)
from acapy_wrapper.models.extra_models import TokenModel # noqa: F401
fr... | StarcoderdataPython |
4919320 | <filename>automapping-stuff/bh_hierarchy_expand.py
import re
from collections import deque
import networkx as nx
from networkx.algorithms import isomorphism
import matplotlib.pyplot as plt
import pandas as pd
import brickschema
from brickschema.namespaces import BRICK, RDFS
from fuzzywuzzy import process, fuzz
class H... | StarcoderdataPython |
1624502 | <reponame>antiprism/antiprism_python
#!/usr/bin/env python3
# Copyright (c) 2014-2016 <NAME> <<EMAIL>>
# 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 ... | StarcoderdataPython |
146763 | # type: ignore
from typing import Any
import qtvscodestyle as qtvsc
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt
from PySide6.QtGui import QAction, QActionGroup, QTextOption
from PySide6.QtWidgets import (
QCheckBox,
QColorDialog,
QComboBox,
QDateTimeEdit,
QDial,
QDockWidget... | StarcoderdataPython |
6631894 | <reponame>icebreaker/dotfiles
import gedit
from FindInProject import FindInProjectPluginInstance
class FindInProjectPlugin(gedit.Plugin):
def __init__(self):
gedit.Plugin.__init__(self)
self._instances = {}
def activate(self, window):
self._instances[window] = FindInProjectPluginInstan... | StarcoderdataPython |
6515101 | # coding: utf-8
"""
Graphical user interface for the Phase Retrieval Algorithm based on:
<NAME>.; <NAME>.; <NAME>.; <NAME>.
Phase Retrieval for High-Numerical-Aperture Optical Systems.
Optics Letters 2003, 28 (10), 801.](dx.doi.org/10.1364/OL.28.000801)
The user interface allows to select the PSF files (supported by b... | StarcoderdataPython |
4878824 | <reponame>dcos/dcos-bot-branches
# Copyright (C) Mesosphere, Inc. See LICENSE file for details.
"""IAM mock endpoint.
"""
import logging
from exceptions import EndpointException
from mocker.endpoints.recording import (
RecordingHTTPRequestHandler,
RecordingTcpIpEndpoint,
)
# pylint: disable=C0103
log = logg... | StarcoderdataPython |
11358259 | import logging
import azure.functions as func
import json
import os
from azure.storage.blob import BlobServiceClient
#
# Azure Blob Integration
#
graph_connection_string = os.environ["AzureGraphStorage"]
graph_container = os.environ["AzureGraphContainer"]
blob_service_client = BlobServiceClient.from_conne... | StarcoderdataPython |
149394 | <filename>database.py
import sqlite3
__all__ = ['Database']
class Database(object):
__vars__ = []
def __init__(self, name):
self._name = name
def _execute(self, command, args=None):
connection = sqlite3.connect("exel.db")
cursor = connection.cursor()
if args is None... | StarcoderdataPython |
6477959 | <reponame>padmec-reservoir/impress<gh_stars>1-10
"""
Module for implementation of multiscale mesh and CoarseVolumes objects functionalities
"""
from . finescaleMesh import FineScaleMesh
from ..msCoarseningLib import algoritmo
from ..msCoarseningLib.partitionTools import partitionManager
from . serialization import IMPR... | StarcoderdataPython |
6677185 | DATA_DIR = '../data/modelnet40v1'
IMG_SUFFIX_LIST = ['.jpg', '.jpeg']
TRAIN_FOLDER_NAME = 'train'
VALIDATION_FOLDER_NAME = 'test'
NUM_WORKERS = 8
NORMALIZATION_MEAN = [0.485, 0.456, 0.406]
NORMALIZATION_STD = [0.229, 0.224, 0.225]
CLASSIFICATION_THRESHOLD = 0.5
F1_AVERAGE='macro' | StarcoderdataPython |
279935 | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
L = len(bin(max(nums))) - 2
nums = [[(num >> i) & 1 for i in range(L)][::-1] for num in nums]
maxXor, trie = 0, {}
for num in nums:
currentNode, xorNode, currentXor = trie, trie, 0
for bit in nu... | StarcoderdataPython |
6422489 | # load modules
from dataclasses import dataclass
from typing import List, Union
from . import Metadata, Score
# definition class
@dataclass(frozen=True)
class ScoreCollection:
scores: Union[List[Score.Score], List, None]
metadata: Union[Metadata.Metadata, None]
# definition function
def gen(response):
... | StarcoderdataPython |
3408405 | <gh_stars>0
from .mm_tasks import *
from .ofa_task import OFATask | StarcoderdataPython |
1771370 | def first_last6(nums):
if not 6 in nums:
return False
else:
if nums[0] == 6 or nums[-1] == 6:
return True
else:
return False
def same_first_last(nums):
if nums != [] and nums[0] == nums[-1]:
retorno = True
else:
retorno = False
return retorno
def c... | StarcoderdataPython |
11292756 | <gh_stars>0
def sfl(L):
""" (list) -> bool
Precondition: len(L) >= 2
Return True if and only if first item of the list is same as last.
>>> sfl([3, 4, 2, 8, 3])
True
>>> sfl([a, b, c])
False
"""
return (L[0] == L[-1])
def is_longer(L1, L2):
""" (list, list) -> bool
Retu... | StarcoderdataPython |
5163745 | <filename>Community/lease_history_ip/lease_history_ip_access.py
# Copyright 2019 BlueCat Networks (USA) Inc. and its affiliates
# -*- 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 Li... | StarcoderdataPython |
11308093 | import rasa.nlu.training_data.entities_parser
import rasa.nlu.training_data.synonyms_parser
import rasa.nlu.training_data.lookup_tables_parser
from rasa.nlu.training_data.loading import load_data
from rasa.nlu.training_data.message import Message
from rasa.nlu.training_data.training_data import TrainingData
| StarcoderdataPython |
3284680 | # Tencent is pleased to support the open source community by making PocketFlow available.
#
# Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | StarcoderdataPython |
11266431 | # Copyright (c) 2019 fortiss GmbH
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# ffmpeg must be installed
from modules.runtime.scenario.scenario_generation.drone_challenge import DroneChallengeScenarioGeneration
from modules.runtime.commons.parameters import ParameterSer... | StarcoderdataPython |
3549904 | from ..factory import Type
class checkChatUsernameResultPublicChatsTooMuch(Type):
pass
| StarcoderdataPython |
199185 | <reponame>bmwant/podmena<filename>podmena/parser.py<gh_stars>10-100
import re
class RegexParser(object):
def __init__(self):
self.pattern = re.compile(
r'<span .+></span>:<span .+>([\w_]+)</span>:</div>')
def parse(self, text):
return self.pattern.findall(text)
| StarcoderdataPython |
9644701 | <filename>py_to_win_app/py_to_win_app.py
import os
import re
import shutil
import subprocess
import sys
import zipfile
from contextlib import contextmanager
from pathlib import Path
from typing import Iterable, Union
import requests
from genexe.generate_exe import generate_exe
__all__ = ["Project"]
_PYTHON_VERSION_R... | StarcoderdataPython |
6540446 | <filename>src/node/ext/ldap/tests/test_ugm_principals.py<gh_stars>1-10
# -*- coding: utf-8 -*-
from node.base import BaseNode
from node.ext.ldap import LDAPNode
from node.ext.ldap import ONELEVEL
from node.ext.ldap import testing
from node.ext.ldap.filter import LDAPFilter
from node.ext.ldap.ugm import Group
from node.... | StarcoderdataPython |
159265 | <reponame>isb-cgc/ISB-CGC-Webapp
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('projects', '0001_initial'),
migrations.swappable_dependency(setting... | StarcoderdataPython |
3280510 | """Compare the speed of exact one-norm calculation vs. its estimation.
"""
from __future__ import division, print_function, absolute_import
import time
import numpy as np
import scipy.sparse.linalg
class BenchmarkOneNormEst(object):
params = [
[2, 3, 5, 10, 30, 100, 300, 500, 1000],
['exact', '... | StarcoderdataPython |
11281652 | <reponame>ehsankorhani/python-lessons<filename>27-advanced-oop/soild-srp.py
# class Car:
# def __init__(self, speed: float, odometer: int):
# self.speed = speed
# self.odometer = odometer
# def accelerate(self):
# return self.speed * 1.1
# def save_current_odometer(self):
# p... | StarcoderdataPython |
4815678 | #!/usr/bin/env python
# just testing basic parallelization that will be used in the actual project
from __future__ import division,unicode_literals
from future.builtins import map,zip, range
import numpy as np
import itertools as it
# setup proper logging
import logging
logger = logging.getLogger('psnobfit')
logger.se... | StarcoderdataPython |
1617415 | import urllib
import urllib2
import socket
import os.path
if os.path.exists('/home/pi/probereqs.log'):
with open('/home/pi/probereqs.log') as f:
probedata = f.read()
url = '_API_URL'
values = { 'device': socket.gethostname(), 'data': probedata }
data = urllib.urlencode(values)
req = urll... | StarcoderdataPython |
6683759 | <filename>patchMap_predict.py
import numpy as np
import cv2
from keras.models import load_model
import scipy.io as sio
base_path_hazyImg = 'image/'
base_path_result = 'patchMap/'
imgname = 'waterfall.tif'
modelDir = 'PMS-Net.h5'
print ("Process image: ", imgname)
hazy_sample = cv2.imread(b... | StarcoderdataPython |
1920202 | __author__ = '<NAME>'
__author_email__ = '<EMAIL>'
from datetime import datetime, timedelta
import json
from pytz import timezone
with open('./config.json', 'r') as file:
conf = json.loads(file.read())
TIMEZONE = str(conf['timezone'])
class notifyOwnerToSetSchedule():
"""
Class that contains all logic to... | StarcoderdataPython |
3283108 | """
Common database model definitions.
These models are 'generic' and do not fit a particular business logic object.
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext as _
from django.core.validators import MinValueValidator,... | StarcoderdataPython |
357128 | <filename>auction/bid/models.py
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from auction.bid.managers import AuctionManager, BidManager
import pendulum
class AuctionItem(models.Model):
name = models.CharField(max_length=255)
description = models.TextField... | StarcoderdataPython |
152027 | <gh_stars>10-100
from textgenrnn import textgenrnn
textgen = textgenrnn(name="my.poem") # 给模型起个名字,比如`poem`, 之后生成的模型文件都会以这个名字为前缀
textgen.reset() # 重置模型
textgen.train_from_file( # 从数据文件训练模型
file_path = '../datasets/cn/5_chars... | StarcoderdataPython |
9783249 | import http.client
import requests
import random
import string
import threading
import time
import ssl
from bs4 import BeautifulSoup
from datetime import datetime
withdraw = True
getLoggedinAddress = True
withdrawCompletely = False
unregisteredLogin = False
def getSession():
length_of_string = 40
letters_and... | StarcoderdataPython |
9745071 | <gh_stars>0
"""
<NAME>
Wed Mar 25 19:23:07 2020
Python 2 - DAT-129 - Spring 2020
Lecture Notes
"""
#PLAN
import urllib
from bs4 import BeautifulSoup
def getSearchURL(term, number):
# assembles a query against goodreads.com give a search term
#url = 'https://www.goodreads.com/search?query=%s' % (str(te... | StarcoderdataPython |
386798 | <gh_stars>100-1000
"""NVR that setups all components for a camera."""
from __future__ import annotations
import logging
from queue import Empty, Queue
from threading import Thread
from typing import TYPE_CHECKING, Dict, List, Union
import cv2
import viseron.mqtt
from viseron import helpers
from viseron.camera import... | StarcoderdataPython |
3329589 | <filename>podcast/admin.py
from django.contrib import admin
# Register your models here.
from .models import Podcast, Category, Series, Advertisement
admin.site.register(Podcast)
admin.site.register(Category)
admin.site.register(Series)
admin.site.register(Advertisement)
| StarcoderdataPython |
3254583 | import argparse
import datetime
import logging
import multiprocessing
import os
import sys
from multicrypto.ellipticcurve import secp256k1
from multicrypto.address import convert_public_key_to_address, convert_private_key_to_wif_format, \
validate_pattern
from multicrypto.coins import coins
from multicrypto.scrip... | StarcoderdataPython |
1629399 | from itertools import product
from typing import Dict
import pandas as pd
from tpcp import HyperParameter, OptimizableParameter, PureParameter, cf, make_optimize_safe
from tpcp._dataset import Dataset
from tpcp._pipeline import OptimizablePipeline, Pipeline
class DummyPipeline(Pipeline):
def __init__(self, para... | StarcoderdataPython |
1879064 | #!/usr/bin/env python
'''
Contains all file-reading code and mapping code to generate results used for HRI17 and RSS17 papers.
'''
import sys
import os
import time
sys.path.append('../src')
from entity import Entity
from mapper import *
from file_io import *
from object_defs import *
if __name__ == "__main__":
# ... | StarcoderdataPython |
5095826 | <gh_stars>1-10
import os
import csv
import shutil
import pathlib
from urllib.request import urlopen
from io import BytesIO
from zipfile import ZipFile, BadZipFile
from django.db import transaction
from django.core.management import BaseCommand
from django.contrib.gis.utils import LayerMapping
import districts
from di... | StarcoderdataPython |
1889321 | #!/usr/bin/env python3
# File : atbash.py
# Author : <NAME>
# Email : <EMAIL>
# Created Time : 2021/10/8 23:29
# Description :
def atbash_encode(plaintext):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphabet_map = alphabet[::-1] + alphabet.lower()[::-1]
alphabet += alphabet.lower()... | StarcoderdataPython |
6679699 | <reponame>NeolithEra/afg
from .scenarios import Supervisor
| StarcoderdataPython |
101517 | """
LRGAN
-----
Implements the latent regressor GAN well described in the BicycleGAN paper[1].
It introduces an encoder network which maps the generator output back to the latent
input space. This should help to prevent mode collapse and improve image variety.
Losses:
- Generator: Binary cross-entropy + L1-latent... | StarcoderdataPython |
6633415 | <gh_stars>1-10
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from functools import partial
import cv2
from utils.dataset import parse_fn
from utils.losses import generator_loss, discriminator_loss, gradient_penalty
from utils.models import Generator, Discriminator
import os
os.environ["... | StarcoderdataPython |
3343999 | <reponame>RohanDalton/sygaldry
import os
__author__ = "<NAME>"
class EnvironmentSingleton(type):
_instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(EnvironmentSingleton, cls).__call__(*args, **kwargs)
else:
pass
... | StarcoderdataPython |
5000697 |
from pyvisdk.esxcli.executer import execute_soap
from pyvisdk.esxcli.base import Base
class FcoeNic(Base):
'''
Operations that can be performed on FCOE-capable CNA devices
'''
moid = 'ha-cli-handler-fcoe-nic'
def disable(self, nicname):
'''
Disable rediscovery of FCOE storage on be... | StarcoderdataPython |
4854571 | <gh_stars>0
from elasticsearch_dsl import analyzer, Date, Document, Index, Text, Integer, Keyword, Double
class Listing(Document):
id = Integer()
listing_url = Text()
scrape_id = Integer()
last_scraped = Keyword()
crawled_date = Date()
name = Text(analyzer='snowball')
host_id = Integer()
... | StarcoderdataPython |
1852024 | <filename>server/intrinsic/management/commands/intrinsic_update_citations.py
from django.core.management.base import BaseCommand
from common.models import PaperCitation
from intrinsic.models import IntrinsicImagesAlgorithm
class Command(BaseCommand):
args = ''
help = 'Fix intrinsic images citations'
def... | StarcoderdataPython |
5152503 | <reponame>MessireToaster/CoEvolution
#!/usr/bin/env python
"""
Make plots out of dictionaries of test results, loaded from pickled files.
"""
import pickle
import re
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# path to pickled results
paths = ["../Results/FinalResults.pickle"]
bins = r... | StarcoderdataPython |
85603 | import logging
__version__ = "2.0.6"
logging.getLogger(__name__).addHandler(logging.NullHandler())
| StarcoderdataPython |
279567 | # The main script
from downloadsprites import downloadSprites
from compresssprites import compressMain
downloadSprites()
compressMain()
| StarcoderdataPython |
3408468 | <reponame>nestor-san/cooperation-fit
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
from django.conf import settings
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **... | StarcoderdataPython |
161812 | <filename>train_ae.py<gh_stars>1-10
import torch
import chess
import fire
from random import random, uniform
from utils import create_path
from torch.nn import functional as F
from models.role.ae import AE
from models.random_player import RandomPlayer
from pathlib import Path
from utils.features import board_to_feat
f... | StarcoderdataPython |
9601978 | default_app_config = 'kungfucms.apps.dashboard.apps.DashboardConfig'
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.