id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5194430 | # Functions
# Write a function that converts a floating point number to a string
# with a specific number of digits past the decimal place.
def solution(f, places):
y = f"{f:.{places}f}"
return y
# Write a function that returns true if a number is between 2 and 7, exclusive.
def solution(n):
if n > 2 and... | StarcoderdataPython |
3384223 | """Defines class for json schema version 2019-09."""
# builtin
from datetime import datetime
# package
from .version import SchemaVersion
from ..types import JSONSchema
class JSONSchema2019_09(SchemaVersion):
"""Class representing JSON schema version 2019-09."""
def __init__(self) -> None:
"""See c... | StarcoderdataPython |
6672508 | <filename>ensemble.py
""" Ensemble을 수행하는 코드입니다. """
import json
import os.path as p
from collections import defaultdict
import numpy as np
from tqdm.auto import tqdm
from utils.tools import get_args, update_args
from utils.prepare import get_retriever, get_reader, get_dataset
TOPK = 5
MAX_ANSWER_LENGTH = 30
OFFSET_... | StarcoderdataPython |
1618312 | <gh_stars>10-100
import falcon
def test_get_returns_hello_name(client):
doc = {"message": "Hello, Bob!"}
result = client.simulate_get("/hello/bob")
assert result.status == falcon.HTTP_OK
assert result.json == doc
| StarcoderdataPython |
226240 | <reponame>samysweb/dnnv<filename>dnnv/nn/transformers/simplifiers/squeeze_gemms.py
import numpy as np
from .base import Simplifier
from ... import operations
from ...graph import OperationGraph
class SqueezeGemms(Simplifier):
def visit_Gemm(self, operation: operations.Gemm) -> operations.Gemm:
if isinsta... | StarcoderdataPython |
9745567 | N = int(input())
S = [input() for _ in range(N)]
for i in range(N):
S[i] = ''.join(sorted(S[i]))
t = {}
for i in range(N):
if S[i] in t:
t[S[i]] += 1
else:
t[S[i]] = 1
print(sum(t[k] * (t[k] - 1) // 2 for k in t))
| StarcoderdataPython |
6542222 | <gh_stars>1-10
#imports
import os
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets
from torchvision import transforms, utils
from torchvision.transforms import ToTensor
from torchvision.io import read_image
from torch.utils.data import DataLoader
from PIL... | StarcoderdataPython |
5043148 | <reponame>DsCodeStudio98m0f/DTia-Nugrahab
"""param
Request Parameter
PROJECT: BaoAI Backend
AUTHOR: henry <<EMAIL>>
WEBSITE: http://www.baoai.co
COPYRIGHT: Copyright © 2016-2020 广州源宝网络有限公司 Guangzhou Yuanbao Network Co., Ltd. ( http://www.ybao.org )
LICENSE: Apache-2.0
"""
from flask_marshmallow import base_fields
fro... | StarcoderdataPython |
8032960 | <filename>setup.py
#!/usr/bin/env python3
from setuptools import setup
setup(
name="pub-sub-demo",
version="1.0",
description="",
packages=["pub_sub_demo"],
include_package_data=True,
zip_safe=False,
install_requires=[
'flask',
'gunicorn',
'requests',
'pyjwt... | StarcoderdataPython |
1817595 | <filename>pytket/pytket/routing/__init__.py
# Copyright 2019-2022 Cambridge Quantum Computing
#
# 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.... | StarcoderdataPython |
8166264 | """
Copyright 2015, Cisco Systems, 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 t... | StarcoderdataPython |
6439566 | """
Tests for the cache management code.
"""
import pathlib
import os
import appdirs
import stdpopsim
import tests
class TestSetCacheDir(tests.CacheWritingTest):
"""
Tests the set_cache_dir function.
"""
paths = [
"/somefile", "/some/other/file/", "relative/path", "relative/path/"]
def ... | StarcoderdataPython |
9689285 | # Databricks notebook source
# MAGIC %pip install great-expectations==0.14.4
# COMMAND ----------
dbutils.widgets.text("loadid", "", "Load Id")
loadid = dbutils.widgets.get("loadid")
# COMMAND ----------
import datetime
import os
from pyspark.sql.functions import col, lit
import ddo_transform.transform as t
import ... | StarcoderdataPython |
6459038 | from hubcheck.pageobjects.basepagewidget import BasePageWidget
from hubcheck.pageobjects.basepageelement import TextReadOnly, Link
class PopularItem(BasePageWidget):
def __init__(self, owner, locatordict={}, item_number=0):
# initialize variables
self.__item_number = item_number
super(Po... | StarcoderdataPython |
11309877 | from app.common.model.page import Page
class OrderPage(Page):
def __init__(self, orders, page, size, total_count):
super().__init__(page, size, total_count)
self.orders = orders
| StarcoderdataPython |
3318540 | ######################################################################
#
# File: b2sdk/unfinished_large_file.py
#
# Copyright 2019 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
class UnfinishedLarge... | StarcoderdataPython |
9740328 | <filename>plugin.py
# BTH address presence Python Plugin
#
# Author: Herman
#
# BTH address in de format xx:xx:xx:xx:xx:xx
# changed to bluetooth library. much more responsive
"""
<plugin key="bthpresence" name="Bluetooth address presence" author="heggink" version="0.0.2" externallink="https://github.com/heggink/domot... | StarcoderdataPython |
5002330 | <filename>instructors/projects-2015/workshop_100515/bubble_sort.py
""" Bubble Sort
"""
import random
import time
def compare_two_numbers(a, b):
""" Return the two numbers as a tuple, smallest to largest.
"""
if a > b:
result = (b, a)
else:
# this covers <=
result = (a, b)
... | StarcoderdataPython |
4814575 | <reponame>slp-ntua/slp-labs<filename>lab2/dnn/torch_dataset.py
import os
import kaldi_io
import numpy as np
from torch.utils.data import Dataset
class TorchSpeechDataset(Dataset):
def __init__(self, recipe_dir, ali_dir, dset, feature_context=2):
self.recipe_dir = recipe_dir
self.ali_dir = ali_dir... | StarcoderdataPython |
295193 | <reponame>jasonjoh/kiota<filename>abstractions/python/kiota/abstractions/api_client_builder.py
from .serialization import (
ParseNodeFactory,
ParseNodeFactoryRegistry,
SerializationWriterFactory,
SerializationWriterFactoryRegistry,
SerializationWriterProxyFactory,
)
from .store import BackingStorePa... | StarcoderdataPython |
79934 | """
Project Euler Problem 173: https://projecteuler.net/problem=173
We shall define a square lamina to be a square outline with a square "hole" so that
the shape possesses vertical and horizontal symmetry. For example, using exactly
thirty-two square tiles we can form two different square laminae:
With one-hundred ti... | StarcoderdataPython |
8117142 | #!/usr/bin/env python
''' getbibref.py
Author: <NAME>
Version: 0.2
Small attempt at a program to take a DOI input (unique address for research papers) and
return the Bibtex formatted result from the above website in a copy/pastable form. '''
import urllib.request
from tkinter import *
##This is the ... | StarcoderdataPython |
1704639 | <gh_stars>1-10
import numpy as np
import pandas as pd
from sklearn.inspection import permutation_importance
from sklearn.model_selection import KFold
from art.utils import to_categorical
from sklearn.preprocessing import StandardScaler
import math
import sys
import argparse
import os
from elm_model import ExtremeLearni... | StarcoderdataPython |
1813457 | <reponame>omnihenry/python
#!/usr/bin/python
# title :ssh_handler.py
# description :This script contains the definition of the class
# that encapsulate the functionalities of remote access
# author :<NAME>
# date :20170820
# version :0.1
# usage :to ... | StarcoderdataPython |
243351 | #funzioni di utilita' (gestione cartelle, etc.
import os
# %% utilities
def creaCartella(currentDir,newFolderName):
newDirPath = os.path.join(currentDir, newFolderName)
try:
os.mkdir(newDirPath)
except OSError:
print(f"Cartella {newFolderName} già esistente")
... | StarcoderdataPython |
9665796 |
from math import sqrt
def bracket_block(text):
"""
finds start and end of the first bracketed block
"""
istart=text.find('(')
cursor=istart
if cursor != -1:
counter=1
while (cursor<len(text)) and counter>0:
cursor+=1
if text[cursor]=='(':
counter += 1
elif text[curs... | StarcoderdataPython |
4871237 | import torch
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
class ModelTrainer:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@staticmethod
def train(model, criterion, optimizer, trainloader, epochs=5):
criterion = criterion.to(Model... | StarcoderdataPython |
3491724 | """Tasks deferred outside the request context."""
from .article import clean_articles, crawl_articles, pair_article
| StarcoderdataPython |
3319077 | <filename>ros/geometry/tf/src/tf/broadcaster.py<gh_stars>100-1000
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
... | StarcoderdataPython |
1143 | # -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import os
import tensorflow as tf
'''
gluoncv backbone + multi_gpu
'''
# ------------------------------------------------
VERSION = 'Cascade_FPN_Res50_COCO_1x_20190421_v3'
NET_NAME = 'resnet50_v1d'
ADD_BOX_IN_TENSORBOARD = True
... | StarcoderdataPython |
232095 | import os
from os import path
from exechelper import func_exec_run
localdir = path.join(path.dirname(path.dirname(path.dirname(__file__))), 'storage')
usearch = path.join(path.abspath(path.dirname(__file__)), path.join('bin', 'usearch10.0.240_i86linux32'))
def run_usearch(*args):
cmdargs = ["-" + args[0]]
cmd... | StarcoderdataPython |
8084456 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
def set_parameter_requires_grad(model, feature_extracting, trainable_layers):
if feature_extracting:
for name, param in model.named_parameters():
print(name)
if name not in trainable_layers:
... | StarcoderdataPython |
5041438 | import numpy as np
################################################################################
# #
# Base class for robots #
# - robot has only 3 actions ... | StarcoderdataPython |
6427383 | <filename>src/asm/schedule/tests/test_filter.py<gh_stars>0
import unittest
import asm.schedule.schedule
class ScheduleFilterTests(unittest.TestCase):
def test_filter_all_days_all_categories(self):
asm.schedule.schedule.Schedule()
| StarcoderdataPython |
3474542 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import numpy as np
import scipy.linalg as spl
from ...externals.transforms3d.quaternions import mat2quat, quat2axangle
from .transform import Transform
from ..utils.affines import apply_affine
# Globals
R... | StarcoderdataPython |
4898004 | <filename>uimnet/algorithms/due.py<gh_stars>1-10
#
# # Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved
#
#
import gpytorch
import torch
import numpy as np
from uimnet import utils
from uimnet.algorithms.base import Algorithm
import torchvision
import torch.cuda.amp as amp
from sklearn import... | StarcoderdataPython |
345115 | from property_test import User
| StarcoderdataPython |
5086463 | import logging
import urllib.parse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadRequest, HttpResponseServerError
from django.shortcuts import redirect, render
from django.views.decorators.http import require_http_methods
from config.settings import NOTION_CLIENT_ID,... | StarcoderdataPython |
4907033 | """
Module to generate instance for Stochastic Capacitated Facility Location Problem
An instance comprises of random first stage cost and fixed (across all the instances)
second stage cost.
"""
from collections import defaultdict
import numpy as np
from ...utils import load_pickle
from ...utils import save_pickle
... | StarcoderdataPython |
12816589 | <filename>fft_ydiv_spin.py
from PyQt5.Qt import QDoubleSpinBox, QKeyEvent
from PyQt5.uic.Compiler.qtproxies import QtCore
from PyQt5.QtCore import pyqtSignal,Qt
class fft_ydiv_spin(QDoubleSpinBox):
val_entered=pyqtSignal()
def __init__(self,parent):
QDoubleSpinBox.__init__(self)
def k... | StarcoderdataPython |
3258598 | from flask import Flask,render_template,Response
import cv2
app=Flask(__name__)
camera=cv2.VideoCapture(0)
# for cctv camera use 'rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp'
def genFrames():
while True:
success,frame=camera.... | StarcoderdataPython |
1771760 | <filename>setup.py<gh_stars>1-10
from setuptools import find_packages, setup
setup(
name='whatsapp_web_driver',
packages=find_packages(include=['whatsapp_web_driver']),
version='0.0.0',
description='Enables the user to easily create their own whatsapp bot.',
author='<NAME>, <NAME>',
license='Ap... | StarcoderdataPython |
11371872 | <gh_stars>0
class Proprietario():
# CONSTRUCTOR
def __init__(self, nome, matricula, curso):
self.nome = nome
self.matricula = matricula
self.curso = curso
# GETTERS AND SETTERS
def get_nome(self):
return self.nome
def set_nome(self, nome):
self.nome = nome
... | StarcoderdataPython |
4881266 | <reponame>Jhonattan-rocha/Meus-primeiros-programas
from contas import Conta_poupnaca, Conta_corrente
from itertools import count
class _MetaClassCliente(type):
def __new__(mcs, name, bases, namespace):
if name == "Cliente":
return type.__new__(mcs, name, bases, namespace)
if "cadastrar... | StarcoderdataPython |
4922684 | #!/usr/bin/env python
from __future__ import print_function
from uuid import uuid4
import requests
import hashlib
import json
class CallOfDutyAPIClient(object):
deviceId = None
ssoCookie = None
cookies = {
'new_SiteId': 'cod',
'ACT_SSO_LOCALE': 'en_US',
'country': 'US',
'X... | StarcoderdataPython |
3461227 | from RPi import GPIO
class LED(object):
def __init__(self, pin):
self.pin = pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
def turn_on(self):
GPIO.output(self.pin, 1)
def turn_off(self):
GPIO.output(self.pin, 0)
| StarcoderdataPython |
214025 | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | StarcoderdataPython |
1949806 | <reponame>datacentricorg/datacentric-py
# Copyright (C) 2013-present The DataCentric Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | StarcoderdataPython |
1729205 | # -*- coding: utf-8 -*-
from .derivation import (
normalised_primary_matrix,
chromatically_adapted_primaries,
primaries_whitepoint,
RGB_luminance_equation,
RGB_luminance,
)
from .rgb_colourspace import RGB_Colourspace
from .rgb_colourspace import XYZ_to_RGB, RGB_to_XYZ
from .rgb_colourspace import ... | StarcoderdataPython |
4967716 | <reponame>justusc/Elemental
#
# Copyright (c) 2009-2015, <NAME>
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El
import time
n=30
A = El... | StarcoderdataPython |
5028086 | <filename>spectrochempy/core/dataset/coordrange.py
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. =
# ... | StarcoderdataPython |
3290460 | #!/usr/bin/env python
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All c... | StarcoderdataPython |
9680436 | <reponame>sapcc/neutron-lib<gh_stars>0
# 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 wr... | StarcoderdataPython |
1780100 | # Version information. This file will be overwritten by the GitLab CI for every release build
__version__ = '0.3.0'
| StarcoderdataPython |
1648773 | import json
class InventoryItemExistException(Exception):
"""
There is an item in the Inventory with the same code -> Integrity Error
"""
def __init__(self):
pass
class InventoryItemDoesNotExistException(Exception):
"""
Requested item not exists
"""
def __init__(self):
... | StarcoderdataPython |
8010648 | from flask import render_template, current_app as app, request, redirect
from werkzeug.utils import secure_filename
import json
import os, glob
with open("config.json", "r") as file:
params = json.load(file)['params']
app.config['Upload_folder'] = params["uploadPath"]
# clear Data
def clearDara():
for fi... | StarcoderdataPython |
5123659 | <gh_stars>0
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from .models import GeneralNotification
class UserAdmin(admin.ModelAdmin):
pass
admin.site.register(GeneralNotification, UserAdmin)
| StarcoderdataPython |
9729634 | #! /usr/bin/env python
"""Choose assassin(s) and maybe targets for a nerf-assassin game.
Arguments:
targets: Comma-separated list of targets. If empty, targets will be
chosen at random.
-p players: list of players.
-d, --dry-run: don't actually send emails; just run the chooser.
"""
# vim:... | StarcoderdataPython |
3348938 | import bpy
import bmesh
import math
from . import object_manager
from . import settings_manager
def set_normals_to_outside(context, objects, only_recalculate_if_flagged = True):
'''
Set normals of objects so that they point outside of the mesh
(convex direction).
Set normals is an issue with planes, ... | StarcoderdataPython |
6558226 | <filename>liao_xue_feng/_6_oop/test.py
# -*- coding: utf-8 -*-
from liao_xue_feng._6_oop.human import Human
from liao_xue_feng._6_oop.student import Student
tom = Human('Tom', 18)
tom.speak()
tom.__age = 0 # not work, because the `__age` property of Human object had been changed to `_Human__age`
# tom._Human__age =... | StarcoderdataPython |
3513495 | <gh_stars>100-1000
def startup_installed(sender):
from uliweb.core import template
from .tags import link, use, htmlmerge
template.default_namespace['_tag_link'] = link
template.default_namespace['_tag_use'] = use
template.default_namespace['_tag_htmlmerge'] = htmlmerge
def init_static... | StarcoderdataPython |
11217372 | <filename>dict_merge.py
dict1 = {'players': 251, 'audience': 1500}
dict2 = {'audience': 1700, 'matches': 30}
merged_dict = {**dict1, **dict2} # if any common keys are found the latter keys are used in the merged dict (dict2)
print(merged_dict)
| StarcoderdataPython |
9718561 | import h5py
import numpy as np
import os
from contextlib import contextmanager
from . import _utils as utils
import time
class _safe_open:
"""Custom context manager for opening files."""
def __init__(self, filename, *args, **kwargs):
self.f = False
while not self.f:
self.open(file... | StarcoderdataPython |
9678877 | <filename>src/domainClient/models/domain_agency_service_v2_model_contact_details.py
# coding: utf-8
"""
Domain Group API V1
Provides public access to Domain's microservices # noqa: E501
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint... | StarcoderdataPython |
3273713 | <gh_stars>1-10
import autoarray as aa
import numpy as np
from autoarray.mock.mock import MockPixelizationGrid, MockMapper
def test__regularization_matrix__matches_util():
pixel_neighbors = np.array(
[
[1, 3, 7, 2],
[4, 2, 0, -1],
[1, 5, 3, -1],
... | StarcoderdataPython |
1959236 | from .seg_hrnet_ocr import HighResolutionNet, get_seg_model | StarcoderdataPython |
1759508 | <filename>txqueue/scheduler/dispatcher.py
# the server runs in ../../api/openAPI3 or ../../api/swagger2
# so at runtime, the relative path to any file in the directory with dispatcher.py
# is ../../
import sys
sys.path.append('../..')
# and the full path to this file will be txqueue.scheduler.dispatcher
import json
im... | StarcoderdataPython |
1793229 | #!/usr/bin/env python
import logging
import rx
asyncio = rx.config['asyncio']
def main():
"""Somewhat simple example of asyncio"""
logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
loop.run_until_complete(do_something())
loop.close()
logging.info('closed event loop')
... | StarcoderdataPython |
4889981 | class ToolStripProgressBar(ToolStripControlHost,IComponent,IDisposable,IDropTarget,ISupportOleDropSource,IArrangedElement):
"""
Represents a Windows progress bar control contained in a System.Windows.Forms.StatusStrip.
ToolStripProgressBar()
ToolStripProgressBar(name: str)
"""
def Instance(self):
"... | StarcoderdataPython |
4837880 |
from lasso.utils.ConsoleColoring import ConsoleColoring
from lasso.logging import str_error, str_warn, str_info
import pickle
import os
import sys
import time
import logging
from concurrent import futures
import ansa
sys.path.append(os.path.dirname(__file__))
sys.path.append(os.path.join(os.path.dirname... | StarcoderdataPython |
348712 | <reponame>ChrisDeadman/pyPhone
from pyphone.widgets import *
class RootPanel(Panel):
def __init__(self, master, cnf={}, **kw):
from pyphone.panels import CallPanel, MessagePanel, InfoPanel, BottomPanel
super().__init__(master, cnf, **kw)
self.grid_rowconfigure(0, weight=7)
self.g... | StarcoderdataPython |
202300 | import json
import logging
from django import template
from cio.pipeline import pipeline
from djedi.auth import has_permission
from djedi.compat import render_to_string
register = template.Library()
logger = logging.getLogger(__name__)
@register.simple_tag(takes_context=True)
def djedi_admin(context):
output ... | StarcoderdataPython |
6660615 | <filename>sols_python/1238.py
entrada1 = int(input())
strings = list()
for c in range(entrada1):
entrada = input()
strings.append(entrada)
for frase in strings:
fraseEmArray = frase.split()
if len(fraseEmArray[0]) <= len(fraseEmArray[1]):
menorPalavra = len(fraseEmArray[0])
else:
men... | StarcoderdataPython |
9636887 | <filename>app_tasks/apps.py<gh_stars>0
from django.apps import AppConfig
class AppTasksConfig(AppConfig):
name = 'app_tasks'
| StarcoderdataPython |
1872844 | <filename>saleor/graphql/order/dataloaders.py
from collections import defaultdict
from django.db.models import F
from ...order.models import Order, OrderEvent, OrderLine
from ...payment.models import Payment
from ...warehouse.models import Allocation
from ..core.dataloaders import DataLoader
class OrderLinesByVaria... | StarcoderdataPython |
1899107 | <reponame>the16thpythonist/ufotest<filename>ufotest/ci/server.py
import os
import json
import time
import smtplib
import datetime
import shutil
import click
from flask import Flask, request, send_from_directory, jsonify
from ufotest.config import Config, get_path
from ufotest.util import get_template, get_version
fro... | StarcoderdataPython |
1836694 | <filename>count_operations.py
import torch
import torchvision.models as models
import torch.nn as nn
import pretrainedmodels
from torchsummary import summary
from torch.autograd import Variable
from collections import OrderedDict
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from networkx.dr... | StarcoderdataPython |
11200007 | import json
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from service.account.account_base_service import AccountBaseService
from service.common.common_service import CommonService
class ApiPermissionCheck(MiddlewareMixin):
"""
api调用权限校验中间件
"""
def process_... | StarcoderdataPython |
4821174 | <reponame>PotatoHD404/py-exceptions<filename>examples/exclude_example.py
from pyexceptions import handle_exceptions
def divide(a, b):
return a / b
def real_main():
i = 5
j = 0
c = divide(i, j)
print(c)
def wrapper():
real_main()
@handle_exceptions(exclude=2)
def main():
wrapper()
i... | StarcoderdataPython |
143703 | """
Utility to call cloudformation command with args
"""
import os
import logging
import platform
import subprocess
import sys
from samcli.cli.global_config import GlobalConfig
LOG = logging.getLogger(__name__)
def execute_command(command, args, template_file):
LOG.debug("%s command is called", command)
tr... | StarcoderdataPython |
4828715 | """Module with the common cryptography-assotiated utils.
This module uses libsodium as a backend."""
from typing import Optional
from pysodium import (
crypto_sign_keypair,
crypto_sign_detached,
crypto_sign_verify_detached,
crypto_hash_sha256,
crypto_hash_sha256_BYTES,
crypto_sign_SECRETKEYBYT... | StarcoderdataPython |
1862243 | from . import Connection
class ConnectionTCP(Connection):
def _connect(self):
hostname = os.getenvb(b'SELPI_CONNECTION_TCP_HOSTNAME')
port = int(os.getenvb(b'SELPI_CONNECTION_TCP_PORT'))
self.__sock = socket.create_connection((hostname, port))
def _read(self, length: int):
retu... | StarcoderdataPython |
3445758 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import sys
sys.stdout.write("This is a program which throws an exception.")
raise Exception("Paf Boum Boum Bada Boum !!!")
| StarcoderdataPython |
6643480 | from abc import ABC, abstractmethod
from typing import Any, Dict, List, Tuple
import numpy as np
from scipy.sparse import diags
import lumos.numpy as lnp
from lumos.optimal_control.collocation import (
build_lagrange_differential_matrix,
build_lagrange_integration_matrix,
CollocationEnum,
get_colloca... | StarcoderdataPython |
11305751 | <reponame>CACF/Lost-and-Stolen-Device-Subsystem
from flask import abort
from functools import wraps
from ..models.case import Case
def restricted(f):
@wraps(f)
def user_level(self, tracking_id, **kwargs):
case = Case.get_case(tracking_id)
if case and case['creator']['user_id'] != kwargs.get('s... | StarcoderdataPython |
1984465 | <filename>src/ppopt/plot.py
import time
from math import atan2
from typing import List
import numpy
import plotly.graph_objects as go
import pypoman
from matplotlib import pyplot
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from .solution import Solution
from .utils.genera... | StarcoderdataPython |
1845143 | <reponame>mirfan899/MTTS
# -*- coding: UTF-8 -*-
"""
..
---------------------------------------------------------------------
___ __ __ __ ___
/ | \ | \ | \ / the automatic
\__ |__/ |__/ |___| \__ annotation and
\ | |... | StarcoderdataPython |
11351462 | <filename>iob2DynaML.py
from math import sqrt
import math
import numpy
from numpy import matmul
from math import sin, cos, radians
import sys,datetime, os
class DnaStation:
def __init__(self):
self.name = ''
self.Constraint=''
self.Type=''
self.XAxis=''
self.YAx... | StarcoderdataPython |
11306785 | <reponame>ubco-mds-2021-labs/dashboard1-group-a
import pandas as pd
TEMP_DATA_PATH = "data/temperature_df_full.csv"
ENERGY_DATA_PATH = "data/energy_df_full.csv"
# Temperature dataframe for Tab 1 Use
# Extra column from csv index dropped for performance.
temperature_df_full = pd.read_csv("data/temperature_df_full.csv"... | StarcoderdataPython |
1686411 | # Code below is the expansion of the statement:
#
# RESULT = yield from EXPR
#
# Copied verbatim from the Formal Semantics section of
# PEP 380 -- Syntax for Delegating to a Subgenerator
#
# https://www.python.org/dev/peps/pep-0380/#formal-semantics
# tag::YIELD_FROM_EXPANSION[]
_i = iter(EXPR) # <1>
try:
_y = n... | StarcoderdataPython |
1758344 | import numpy as _np
import copy as _copy
def read_energy_acceptance_file(fname, eRF):
# reads raw data from file
lines = [line.strip() for line in open(fname)]
# processes raw data
accp, accn = [], []
for line in lines:
if not line or line[0] == '#':
continue
values = ... | StarcoderdataPython |
36676 | <gh_stars>0
import youtube_dl
class Download2Mp3:
def __init__(self, CallableHook=None):
self.hook = CallableHook
self.notDownloaded = []
self.setupDownloadParam()
# Public functions
def downloadMusicFile(self, url):
if type(url) is not str:
raise TypeError("ur... | StarcoderdataPython |
8049604 | <filename>samples/uvas/heat_map_generation/count_heatMap.py
import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib import cm
def segment_hilera(pt1, pt2, delta_h):
"""
Segmenta la hile... | StarcoderdataPython |
5136256 | import unittest
from beziers.cubicbezier import CubicBezier
from beziers.point import Point
from beziers.path import BezierPath
class CubicMethods(unittest.TestCase):
def test_extremes(self):
q = CubicBezier(
Point(65,59), Point(194,90), Point(220,260), Point(70,261)
)
# console.log(Bezier(65,59, 1... | StarcoderdataPython |
8009339 | """
This is a module used in a test, not a test itself.
"""
from zope.interface import classProvides
from twisted.plugin import IPlugin
from eridanus.ieridanus import IEridanusPluginProvider
from eridanus.plugin import Plugin
class SadPlugin(Plugin):
"""
A plugin that does nothing.
"""
classProvides(... | StarcoderdataPython |
12839522 | <gh_stars>1-10
from typing import Optional, Dict, List
import json
import os
import re
from pprint import pprint
LIBC_REPO_PATH = os.getenv("LIBC_REPO_PATH", "libc")
PREDICATES = {
"fuchsia/mod.rs": {"os": ["fuchsia"]},
"unix/bsd/apple/mod.rs": {"os": ["macos", "ios"]},
"unix/bsd/freebsdlike/dragonfly/mod... | StarcoderdataPython |
254621 | # ToDo
#
# Add a syntax like
# .define mp_XXX
# with no definition of the value. When this is encountered,
# the script will get the variable's value from the python
# global variables. This makes it easier to define multiline
# strings and get them into the output.
'''
A macro processor; prin... | StarcoderdataPython |
11394931 | #===========================================#
# #
# #
#----------CROSSWALK RECOGNITION------------#
#-----------WRITTEN BY N.DALAL--------------#
#-----------------2017 (c)------------------#
# ... | StarcoderdataPython |
184783 | <reponame>yasuaki-344/streamlit-docker
"""プロットデータアクセスオブジェクトのサンプル."""
import numpy as np
class PlotDataRepository:
"""データアクセスオブジェクトの一例."""
def __init__(self):
"""Initialize a new instance of ExampleRepository."""
pass
def generate_data(self) -> np.array:
"""データ取得の一例."""
x_... | StarcoderdataPython |
4967987 | <gh_stars>0
#!/usr/bin/env python3
#
# Copyright (c) <NAME> and the University of Texas MD Anderson Cancer Center
# Distributed under the terms of the 3-clause BSD License.
import copy
import os
import subprocess
import time
import signal
from collections import OrderedDict, Mapping, Sequence
from .eval import SoS_ev... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.