id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3367424 | """ TechTV constants """
TTV_VIDEO_BUCKET = "ttv_videos"
TTV_THUMB_BUCKET = "ttv_static"
class ImportStatus:
"""Simple class for possible video statuses"""
CREATED = "Created"
COMPLETE = "Complete"
ERROR = "Error"
MISSING = "Missing"
ALL_STATUSES = [CREATED, COMPLETE, ERROR, MISSING]
| StarcoderdataPython |
1785764 | """
Tests functions which use MOPAC.
These tests are only run when the --mopac_path pytest option is used.
MOPAC is 3rd party software, it does not come with ``stk``.
"""
import pytest
import sys
import os
import stk
mopac = pytest.mark.skipif(
all('mopac' not in x for x in sys.argv),
reason="Only run when ... | StarcoderdataPython |
3272515 | <gh_stars>0
#!/usr/bin/env python
#
# Quick SSL Cert creation method
#
# Used if you want to create self signed
from src.core.setcore import *
import subprocess
import os
definepath = os.getcwd()
os.chdir(userconfigpath)
# create the directories for us
subprocess.Popen("mkdir CA;cd CA;mkdir newcerts private", shell=Tr... | StarcoderdataPython |
1744546 | <filename>fuxi/web/api/config/settings.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : jeffzhang
# @Time : 2020/1/17
# @File : settings.py
# @Desc : ""
from flask import session
from flask_restful import Resource, reqparse
from fuxi.core.auth.token import auth
from fuxi.core.data.response import... | StarcoderdataPython |
1601390 | from django.dispatch import Signal
# An existing user removed from a tenant
tenant_user_removed = Signal(providing_args=["user", "tenant"])
# An existing user added to a tenant
tenant_user_added = Signal(providing_args=["user", "tenant"])
# An existing user is connected to a tenant user
tenant_user_connected = Sign... | StarcoderdataPython |
3708 | from uuid import uuid4
from sqlalchemy import Index, Column, Text, Table, ForeignKey
from sqlalchemy.orm import object_session
from onegov.core.orm import Base
from onegov.core.orm.types import UUID
spoken_association_table = Table(
'spoken_lang_association',
Base.metadata,
Column(
'translator_i... | StarcoderdataPython |
3255772 | <reponame>sungheeyun/optmlstat
from abc import abstractmethod
from typing import Any
from optmlstat.basic_modules.class_base import OptMLStatClassBase
from optmlstat.opt.opt_prob import OptimizationProblem
from optmlstat.opt.opt_parameter import OptimizationParameter
class OptimizationAlgorithmBase(OptMLStatClassBas... | StarcoderdataPython |
154445 | import pyplc
import threading, time
class Plc(object):
__pl = None
def __init__(self, db):
self.record = False
self.db = db
self.cur = self.db.getCursor()
print("Init PLC")
self.__pl = pyplc.PyPlc()
self.__pl.setrxcb(self.rx_callback)
self.__pl.speed=200... | StarcoderdataPython |
3300529 | import unittest
from cowrie.core.output import Output
class TestPublicIPAsSensorName(unittest.TestCase):
def test_public_ip(self):
print(Output().sensor)
assert Output().sensor[0] in ['1', '2']
| StarcoderdataPython |
3249026 | <gh_stars>0
import math
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
from step03_positional_encoding import PositionalEncoding
# https://blog.csdn.net/SangrealLilith/article/details/103527408
num_layers = 4
d_model = 128
dff = 512
num_heads = 8
dropout_rate = 0.1
class ... | StarcoderdataPython |
16443 | <reponame>justinormont/NimbusML-1
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------------------------
# ... | StarcoderdataPython |
129951 | # Copyright (c) 2022, <NAME> and Contributors
# See license.txt
# import frappe
import unittest
class TestEstimateBOM(unittest.TestCase):
pass
| StarcoderdataPython |
4839938 | # Merge sort
def sortElements(arr):
mergesort(arr,[None] * len(arr),0,len(arr)-1)
print(arr)
def mergesort(arr,temp,left,right):
if left < right:
mid = int((left + right) /2)
mergesort(arr,temp,left,mid)
mergesort(arr,temp,mid+1,right)
merge(arr,temp,left,right)
def merge(a... | StarcoderdataPython |
3331991 | from django.db import models
# Create your models here.
from django.contrib.auth import get_user_model
User = get_user_model()
class Project(models.Model):
user = models.ForeignKey(User, related_name='projects',
on_delete=models.CASCADE)
name = models.TextField()
description ... | StarcoderdataPython |
4831487 | <filename>dicionario/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name='home'),
path('busca/', views.BuscaView.as_view(), name='busca'),
path('dicionario/<slug:slug>', views.TermoDetailView.as_view(), name='termo-detail'),
path('categorias/', views.Categ... | StarcoderdataPython |
3282685 | <filename>find_drive/find_drive.py
from subprocess import check_output
def find_drive():
drive = ["A:","B:","C:","D:","E:","F:","G:","H:","Z:","N:","K:","L:","X:","P:","U:","J:","S:","R:","W:","Q:","T:","Y:","I:","O:","V:","M:"]
system_drive = []
cmd = check_output("net share",shell=True)
for i in... | StarcoderdataPython |
1788612 | <reponame>nurulishlah/qiscus-sdk-wrapper
# -*- coding: utf-8 -*-
import json
from requests import post
class QiscusSDK(object):
"""
Simple Qiscus SDK wrapper, NOW POST TO QISME ENGINE
"""
@staticmethod
def send_message(topic_id, message='', _type='text', base_url='', access_token='', payload=Non... | StarcoderdataPython |
164354 | """
Author: <NAME> and <NAME>
E-mail author: <EMAIL>
Last Modified: May 7 2020
"""
import math
import pandas as pd
import motmetrics as mm
import numpy as np
from collections import defaultdict
from Metrics import Metrics
"""
Create individual metrics class for new challenge. The new metrics class inherits functiona... | StarcoderdataPython |
67688 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
version = "1.2.0"
setuptools.setup(
name="sabersql",
version=version,
author="<NAME>",
author_email="<EMAIL>",
description="SaberSQL is a tool to scrape baseball data from various sources and import it into a My... | StarcoderdataPython |
3246033 | """
Proxy RPC calls to seafile_api, silence RPC errors, emulating Ruby's
"method_missing".
"""
from functools import partial
import logging
from seaserv import seafile_api
from pysearpc import SearpcError
# Get an instance of a logger
logger = logging.getLogger(__name__)
class RPCProxy(object):
def __init__(sel... | StarcoderdataPython |
3229248 | <filename>apps/crm/apps.py
# Librerias Django
from django.apps import AppConfig
class CrmConfig(AppConfig):
name = 'crm'
| StarcoderdataPython |
1624060 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 14:52:28 2019
@author: Carlos
"""
import os
import sys
from pathlib import Path
import numpy as np
import datetime
def query_yes_no(question, default="yes"):
'''
Ask a yes/no question via raw_input() and return their answer.
:param quest... | StarcoderdataPython |
94877 | import os
from unittest.mock import MagicMock
import pytest
from razemax.drivers import SQSDriver
from razemax.exceptions import DriverError
class TestSQSDriver:
def test_not_message(self):
queue = MagicMock()
queue.receive_messages.return_value = None
result = SQSDriver(queue).receive_... | StarcoderdataPython |
3283856 | <gh_stars>1-10
"""
home.collect.handlers
=====================
Handlers are defined to handle events that Home collects. They will either
just record the event, or store it in a particular way or take action based on
the event.
"""
from logging import getLogger
from home import db
from home.exceptions import Handler... | StarcoderdataPython |
89342 | # input a directory, each file is a document
import os
import sys
from gensim import corpora, models
from topic.topicio import TopicIO
from preprocess.DocTokenizer import DirDocTokenizer, FileDocTokenizer
from utils.WordCounter import WordCounter
#
# Analyze a specific LDA file and output results
# Assume the exi... | StarcoderdataPython |
60437 |
import logging
import logging.handlers
"""
Returns a logging handler with a default format
"""
def get_logging_handler(log_filename):
handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=2*1024*1024, backupCount=5)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %... | StarcoderdataPython |
1625113 | load("@io_bazel_rules_go//go:def.bzl", "go_repository")
def mixer_adapter_repositories():
native.git_repository(
name = "org_pubref_rules_protobuf",
commit = "563b674a2ce6650d459732932ea2bc98c9c9a9bf", # Nov 28, 2017 (bazel 0.8.0 support)
remote = "https://github.com/pubref/rules_protobuf... | StarcoderdataPython |
1658314 | <reponame>C-Stevens/laika-weblogs<filename>log/forms.py
from django import forms
from django.utils.safestring import mark_safe
from django.utils import timezone
import datetime
class weblog_userForm(forms.Form):
nickname = forms.CharField(label='', initial="Nickname", widget=forms.TextInput(attrs={
'requir... | StarcoderdataPython |
3274055 | from logging import Logger
from slack_bolt import Ack
from slack_sdk import WebClient
def sample_shortcut_callback(body: dict, ack: Ack, client: WebClient, logger: Logger):
try:
ack()
client.views_open(
trigger_id=body["trigger_id"],
view={
"type": "modal",... | StarcoderdataPython |
101966 | <filename>Stacks/stacksUsingList.py
#stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner.
#In stack, a new element is added at one end and an element is removed from that end only.
stack = []
# append() function to push
# element in the stack
stack.app... | StarcoderdataPython |
1884 | from multiprocessing import Pool
import EnvEq as ee
import numpy as np
import itertools as it
import os
#parsing input into numpy arrays
from input import *
y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test])
p=np.array([p_o2,p_test])
mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]])
lam=np.a... | StarcoderdataPython |
1622428 | <reponame>uchicago-link/bio-grid-compute-engine
#!/usr/bin/python
import os
import time
import urllib2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--database')
parser.add_argument('--query')
parser.add_argument('--outfile')
parser.add_argument('--jobid')
args = parser.parse_args()
# Fake w... | StarcoderdataPython |
154179 | <filename>Prob&Stats_hackerrank/day4_bionomial.py<gh_stars>0
from scipy.stats import binom
b=1.09
g=1
s=2.09
p=(b/s)
result=binom.rvs(size=3,n=6,p=(b/s))
print("%.3f"%result)
| StarcoderdataPython |
118557 | <reponame>dwward/kb-syllabus
'''
Utility to assist in converting CSV format of Kaiwan Syllabus to
a technique list. Expects CSV format in a particular format that
requires the Excel spreadsheet to be altered according to
example below.
Example
-------------
THROWING TECHNIQUES (NAGE WAZA),... | StarcoderdataPython |
95702 | <filename>poputils/utils/cidr.py
class CIDR(object):
def __init__(self, base, size=None):
try:
base, _size = base.split('/')
except ValueError:
pass
else:
if size is None:
size = _size
self.size = 2 ** (32 - int(size))
... | StarcoderdataPython |
1799250 | <reponame>ABEMBARKA/monoUI
#!/usr/bin/env python
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, p... | StarcoderdataPython |
3225418 | <gh_stars>0
from .baby_robot_env_v0 import BabyRobotEnv_v0
from .baby_robot_env_v1 import BabyRobotEnv_v1
from .baby_robot_env_v2 import BabyRobotEnv_v2
from .baby_robot_env_v3 import BabyRobotEnv_v3
from .baby_robot_env_v4 import BabyRobotEnv_v4
from .baby_robot_env_v5 import BabyRobotEnv_v5
from .baby_robot_env_v6 im... | StarcoderdataPython |
3370591 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_listdetail
----------------------------------
Tests for `swmmtoolbox` module.
"""
import shlex
import subprocess
import os
import six
import csv
from unittest import TestCase
from pandas.util.testing import assert_frame_equal
import sys
try:
f... | StarcoderdataPython |
4829977 | """ Test the electronic energy from several different Molpro jobs.
"""
import numpy
import elstruct
import importlib
from elstruct.params import METHOD
# Program to test
PROGRAMS = ['molpro2015']
# Theories to test
THEORIES = [
METHOD.RHF,
METHOD.UHF,
METHOD.ROHF,
METHOD.RHF_MP2,
METHOD.UHF_UMP2,... | StarcoderdataPython |
145563 | <reponame>emaric/poor-trader-py
import abc
from poor_trader import utils
from poor_trader.market import Market
from poor_trader.screening import entity, indicator
from poor_trader.screening.entity import Direction
class StopPriceStrategy(entity.Strategy):
def __init__(self):
super().__init__(self.__clas... | StarcoderdataPython |
1640153 | <filename>python/202_Happy_Number_wei.py
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
# https://en.wikipedia.org/wiki/Happy_number
#after each time, they check for both halt conditions: reaching 1, and repeating a number.
#E... | StarcoderdataPython |
1715618 | <reponame>girder/django-girder-utils
from datetime import timedelta
from django.core.files.storage import Storage
try:
from storages.backends.s3boto3 import S3Boto3Storage
except ImportError:
# This should only be used for type interrogation, never instantiation
S3Boto3Storage = type('FakeS3Boto3Storage',... | StarcoderdataPython |
1676067 | <gh_stars>0
# -*- coding: utf-8 -*-
import os
import random
import sh
import string
import unittest
from zipfile import is_zipfile
from bitbucket.tests.private.private import AuthenticatedBitbucketTest
TEST_REPO_SLUG = "test_repository_creation"
def skipUnlessHasGit(obj):
# Test git presence
try:
sh... | StarcoderdataPython |
3391332 | <filename>medusa/xmedusa.py
#! /usr/bin/env python3
###############################################################################
import asyncio
import random
async def mainCoroutineSimple():
print('Simple coroutine')
async def mainCoroutineFancy(id):
process_time = random.randint(1,5)
await asyncio... | StarcoderdataPython |
3340581 | <reponame>tefra/xsdata-w3c-tests<filename>output/models/nist_data/atomic/negative_integer/schema_instance/nistschema_sv_iv_atomic_negative_integer_pattern_5_xsd/__init__.py
from output.models.nist_data.atomic.negative_integer.schema_instance.nistschema_sv_iv_atomic_negative_integer_pattern_5_xsd.nistschema_sv_iv_atomic... | StarcoderdataPython |
3221900 | <filename>python/test/test_logger_data_type.py
# coding: utf-8
"""
Seldon Deploy API
API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501
OpenAPI spec version: v1alpha1
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/... | StarcoderdataPython |
3205103 | import django_tables2 as tables
from django.urls import reverse
from django.utils.html import format_html
class StandardItemTable(tables.Table):
"""
Table template for standard items owned and editable by the current user. This is meant to be a template for the
django-tables2 table_factory. Constructor do... | StarcoderdataPython |
1695910 | from constants import Unit, OrderType
class Quantity(object):
def __init__(self, amount=0, units=Unit.USD):
self.amount=amount
self.units=units
class Order(object):
def __init__(self, size=Quantity(), price=Quantity(), kind=OrderType.BID):
self.size=size
self.price=price
self.kind=kind
# Negative price... | StarcoderdataPython |
4823752 | import numpy as np
import cv2
# c++ version pse based on opencv 3+
from pse import decode as pse_decode
from util.config import config as cfg
import time
class TextDetector(object):
def __init__(self, model):
# evaluation mode
self.model = model
model.eval()
# parameter
se... | StarcoderdataPython |
3304932 | import tkinter as tk
import utility
from signup import signup_screen
from login import login_screen
bg_col: str = "grey"
fg_col: str = "white"
button_col: str = "dark grey"
root = tk.Tk()
root.geometry(f"{root.winfo_screenwidth()}x{root.winfo_screenheight()}+-5+0")
root.title("VMedia")
root.config(bg=bg_col)
root.bi... | StarcoderdataPython |
3273570 | <reponame>cnHeider/draugr
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__doc__ = r"""
Created on 14-02-2021
"""
import numpy
import torch
from torch.autograd import Function
__all__ = ["GuidedBackPropReLUModel", "GuidedBackPropReLU"]
class GuidedBackPropReLU(Function)... | StarcoderdataPython |
3296755 | # -*- coding: utf-8 -*-
__author__ = 'olunx'
import json
from django.conf import settings
from ebaysdk.exception import ConnectionError
from ebaysdk.trading import Connection as Trading
from apps.ebay.models import EbayProductItem
def add_fixed_price_item(data):
"""http://www.utilities-online.info/xmltojson/#... | StarcoderdataPython |
3361693 | <filename>webhooks.py
#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
一个使用github webhook 自动更新网站的脚本
首先需要设置环境变量`export GH_SECRET_TOKEN='your secret token'`,
GH_SECRET_TOKEN 可以使用 `ruby -rsecurerandom -e 'puts SecureRandom.hex(20)'` 生成
"""
import os
import subprocess
import json
import hmac
from http.server import HT... | StarcoderdataPython |
65042 | from django import template
from django.contrib.contenttypes.models import ContentType
from ..models import Comment
from ..forms import CommentForm
register = template.Library()
@register.simple_tag
def get_comment_count(obj):
content_type = ContentType.objects.get_for_model(obj)
return Comment.objects.filte... | StarcoderdataPython |
106791 | from .map_aiter import map_aiter
from .join_aiters import join_aiters
def message_stream_to_event_stream(event_template, message_stream):
"""
This tweaks each message from message_stream by wrapping it with a dictionary
populated with the given template, putting the message is at the top
level under "... | StarcoderdataPython |
69863 | <reponame>iColabora/pixie
# Copyright 2018- The Pixie 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
#
# Unless required by applic... | StarcoderdataPython |
1733258 | <reponame>jinbooooom/coding-for-interview<filename>dataStructure/tree/BinaryTree.py
# -*- coding:utf-8 -*-
class BinaryTree:
def __init__(self, rootObj):
self.key = rootObj
self.left = None
self.right = None
def insertLeft(self, newNode):
if not self.left: # 若左孩子节点为空
... | StarcoderdataPython |
1616200 | <filename>tests.py
import notedown
simple_backtick = """
```
code1
space_indent
```
text1
``
```
code2
tab_indent
~~~
```
text2"""
simple_tilde = """
~~~
code1
space_indent
~~~
text1
``
~~~~
code2
tab_indent
~~~
~~~~
text2"""
simple_indented = """
code1
space_indent
text1
``
code2
tab_i... | StarcoderdataPython |
55613 | from django.conf.urls import url
from ratelimitbackend import admin
from ratelimitbackend.views import login
from .forms import CustomAuthForm, TokenOnlyAuthForm
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'admin/login.html'}, name='login'),
url(r'^custom_login/$', login,
{'tem... | StarcoderdataPython |
4836105 | # -*- coding: utf-8 -*-
"""Convert a BEL graph to HiPathia inputs.
Input
-----
SIF File
~~~~~~~~
- Text file with three columns separated by tabs.
- Each row represents an interaction in the pathway. First column is the source
node, third column the target node, and the second is the type of relation
between them... | StarcoderdataPython |
3275875 | <reponame>utkarshdeorah/sympy<gh_stars>1-10
from sympy.core.numbers import E
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.geometry.curve import Curve
from sympy.integrals.integrals import line_integrate
... | StarcoderdataPython |
32561 | <reponame>boxingbeetle/softfab<filename>src/softfab/pages/InspectDone.py
# SPDX-License-Identifier: BSD-3-Clause
from typing import ClassVar, Mapping, cast
from softfab.ControlPage import ControlPage
from softfab.Page import InvalidRequest, PageProcessor
from softfab.pageargs import DictArg, EnumArg, StrArg
from soft... | StarcoderdataPython |
4828526 | import numpy as np
import torch
import torch.nn.functional as F
def ista_iteration(iterate, y, operator, step, lambd,
inpainting=False, prior_inpainting=None):
"""
ISTA iteration
Parameters
----------
iterate : torch.Tensor
Current iterate
y : torch.Tensor
d... | StarcoderdataPython |
3219068 | # Advent of Code - 2015 - Day 8
# --- Day 8: Matchsticks ---
# Space on the sleigh is limited this year, and so Santa will be bringing his list as a digital copy. He needs to know how much space it will take up when stored.
# It is common in many programming languages to provide a way to escape special characters in... | StarcoderdataPython |
3375134 | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest... | StarcoderdataPython |
1637072 | <gh_stars>10-100
import sys
from .tag import CrimeTags
"""
A command line interface to the automatic article crime taging.
Run with `python -m tagnews.crimetype.cli`
"""
if __name__ == '__main__':
crimetags = CrimeTags()
if len(sys.argv) == 1:
print(('Go ahead and start typing.'
'\nIf ... | StarcoderdataPython |
1705279 | <reponame>maburto00/ndsgo
from utils import Color, cd2p, rc2p, eprint, c_cd2cp,p2a
import utils
import struct
# NS is overwritten in __init__ to be N+1
NS = 19 + 1
WE = 1
letter_coord = 'ABCDEFGHJKLMNOPQRST'
color_string = 'XO.'
#NUM_CHANNELS = 4 #used in dataset_generator
class Error:
SUICIDE, KO, NONEMPTY, NO... | StarcoderdataPython |
1734302 | # encoding: utf-8
'''
JSON: JavaScript Object Notation
:see: `RFC 4627 <http://tools.ietf.org/html/rfc4627>`__
:requires: `cjson <http://pypi.python.org/pypi/python-cjson>`__ | minjson
'''
from smisk.core import request
from smisk.serialization import serializers, Serializer
try:
from cjson import \
en... | StarcoderdataPython |
54285 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 8 12:16:53 2021
@author: M.Tarka
"""
from machinetranslation import translator
from flask import Flask, render_template, request
#import json
app = Flask("Web Translator")
@app.route("/englishToFrench")
def english_to_french():
textToTranslate = r... | StarcoderdataPython |
84080 | import pickle
import csv
from gensim.parsing import preprocessing
import re
import os
from tqdm import tqdm
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=MAG19 user=mag password=<PASSWORD>$ host=shetland.informatik.uni-freiburg.de")
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCurso... | StarcoderdataPython |
4836033 | <reponame>chainren/python-learn<filename>100days/day60/urllib_demo.py
import urllib.parse
import urllib.request
url = 'http://www.baidu.com/s'
params = urllib.parse.urlencode({'wd':'python'})
# 发送请求
resp = urllib.request.urlopen('?'.join([url, params]))
# 处理响应
print(resp.getcode())
print(resp.readlines()) | StarcoderdataPython |
3304653 | <reponame>TCC-joaorobson-ViniciusBernardo/backend<filename>sigeml/services/publisher.py
import json
import logging
import random
import time
import paho.mqtt.client as mqtt
logging.basicConfig(level=logging.INFO)
class Publisher:
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name... | StarcoderdataPython |
125189 | from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QListWidget,
QDialogButtonBox, QLabel)
class PickChannels(QDialog):
def __init__(self, parent, channels, selected=[]):
super().__init__(parent)
self.parent = parent
self.setWindowTitle('Pick Channels')
... | StarcoderdataPython |
159927 | class Terminal(object):
check = u'\u2714'
error = u'\u2715'
broken = u'\u2718'
arrow = u'\u21D2'
broken_arrow = u'\u21CF'
under_arrow = u'\u21AA'
class tcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '... | StarcoderdataPython |
129736 | <filename>my_rl_teacher/random_info_maker.py<gh_stars>0
import numpy as np
def make_random_info(vec_obs_size:int, act_size:int, stack_num:int):
observation = [2*np.random.rand(vec_obs_size)-1 for x in range(stack_num)]
action = [2*np.random.rand(act_size)-1 for x in range(stack_num)]
reward = [2*np.random.... | StarcoderdataPython |
134557 | <gh_stars>1000+
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"... | StarcoderdataPython |
3236348 | """
Faça um programa que abre e reproduza o audio de um mp3
"""
from playsound import playsound
playsound('Unusual.mp3', block=True)
| StarcoderdataPython |
4832247 | <gh_stars>0
import matplotlib.pyplot as plt
def informar_dados():
valor_inicial = float(input('Digite o valor inicial: '))
rendimento = float(input('Digite o rendimento por período(%): '))
valor_aporte = float(input('Digite o valor do aporte por período: '))
total_periodos = int(input('Digite o número ... | StarcoderdataPython |
1754541 | ##############################################################################
# Copyright 2020 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# htt... | StarcoderdataPython |
1735337 | <gh_stars>0
import os
from flask import Flask
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
app= Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sq... | StarcoderdataPython |
1641749 | <gh_stars>0
"""
Mask Resolver
-------------
This module provides functionality to resolve and write script masks for ``HTCondor`` jobs
submission.
"""
import logging
import re
from pathlib import Path
import pandas as pd
from pylhc_submitter.htc.utils import COLUMN_JOB_DIRECTORY, COLUMN_JOB_FILE
LOG ... | StarcoderdataPython |
3323144 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 15:19:11 2019
@author: <NAME>
"""
import torch
from torch import nn
from torch.autograd import Variable
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import torch.utils.data as data_utils
import numpy as np
import scip... | StarcoderdataPython |
3240139 | from website.models import Organism, Genome, Tag, TaxID
import os
import shutil
import json
from rest_framework import serializers
class TagField(serializers.StringRelatedField):
def to_internal_value(self, value):
return Tag.objects.get_or_create(tag=value).tag
class TaxidField(serializers.PrimaryKeyRe... | StarcoderdataPython |
3360803 | <gh_stars>0
import logging
log = logging.getLogger('prospecting.process')
import pandas as pd
def clean_data(dataframe, metadata):
log.info("Cleaning data...")
tmp_df = dataframe.copy()
tmp_df = drop_rows_with_na(tmp_df,metadata, copy=False)
tmp_df = derive_to_bool(tmp_df,metadata, copy=False)
t... | StarcoderdataPython |
3310185 | #####
#
# This class is part of the Programming the Internet of Things project.
#
# It is provided as a simple shell to guide the student and assist with
# implementation for the Programming the Internet of Things exercises,
# and designed to be modified by the student as needed.
#
import json
import logging
from ... | StarcoderdataPython |
3330153 | class ModelStub:
# DELETE ME - Remove this class when you load a real model. This only
# exists so the ModelWrapper works when creating an initial project.
"""
A placeholder for a real ML Model. Returns the number of features in each row.
Example:
ModelStub().predict([[1,2],[3,4]]) => [2,2... | StarcoderdataPython |
901 | #!/usr/bin/env python
""" VAPI test """
import unittest
import os
import signal
from framework import VppTestCase, running_extended_tests, \
VppTestRunner, Worker
@unittest.skipUnless(running_extended_tests(), "part of extended tests")
class VOMTestCase(VppTestCase):
""" VPP Object Model Test """
def te... | StarcoderdataPython |
1614310 | <gh_stars>0
helloworldfile = \
"""#include <stdio.h>
int main(){
printf("Hello World!");
return false;
}
"""
mergesortfile = \
"""#include <stdio.h>
#include <stdlib.h>
#define NUM 100
typedef int ElementType;
int False;
/* L = 左边起始位置, R = 右边起始位置, RightEnd = 右边终点位置*/
void Merge( ElementType A[], Element... | StarcoderdataPython |
1609985 | from ..adapters.firebird import FireBird
from ..objects import Expression
from .base import SQLDialect
from . import dialects, sqltype_for
@dialects.register_for(FireBird)
class FireBirdDialect(SQLDialect):
@sqltype_for("text")
def type_text(self):
return "BLOB SUB_TYPE 1"
@sqltype_for("bigint")
... | StarcoderdataPython |
69111 | import FWCore.ParameterSet.Config as cms
process = cms.Process("GEOM")
process.load("SimG4CMS.HcalTestBeam.TB2004GeometryXML_cfi")
process.VisConfigurationService = cms.Service("VisConfigurationService",
Views = cms.untracked.vstring('3D Window'),
ContentProxies = cms.untracked.vstring('Simulation/Core',
... | StarcoderdataPython |
3392421 | """
Modified from SparseConvNet data preparation: https://github.com/facebookresearch/SparseConvNet/blob/master/examples/ScanNet/prepare_data.py
"""
import os
import os.path as osp
import json
import argparse
import multiprocessing as mp
import torch
import plyfile
import numpy as np
import gorilla
G_LABEL_NAMES = [... | StarcoderdataPython |
1626183 | """
Module pdoc provides types and functions for accessing the public
documentation of a Python module. This includes modules (and
sub-modules), functions, classes and module, class and instance
variables. Docstrings are taken from modules, functions and classes
using the special `__doc__` attribute. Docstrings for va... | StarcoderdataPython |
85211 | from deepaccess.ensemble_utils import ensure_dir
from deepaccess.ensemble_utils import act_to_class
from deepaccess.ensemble_utils import fa_to_onehot
from deepaccess.interpret.importance_utils import *
from .CNN import *
from .DeepAccessModel import *
from .train import *
| StarcoderdataPython |
3275104 | <gh_stars>1-10
import array
import math
import os
from os.path import dirname, join
import pytest
from dr_libs import dr_wav
TEST_INPUT_DIR = join(dirname(__file__), "input")
TEST_OUTPUT_DIR = join(dirname(__file__), "output")
TEST_WAV_MONO_48_S16 = "sine-mono-48-s16.wav"
TEST_WAV_MONO_48_S32 = "sine-mono-48-s32.wa... | StarcoderdataPython |
1675140 | ### IMPORT LIBRARIES ###
from matplotlib import style
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas.plotting import table
from datetime import datetime, timedelta
from datetime import date
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm impor... | StarcoderdataPython |
1782933 | <reponame>ahall26/TeamSimulator<filename>scripts/create_team.py
from collections import OrderedDict
from random import Random
from urllib.parse import unquote
from faker import Faker
def create_team(num=1, team_role="Accountant", team_size=Faker().random_int(min=3, max=10),
team_company=Faker().last_... | StarcoderdataPython |
33761 | <reponame>cotobadesign/cotoba-agent-oss
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to u... | StarcoderdataPython |
3325674 | """Minimal Bokeh Hello World Example"""
from bokeh.models import Div
from bokeh.plotting import curdoc
app = curdoc()
model = Div(text="<h1>Hello Bokeh World from .py Code File</h1>", sizing_mode="stretch_width")
app.add_root(model)
| StarcoderdataPython |
89134 | __author__ = 'kevinorr'
"""
This was my attempt at the first part of Q2 in a Google challenge about maximising the number of bunnies in train cars...
It passed the 'verify' section - all the tests passed.
"""
from collections import Counter
def answer(x):
"""
sort the list and find out what the mode would ... | StarcoderdataPython |
1683913 | <reponame>kubex909/Python-course-SI
import numpy as np
def bubbleSort(data):
lenght=len(data)
swapped= True
while (swapped == True):
swapped= False
for i in range(lenght-1):
if data[i]>data[i+1]:
data[i], data[i+1] = data[i+1], data[i]
swappe... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.