id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
4833005 | # 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 or agreed to in writi... | StarcoderdataPython |
4804213 |
from collections import defaultdict
from random import sample, seed
import scrapy
import re
from datetime import datetime
from nature_news_scraper.spiders import article_crawl
class NewsSpider(scrapy.Spider):
name = "doi_crawl"
def start_requests(self):
year = int(self.target_year)
type_arti... | StarcoderdataPython |
3661 | <reponame>meysam81/sheypoor
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app import api
from app.core.config import config
app = FastAPI(title="Sheypoor")
# Set all CORS enabled origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,... | StarcoderdataPython |
1783262 | <gh_stars>0
from LinkedList import LinkedList, Node
def naiveFillSmallLinkedList(val, nodeList, node):
if node is None:
node = Node(val)
nodeList.head = node
else:
temp = Node(val)
node.next = temp
node = node.next
return node, nodeList
def naivePartition(ll, x):
... | StarcoderdataPython |
19877 | <gh_stars>0
import png
import numpy
import pprint
import math
import re
def gen_background(width, height, mag, b_col):
bg = numpy.zeros((width * mag, height * mag, 4), dtype=numpy.uint8)
for y in range(0, height * mag, mag):
for x in range(0, width * mag):
bg[y][x] = b_col
for... | StarcoderdataPython |
182911 | from pudzu.charts import *
from pudzu.dates import *
import dateparser
# -------------
# G7 time chart
# -------------
START = dateparser.parse('1 January 1960').date()
END = datetime.date.today()
def duration(d):
return dateparser.parse(get_non(d, 'end', END.isoformat())).date() - max(START, datepar... | StarcoderdataPython |
1682108 | <filename>asynchronous_qiwi/call/API/QIWIWallet/balance_api/create_balance.py
from loguru import logger
from aiohttp import ClientError
from .....data.URL import QIWIWalletURLS
from .....connector.aiohttp_connector import Connector
from .....data_types.connector.request_type import POST
class CreateBalanceAPI:
@... | StarcoderdataPython |
3231792 | <reponame>jonathanvevance/predicting_fgroups_ddp<filename>src/utils/train_utils.py
"""MIL functions."""
import torch
import torch.nn as nn
from sklearn.metrics import precision_recall_fscore_support
from tqdm import tqdm
class weightedLoss(nn.Module):
def __init__(self, torch_loss, weight, device):
"""
... | StarcoderdataPython |
4821759 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_plugins_file', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='file... | StarcoderdataPython |
6428 | import os
import math
import time
import geohash
import geojson
from geojson import MultiLineString
from shapely import geometry
import shapefile
import numpy
import datetime as dt
import pandas as pd
import logging
logger = logging.getLogger(__name__)
source_shape_file_path = "C:/temp/2018/"
threshold = 60*60
cols = ... | StarcoderdataPython |
3202532 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from rest_framework_tus.views import UploadViewSet
from .routers import TusAPIRouter
router = TusAPIRouter()
router.register(r'files', UploadViewSet, basename='upload')
urlpatterns = [
url(r'', include((router.urls, 'rest_framework_... | StarcoderdataPython |
80941 | # coding: utf-8
"""
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://www.apache.org/licenses/LICENSE-2.0
or in ... | StarcoderdataPython |
3247240 | import glob
import os
import shutil
from subprocess import check_call
import sys
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
ROOT_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))
STANDALONE_DIR = os.path.join(ROOT_DIR, "standalone-build")
PROJECT_NAME = "VTK"
def get_dummy_python_lib():
"""Since... | StarcoderdataPython |
4815028 | <gh_stars>1-10
#!/usr/bin/python
# coding=UTF-8
# -*- coding: UTF-8 -*-
#input file of folder of fasta files
#Uses BLAST to search for homologous PDB structures
# This file is part of asa_uta.py.
#
# asa_uta is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Publ... | StarcoderdataPython |
62698 | from nltk.corpus import stopwords
stop_words = set(stopwords.words("indonesian"))
print(stop_words)
| StarcoderdataPython |
3347771 | #! /usr/bin/env python
"""
This script allows for the search of Sentinel-1 data on scihub.
Based on some search parameters the script will create a query on
www.scihub.copernicus.eu and return the results either as shapefile,
sqlite, or PostGreSQL database.
"""
# import modules
import getpass
import os
import logging... | StarcoderdataPython |
15471 | <gh_stars>1-10
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import object
__copyright__ = "Copyright 2015 Contributing Entities"
__license__ = """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in ... | StarcoderdataPython |
1734089 | import logging
import logging.config
import os
from src import const
class Log:
def debug2(self, msg, *args, **kwargs):
"""Log with severity 'DEBUG2'."""
self.log.log(const.LogLevel.DEBUG2, msg, *args, **kwargs)
def debug3(self, msg, *args, **kwargs):
"""Log with severity 'DEBUG3'.""... | StarcoderdataPython |
67233 | <filename>Libraries/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydicom-0.9.8-py2.7.egg/dicom/test/test_charset.py
# -*- coding: latin_1 -*-
# test_charset.py
"""unittest cases for dicom.charset module"""
# Copyright (c) 2008 <NAME>
# This file is part of pydicom, released under a modified MIT license.
# ... | StarcoderdataPython |
27737 | #!/usr/bin/env python
import sys
sys.path.insert(1, "..")
from SOAPpy.Errors import Error
from SOAPpy.Parser import parseSOAPRPC
original = """<?xml version="1.0"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:... | StarcoderdataPython |
73707 | <reponame>facebookresearch/worldsheet<filename>mmf/neural_rendering/metrics/perc_sim.py<gh_stars>10-100
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. All rights ... | StarcoderdataPython |
3243701 | """
Object that can read/write meteostations metadata and extract related
measurements
"""
from pyowm.commons.http_client import HttpClient
from pyowm.stationsapi30.station_parser import StationParser
from pyowm.stationsapi30.aggregated_measurement_parser import AggregatedMeasurementParser
from pyowm.constants import ... | StarcoderdataPython |
176645 | <filename>yggdrasil/tests/scripts/python_model.py
from yggdrasil.tools import sleep
sleep(1)
print('Python model')
| StarcoderdataPython |
3364152 | from setuptools import setup, find_packages
# Install with 'pip install -e .'
setup(
name="xomx",
version="0.1.0",
author="<NAME>",
description="xomx: a python library for computational omics",
url="https://github.com/perrin-isir/xomx",
packages=find_packages(),
install_requires=[
... | StarcoderdataPython |
84859 | <reponame>Skyross/eventsourcing
from unittest import TestCase
from eventsourcing.utils import retry
class TestRetryDecorator(TestCase):
def test_bare(self):
@retry
def f():
pass
f()
def test_no_args(self):
@retry()
def f():
pass
f()
... | StarcoderdataPython |
120892 | <filename>tests/fl_simulation/server/test_malicious_activity_prevention.py
from fl_simulation.client.update import ModelUpdate
from fl_simulation.server.aggregation import DistanceBasedModelAssigner
import pytest
import torch
from fl_simulation.server.update import AggregatedUpdate
from fl_simulation.utils.types impor... | StarcoderdataPython |
188047 | <filename>cfgov/regulations3k/tests/test_hooks.py
from __future__ import unicode_literals
from django.test import TestCase
from wagtail.tests.utils import WagtailTestUtils
class TestRegs3kHooks(TestCase, WagtailTestUtils):
def setUp(self):
self.login()
def test_part_model_admin(self):
resp... | StarcoderdataPython |
1780236 | <reponame>rescapes/rescape-python-helpers
from django.contrib.gis.geos import GEOSGeometry, GeometryCollection
from snapshottest import TestCase
from .geometry_helpers import ewkt_from_feature_collection
from rescape_python_helpers import ewkt_from_feature, geometry_from_feature, geometrycollection_from_feature_collec... | StarcoderdataPython |
61837 | <reponame>Southampton-Maritime-Robotics/autonomous-sailing-robot<gh_stars>1-10
"""
Set of test functions
so BeagleBone specific GPIO
functions can be tested
For obvious reasons these values
are ONLY for testing!
TODO:
Expand to use test values instead of set values
"""
def begin():
print("WARNING, not using actu... | StarcoderdataPython |
3371324 | """
Given an array and a number k
Find the max elements of each of its sub-arrays of length k.
Keep indexes of good candidates in deque d.
The indexes in d are from the current window, they're increasing,
and their corresponding nums are decreasing.
Then the first deque element is the index of the largest window value... | StarcoderdataPython |
3292300 | <reponame>CrazyDi/Python1
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(1024)
message = data.decode()
addr = writer.get_extra_info("peername")
print("received %r from %r" % (message, addr))
# writer.close()
if __name__ == "__main__":
loop = asyncio.new_event_l... | StarcoderdataPython |
3230200 | <reponame>qychen13/ClusterAlignReID<filename>utils/construct_engine.py
import time
import os
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
from .engine import Engine
from .evaluation import test
from .center import calculate_id_features, update_id_features
def construct_engine(... | StarcoderdataPython |
187872 | <reponame>pddg/qkouserver
import os
from typing import List, Union
from ast import literal_eval
# dir name or file path
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
PRJ_DIR = os.path.dirname(BASE_DIR)
SQLITE_DIR_PATH = os.getenv("SQLITE_PATH", BASE_DIR)
SQLITE_PATH = "sqlite:///{path}".format(path=os.path.joi... | StarcoderdataPython |
65849 | # Not picklable!
import os # noqa
| StarcoderdataPython |
4834431 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 19:55:42 2020
@author: Dell
"""
import ifaddr
from lifxlan import LifxLAN, group, device, light
foco2=light.Light("D0:73:D5:5E:25:BD","192.168.0.3")
foco1=light.Light("D0:73:D5:5C:A7:DB","192.168.0.9")
foco = LifxLAN()
#foco.set_power_all_lights("on", rapid = False)
de... | StarcoderdataPython |
1658006 | import pytest
from hypothesis import given
from strategies import atlas_results_metas
from fetchmesh.atlas import AtlasAnchor, Country
from fetchmesh.filters import (
AnchorRegionFilter,
HalfPairFilter,
PairRegionSampler,
PairSampler,
SelfPairFilter,
)
def test_anchor_region_filter():
anchors... | StarcoderdataPython |
1696668 | <reponame>e5120/EDAs<gh_stars>1-10
import os
import csv
import json
import logging
import datetime
from collections import OrderedDict
from types import MappingProxyType
import numpy as np
logging.basicConfig(level=logging.INFO,
format="[%(asctime)s %(levelname)s] %(message)s")
class Logger(obje... | StarcoderdataPython |
3381362 | <filename>a2c_ppo_acktr/algo/ppo.py
import torch
import torch.nn as nn
import torch.optim as optim
from a2c_ppo_acktr.algo.sog import BlockCoordinateSearch, OneHotSearch
class PPO:
def __init__(self,
actor_critic,
args,
lr=None,
eps=None,
... | StarcoderdataPython |
3328299 | """
Traffic/VPN subparser package.
"""
import api_parser._traffic.subparsers as sps
def create_traffic_subparser(subparsers):
"""
Creates the _traffic subparser.
Args:
subparsers: Subparser object from argparse obtined from calling ArgumentParser.add_subparsers().
"""
p = subparsers.add_p... | StarcoderdataPython |
3240690 | from flask import request
import time
import threading
from libs import ddbb
from hashlib import md5
import json
limiter = {}
llimiter = threading.Lock()
count_limit = 5
def get_ip():
proxy = request.headers.get('X-Real-Ip')
real = request.remote_addr
if proxy != None and real == ddbb.settings.proxy:
... | StarcoderdataPython |
1636092 | <filename>ersilia/hub/content/card.py<gh_stars>10-100
import os
import json
import collections
import tempfile
import requests
from pyairtable import Table
from ... import ErsiliaBase
from ...utils.terminal import run_command
from ...auth.auth import Auth
from ...default import (
AIRTABLE_READONLY_API_KEY,
AIR... | StarcoderdataPython |
1678287 | # coding=utf-8
"""API to most common queries to the dataset."""
import collections
import os
import sqlite3
from typing import AnyStr
import tqdm
def main():
db_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '../data/dataset/evalution2.db'))
# use verbose=1 for debugging.
db = EvaldDB(d... | StarcoderdataPython |
3233640 | <filename>app.py
import dash
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.FLATLY])
app.title = 'Crypto Dollar Cost Calculator'
server = app.server
app.config.suppress_callback_exceptions ... | StarcoderdataPython |
197998 | from trp.t_pipeline import add_page_orientation, order_blocks_by_geo
from typing import List
from trp.t_pipeline import add_page_orientation, order_blocks_by_geo, pipeline_merge_tables, add_kv_ocr_confidence
from trp.t_tables import MergeOptions, HeaderFooterType
import trp.trp2 as t2
import trp as t1
import json
impor... | StarcoderdataPython |
3236515 | <reponame>ciandt/tech-gallery-chat-bot<filename>tests/test_dependencies.py<gh_stars>1-10
from unittest import mock
from unittest.mock import ANY
import pytest
from tech_gallery_bot.dependencies import get_dependencies
from tech_gallery_bot.repositories import UserRepository, UserProfileRepository
@pytest.mark.param... | StarcoderdataPython |
3357016 | from signal import siginterrupt
from tkinter.tix import REAL
Algoritmo: Descuento:
#Para este ejercicio tenemos que crear un algoritmo para calcular el descuento de una compra
#teniendo en cuenta que se aplicará un descuento de un 5 % a compras valoradas entre 100 y 500 euros y de un 8% para compras valoradas en más ... | StarcoderdataPython |
125609 | <gh_stars>0
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------... | StarcoderdataPython |
3276820 | <gh_stars>0
import os
from app.lookups import base as lookups
from app.drivers.base import BaseDriver
from app.drivers.options import mslookup_options
class LookupDriver(BaseDriver):
outfile, outdir = None, None
def __init__(self):
super().__init__()
self.parser_options = mslookup_options
... | StarcoderdataPython |
4835874 |
import matplotlib
matplotlib.use('Agg')
import os
import pandas as pd
import numpy as np
import sys
import pickle
from scipy.spatial.distance import cdist
import math
import networkx as nx
import networkx.algorithms.components.connected as nxacc
import networkx.algorithms.dag as nxadag
import matplotlib.pyplot as plt... | StarcoderdataPython |
147201 | """
BlackHole.py
Author: <NAME>
Affiliation: University of Colorado at Boulder
Created on: Mon Jul 8 09:56:38 MDT 2013
Description:
"""
import numpy as np
from .Star import _Planck
from .Source import Source
from types import FunctionType
from scipy.integrate import quad
from ..util.ReadData import read_lit
from... | StarcoderdataPython |
182089 | <reponame>coogger/coogger<filename>apps/cooggerapp/models/userextra.py
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext as _
from apps.cooggerapp.choices import FOLLOW, TITLES, make_choices
class OtherAddressesOfUsers(models.Model):
"maybe Many... | StarcoderdataPython |
1692338 | <filename>python/batch-compute-with-step-functions/workshop/construct/cicdpipeline/cicd_web.py<gh_stars>0
from aws_cdk import (
core,
aws_iam as _iam,
aws_codepipeline as _codepipeline,
aws_codepipeline_actions as _codepipeline_actions,
aws_codecommit as _codecommit,
aws_codebuild as _codebuild
... | StarcoderdataPython |
30074 | <reponame>mariocesar/boot.py<filename>setup.py
#!/usr/bin/env python3
import sys
from setuptools import find_packages, setup
if sys.version_info < (3, 6):
sys.exit('Python 3.6 is the minimum required version')
description, long_description = (
open('README.rst', 'rt').read().split('\n\n', 1))
setup(
nam... | StarcoderdataPython |
193455 | <gh_stars>1-10
#
# Copyright (c) 2014-2015 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import logging
from django.urls import reverse # noqa
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from starlingx_dashboa... | StarcoderdataPython |
3216177 | # -*- coding:utf-8 -*-
import copy
import json
import logging
import os
import sys
from io import open
logger = logging.getLogger(__name__)
CONFIG_NAME = "config.json"
class PretrainedConfig(object):
pretrained_config_archive_map = {}
def __init__(self, **kwargs):
pass
def s... | StarcoderdataPython |
1782012 | <filename>py/invoke/gen-py/map_service/MapService.py<gh_stars>0
#
# Autogenerated by Thrift Compiler (0.10.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol... | StarcoderdataPython |
1795423 | <filename>xcv/WIP/hud.py
"""This is for drawing game/debug info on the OpenCV output frame.
See gui.py for displaying information within the GUI Window.
"""
from collections import namedtuple
import cv2
# ========================================
# Color Stuff
Color = namedtuple('Color', ['r', 'g', 'b'])
GREEN = Colo... | StarcoderdataPython |
1757664 | #!/usr/bin/env python
# Standard Python libraries.
# Third party Python libraries.
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Custom Python libraries.
from . import logger
# Disable warning: "InsecureRequestWarning: Unverified HTTPS request is being made.
# Adding cer... | StarcoderdataPython |
15908 | r"""
This is the base module for all other objects of the package.
+ `LaTeX` returns a LaTeX string out of an `Irene` object.
+ `base` is the parent of all `Irene` objects.
"""
def LaTeX(obj):
r"""
Returns LaTeX representation of Irene's objects.
"""
from sympy.core.core import all_classes
... | StarcoderdataPython |
3379252 | <gh_stars>0
import unittest
from models import Newssources
class SourcesTest(unittest.TestCase):
'''
test class to test behaviour of news article class
'''
def setUp(self):
'''
set up method that will rub
before every test
'''
self.new_source = Newssource('The ... | StarcoderdataPython |
132119 | <filename>holoviews/plotting/mpl/graphs.py<gh_stars>0
import param
import numpy as np
from matplotlib.collections import LineCollection, PolyCollection
from ...core.data import Dataset
from ...core.options import Cycle
from ...core.util import basestring, unique_array, search_indices, max_range
from ..util import pro... | StarcoderdataPython |
1681897 | import os
import json
import six
from girder.models.collection import Collection
from girder.models.folder import Folder
from girder.models.item import Item
from girder.models.upload import Upload
from girder.models.user import User
from tests import base
def setUpModule():
base.enabledPlugins.append('dicom_view... | StarcoderdataPython |
3207184 | <reponame>bhatiadivij/kgtk<filename>examples/obtain_stats.py
import kgtk.gt.io_utils as gtio
import kgtk.gt.analysis_utils as gtanalysis
datadir='data/'
mowgli_nodes=f'{datadir}nodes_v002.csv'
mowgli_edges=f'{datadir}edges_v002.csv'
output_gml=f'{datadir}graph.graphml'
g=gtio.load_gt_graph(output_gml.replace(".graphm... | StarcoderdataPython |
40576 | from django.http import HttpResponseRedirect
from thedaily.models import OAuthState
from thedaily.views import get_or_create_user_profile
def get_phone_number(backend, uid, user=None, social=None, *args, **kwargs):
subscriber = get_or_create_user_profile(user)
if not subscriber.phone:
state = kwargs[... | StarcoderdataPython |
1633821 | from typing import Optional
from .package_metadata import \
DamlModelInfo, \
IntegrationTypeFieldInfo, \
IntegrationTypeInfo, \
CatalogInfo, \
PackageMetadata, \
DABL_META_NAME, \
DIT_META_NAME, \
DIT_META_NAMES, \
DIT_META_KEY_NAME, \
TAG_EXPERIMENTAL, \
normalize_catalog,... | StarcoderdataPython |
162011 | from __future__ import print_function
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from startup_dialog_ui import Ui_startupDialog
from colorimeter import constants
from colorimeter.gui.basic import startBasicMainWindow
from colorimeter.gui.plot import startPlotMainWindow
from colorimeter.gui.measure impo... | StarcoderdataPython |
1729247 | # Generated by Django 3.0.8 on 2020-09-03 00:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
... | StarcoderdataPython |
1796721 | """
Your chance to explore Loops and Turtles!
Authors: <NAME>, <NAME>, <NAME>, <NAME>,
their colleagues and <NAME>.
"""
###############################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
#############################... | StarcoderdataPython |
89379 | <gh_stars>0
"""Provides a facade-like interface for easy access to ``tesliper``'s functionality.
There are some conventions that are important to note:
- ``tesliper`` stores multiple data entries of various types for each conformer. To
prevent confusion with Python's data ``type`` and with data itself, ``tesliper``... | StarcoderdataPython |
11534 | <reponame>hehaoqian/romt<filename>src/romt/manifest.py
#!/usr/bin/env python3
# coding=utf-8
import copy
from pathlib import Path
from typing import (
Any,
Generator,
Iterable,
List,
MutableMapping,
Optional,
)
import toml
from romt import error
def target_matches_any(target: str, expected_... | StarcoderdataPython |
152764 | ####
# This sample uses the PyPDF2 library for combining pdfs together to get the full pdf for all the views in a
# workbook.
#
# You will need to do `pip install PyPDF2` to use this sample.
#
# To run the script, you must have installed Python 3.5 or later.
####
import argparse
import getpass
import logging
import t... | StarcoderdataPython |
190375 | <filename>paprika/threads/SecondTimer.py
import threading
class SecondTimer(object):
def __init__(self, seconds):
object.__init__(self)
self.__executors = []
self.__seconds = seconds
self.__elapsed = 0
def get_elapsed(self):
return self.__elapsed
def set_elapsed(s... | StarcoderdataPython |
1677592 | """A RedirectionProvider Service Provider."""
from config import session
from masonite.drivers import SessionCookieDriver, SessionMemoryDriver
from masonite.managers import SessionManager
from masonite.provider import ServiceProvider
from masonite.view import View
from masonite.request import Request
from masonite imp... | StarcoderdataPython |
91706 | <reponame>desafinadude/municipal-data
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-10-06 17:45
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migratio... | StarcoderdataPython |
3204285 | from argparse import Namespace
from src.learner import Learner
args = Namespace(
# Data and Path information
surname_csv="data/surnames/surnames_with_splits.csv",
vectorizer_file="vectorizer.json",
model_state_file="model.pth",
save_dir="model_storage/ch4/cnn",
# Model hyper parameters
hid... | StarcoderdataPython |
161639 | <gh_stars>1-10
from PIL import Image
from cStringIO import StringIO
def inline(image, size):
tmp = Image.new('RGB', (size, size), None)
buf = tmp.load()
for v in xrange(size):
for u in xrange(size):
buf[u, v] = next(image)
out = StringIO()
tmp.save(out, 'PNG')
result = out... | StarcoderdataPython |
3205393 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from .building_type import BuildingType
class ProfitableBuilding(BuildingType):
""" A Massilian building that generates income for the state. """
building_income = models.DecimalField(_('Income'), max_digits=4, decimal_place... | StarcoderdataPython |
1731124 | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import SlickGalleryPlugin
from django.utils.translation import ugettext as _
class SlickGalleryPluginBase(CMSPluginBase):
name = _('Slick gallery')
model = SlickGalleryPlugin
render_template = "cmsplugin_slick_... | StarcoderdataPython |
21898 | <filename>scripts/pa-loaddata.py<gh_stars>0
#! /usr/bin/python
import argparse
import os
from biokbase.probabilistic_annotation.DataParser import DataParser
from biokbase.probabilistic_annotation.Helpers import get_config
from biokbase import log
desc1 = '''
NAME
pa-loaddata -- load static database of gene anno... | StarcoderdataPython |
1660157 | <filename>tests/epyccel/modules/types.py
# pylint: disable=missing-function-docstring, missing-module-docstring/
def test_int_default(x : 'int'):
return x
def test_int64(x : 'int64'):
return x
def test_int32(x : 'int32'):
return x
def test_int16(x : 'int16'):
return x
def test_int8(x ... | StarcoderdataPython |
3221233 | <gh_stars>1-10
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
def show_graph(g) :
nx.draw(g,with_labels=True, font_weight='bold')
plt.show()
U=nx.Graph()
U.add_edge("a","b")
U.add_edge("b","c")
U.add_edge("a","c")
D=nx.DiGraph()
D.add_edge("a","b")
D.add_edge("b","c")
D.add_edge("a","c... | StarcoderdataPython |
3297868 | from elasticsearch import Elasticsearch
import os
import zipfile
import shutil
import urllib.request
import logging
import lzma
import json
import tarfile
import hashlib
logger = logging.getLogger(__name__)
# index settings with analyzer to automatically remove stop words
index_settings = {
"settings": {
... | StarcoderdataPython |
3325010 | # Python Program to find Largest of Two Numbers
a = float(input(" Please Enter the First number : "))
b = float(input(" Please Enter the Second number : "))
if(a > b):
print('first number is lergest ')
elif(b > a):
print('second number is lergest')
else:
print("Both are Equal") | StarcoderdataPython |
3330449 |
import json
import itertools
from os import environ, path, makedirs
import logging
import logging.config
from dotenv import load_dotenv
load_dotenv()
# pipenv run python generate_dqm_json_test_set.py
# Take large dqm json data and generate a smaller subset to test with, with data from beginning, middle, and end o... | StarcoderdataPython |
37453 | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... | StarcoderdataPython |
17925 | <gh_stars>0
from nanome._internal._util._serializers import _StringSerializer
from nanome._internal._util._serializers import _TypeSerializer
class _OpenURL(_TypeSerializer):
def __init__(self):
self.string = _StringSerializer()
def version(self):
return 0
def name(self):
return ... | StarcoderdataPython |
3241821 | import logging
from django.contrib.auth.mixins import UserPassesTestMixin
from django.shortcuts import render
logger = logging.getLogger(__name__)
def handler500(request):
return render(request, 'errors/application-error.html', status=500)
def index(request):
return render(request, 'index.html')
class _... | StarcoderdataPython |
3305476 | import numpy
from grunnur import dtypes, Program, Queue, Array
def check_struct_fill(context, dtype):
"""
Fill every field of the given ``dtype`` with its number and check the results.
This helps detect issues with offsets in the struct.
"""
struct = dtypes.ctype_struct(dtype)
program = Prog... | StarcoderdataPython |
4827142 | import time
import joblib
import os
import os.path as osp
import tensorflow as tf
import torch
import gym
from spinup import EpochLogger
from spinup.utils.logx import restore_tf_graph
def load_policy_and_env(fpath, itr='last', deterministic=False):
"""
Load a policy from save, whether it's TF or PyTorch, alon... | StarcoderdataPython |
1651435 | <filename>src/whoosh/util/times.py
# Copyright 2010 <NAME>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# t... | StarcoderdataPython |
73995 | <gh_stars>0
def do_stuff(fn, lhs, rhs):
return fn(lhs, rhs)
def add(lhs, rhs):
return lhs + rhs
def multiply(lhs, rhs):
return lhs * rhs
def exponent(lhs, rhs):
return lhs ** rhs
print(do_stuff(add, 2, 3))
print(do_stuff(multiply, 2, 3))
print(do_stuff(exponent, 2, 3))
| StarcoderdataPython |
116695 | from dataset import Dataset
from util import Util
class Feature:
def __init__(self, use_features):
self.dataset = Dataset(use_features)
years = [y for y in range(2008, 2020)]
self.data = self.dataset.get_data(years, "tokyo")
def get_dataset(self):
return self.data.c... | StarcoderdataPython |
3364353 | """
Generate `pyi` from corresponding `rst` docs.
"""
import rst
from class_ import Class
from rst2pyi import RST2PyI
__author__ = rst.__author__
__copyright__ = rst.__copyright__
__license__ = rst.__license__
__version__ = "7.2.0" # Version set by https://github.com/hlovatt/tag2ver
def pyb(shed: RST2PyI) -> None:... | StarcoderdataPython |
1727121 | <filename>src/pose3d_utils/mat4.py
import numpy as np
def identity():
return np.eye(4, dtype=np.float64)
def affine(A=None, t=None):
aff = identity()
if A is not None:
aff[0:3, 0:3] = np.array(A, dtype=aff.dtype)
if t is not None:
aff[0:3, 3] = np.array(t, dtype=aff.dtype)
return... | StarcoderdataPython |
1787340 | <reponame>seanrcollings/arc<gh_stars>1-10
import functools
import io
import re
import sys
import time
from types import MethodType
import typing as t
import os
from arc import logging, typing as at
from arc.color import fg, effects, colorize
logger = logging.getArcLogger("util")
IDENT = r"[a-zA-Z-_0-9]+"
def inde... | StarcoderdataPython |
178145 | <gh_stars>0
import utilities
import database
import model
from discord.ext import commands
import discord
import random
class Management(commands.Cog):
"""Here lie commands for managing guild-specific settings."""
def __init__(self, bot: model.Bakerbot) -> None:
self.bot = bot
async def cog_check... | StarcoderdataPython |
3228662 | <reponame>Cosmo-Tech/cosmotech-api-python-client<filename>test/test_scenariorun_api.py
"""
Cosmo Tech Plaform API
Cosmo Tech Platform API # noqa: E501
The version of the OpenAPI document: 0.0.11-SNAPSHOT
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import unittest
import c... | StarcoderdataPython |
22895 | """
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
import queue
from multiprocessing import Queue, Process
import sys
import os
from mc_memory_nodes import InstSegNode, PropSegNode
from heuristic_perception import all_nearby_objects
from shapes import get_bounds
VISION_DIR = os.path.dirname(os.pa... | StarcoderdataPython |
3311478 | class Parent:
parentattr=100
def __init__(self):
print "Calling Parent Constructer "
def Parentattr(self,attr):
Parent.attr = attr
def Parentmethod(self):
print "Calling Parent Method "
def Getattrr(self):
print "Get Attr= ",parent... | StarcoderdataPython |
1651437 | <reponame>anthon-alindada/sanic_messaging<filename>app/domain/messaging/stores/message_store.py
# -*- coding: utf-8
# Core
from .base_store import BaseStore
# Model
from ..models import Message
class MessageStore(BaseStore):
"""
Message stores
"""
async def create(self, content, author_id, channel_i... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.