id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1659993 | <filename>lightbus_examples/ex01_quickstart/another_service/check_password.py
# File: ./another_service/check_password.py
# Import our service's bus client
from bus import bus
# Call the check_password() procedure on our auth API
valid = bus.auth.check_password(username="admin", password="<PASSWORD>")
# Show the res... | StarcoderdataPython |
1662661 | import rsa
def getIntSize(i):
return (i.bit_length() + 7) // 8
def pubkeyToBin(key):
out = bytearray()
out += getIntSize(key.n).to_bytes(4, "little")
out += key.n.to_bytes(getIntSize(key.n), "little")
out += key.e.to_bytes(getIntSize(key.e), "little")
return out
def pubkeyFromBin(... | StarcoderdataPython |
177651 | <reponame>ruijis/buildsimhub_python_api
from .model_action import ModelAction
class HeatingEfficiency(ModelAction):
def __init__(self):
ModelAction.__init__(self, 'heating_all_equip')
self._measure_name = 'HeatingEff'
self._lower_limit = 0
self._upper_limit = 1
self._measur... | StarcoderdataPython |
154823 |
from .views import yaml_to_html
try:
from django.urls import path
urlpatterns = [
path('api-doc/', yaml_to_html, name="api-doc"),
]
except:
from django.conf.urls import url
urlpatterns = [
url(r'^api-doc/', yaml_to_html, name="api-doc"),
]
| StarcoderdataPython |
4809658 | """Base class for source collector unit tests."""
import io
import json
import logging
import pathlib
import unittest
import sys
import zipfile
from typing import Union
from unittest.mock import AsyncMock, PropertyMock, patch
import aiohttp
from base_collectors import MetricCollector
MODULE_DIR = pathlib.Path(__fi... | StarcoderdataPython |
3375214 | <reponame>linbinbin92/data_driven_microstructure_paper_material<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <EMAIL>
"""
import os
import glob
import subprocess
import time
# bashCommand = "sbatch job.sh"
def CreaJobFileCluster(dest):
os.chdir(dest)
cdir_origin=os.getcwd()
print... | StarcoderdataPython |
4832462 | <reponame>z-yin/CityLink
#!/usr/bin/env python
# coding: utf-8
import os
import csv
import time
import jieba
import pprint
import re, string
import numpy as np
from gensim import corpora
# from threading import Semaphore, Thread, Event # for multi-processing
from sklearn.manifold import TSNE
from sklearn.cluster impo... | StarcoderdataPython |
167003 | # Code based on https://github.com/yaringal/ConcreteDropout
# License:
# MIT License
#
# Copyright (c) 2017
#
# 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 wi... | StarcoderdataPython |
1721273 | <filename>flirt/hrv/features/nl_features.py
import numpy as np
from flirt.hrv.features.data_utils import DomainFeatures
class NonLinearFeatures(DomainFeatures):
def __init__(self, emb_dim: int = 2):
self.emb_dim = emb_dim
def __get_type__(self) -> str:
return "Non-Linear"
def __generate... | StarcoderdataPython |
3247859 | """
Project Module.
"""
import os
from optparse import Values
from pathlib import Path
from typing import List, Optional, Any, Dict, Callable, TYPE_CHECKING
# from pineboolib.fllegacy.flaccesscontrollists import FLAccessControlLists # FIXME: Not allowed yet
from PyQt5 import QtWidgets
from pineboolib.core.utils im... | StarcoderdataPython |
119512 | <reponame>manish1822510059/Python-1000-program
inc = 1
num = 1
for x in range (5,0,-1):
for y in range(x,0,-1):
print(" ",end="")
print(str(num)*inc)
num += 2
inc += 2 | StarcoderdataPython |
3340890 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" a robot
"""
import gevent
# from gevent import socket
import struct
import time
from net import baseclient
from dao.stock_def import EtfInfo
from pb import base_pb2
from pb import error_pb2
from pb import pq_quota_pb2
from pb import quotation_def_pb2
from pb import... | StarcoderdataPython |
1668721 | import zlib
from rdkit import Chem
from rdkit.Chem.PropertyMol import PropertyMol
import torch
import numpy as np
from modules.mol import conformation_generation, get_mol_coordinate, get_mol_type_one_hot
from modules.surface import MoleculeAtomsToPointNormal
def generate_and_encode(smi):
"""
Generate the co... | StarcoderdataPython |
80991 | import yaml
import pytest
from unittest import mock
import kubernetes
from kubernetes.config.config_exception import ConfigException
from mlflow.projects import kubernetes as kb
from mlflow.exceptions import ExecutionException
from mlflow.entities import RunStatus
def test_run_command_creation(): # pylint: disable... | StarcoderdataPython |
1757735 | import logging
import sys
LOGGER_NAME = 'aqueduct'
log = logging.getLogger(LOGGER_NAME)
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [Flow] [pid:%(process)d] %(message)s')
ch = logging.StreamHandler(sys.stderr)
ch.setFormatter(formatter)
log.addHandler(ch)
| StarcoderdataPython |
93665 | <reponame>gecko17/project-sailor
from unittest.mock import patch, Mock, call
import pytest
from sailor.assetcentral.equipment import Equipment
from sailor.assetcentral.location import Location, LocationSet
from sailor.assetcentral import constants
@pytest.fixture
def mock_url():
with patch('sailor.assetcentral.... | StarcoderdataPython |
1647223 | <filename>pymodaq_plugins/hardware/picoquant/histomode.py
# Demo for access to TimeHarp 260 Hardware via TH260LIB.DLL v 3.1.
# The program performs a measurement based on hard coded settings.
# The resulting histogram is stored in an ASCII output file.
#
# <NAME>, PicoQuant GmbH, February 2018
import time
import ctype... | StarcoderdataPython |
164127 | ## interaction / scripts / create_translation_repository.py
'''
This script will pre-calculate the translation operators for a given bounding
box, max level, and frequency steps for a multi-level fast multipole algorithm.
This can take hours to days depending on the number of threads available, size
of bounding box, n... | StarcoderdataPython |
96241 | from flask import request, render_template_string, session, abort, Response
import pathlib
from io import StringIO
class Watch_HTML():
endpoints = ["/webwatch"]
endpoint_name = "page_webwatch_html"
endpoint_access_level = 0
def __init__(self, fhdhr, plugin_utils):
self.fhdhr = fhdhr
... | StarcoderdataPython |
1719504 | <reponame>alexmanuele/Indizio<filename>filter_graphml.py
import networkx as nx
import argparse
argparser = argparse.ArgumentParser(description='Filter GraphML file to explore relationships.')
requiredNamed = argparser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', help='Input GraphML f... | StarcoderdataPython |
3363613 | # -*- coding:utf-8 -*-
import os
import traceback
import time
import numpy as np
#os.environ['KERAS_BACKEND'] = "theano"
#os.environ['THEANO_FLAGS'] = "device=cpu"
from utils.preprocess import *
from utils.load_data import *
import csv
from utils.Extract_Features import Extract_Features
from keras.models import model... | StarcoderdataPython |
1701871 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from base.AwsService import AwsService
class S3(AwsService):
def set_serviceConfig(self, config):
self.set_s3Service(config)
def get_serviceConfig(self):
ret=self.get_s3Service()
return ret
def get_s3Service(self):
... | StarcoderdataPython |
3358770 | import pandas as pd
import itertools
from functools import partial
from fastai.callbacks import CSVLogger
def get_config_df(config):
df = pd.DataFrame(list(itertools.product(*config.values())), columns=config.keys())
df.index = [f'model_{i+1}' for i in range(len(df))]
return df
def create_experiment(nm, ... | StarcoderdataPython |
131765 | <gh_stars>1-10
import graphene
from ...tests.utils import assert_no_permission, get_graphql_content
QUERY_CHANNELS = """
query {
channels {
name
slug
currencyCode
}
}
"""
def test_query_channels_as_staff_user(staff_api_client, channel_USD, channel_PLN):
# given
# when
re... | StarcoderdataPython |
1717365 | <reponame>ninasm/M242_Uebungsprojekte
import os, pathlib
def RewriteCsv( fname, outName ):
with open( fname, "r") as input:
lines = input.readlines()
lineNr = 0
values = lines[lineNr].split(',')
while values[0] != 'Sample-Nr':
lineNr+=1
values = lin... | StarcoderdataPython |
1625615 | #------------------------------------------------------------------------------
# Get the status of the color trend report.
# GET /v1/color_trends/{report_name}/trend_report
#------------------------------------------------------------------------------
import os
import json
import requests
from urlparse import urljoi... | StarcoderdataPython |
109303 | """ Use this module for imports to extend the Admin classes
"""
from django.conf import settings
if 'facebook.modules.profile.page' in settings.INSTALLED_APPS:
from facebook.modules.profile.page.admin import PageAdmin
if 'facebook.modules.profile.user' in settings.INSTALLED_APPS:
from facebook.modules.profil... | StarcoderdataPython |
1661872 | <filename>logbunker/apps/backoffice/backend/dependencies/BackofficeContainer.py
from dependency_injector import containers, providers
from logbunker.apps.backoffice.backend.controllers.LogGetController import LogGetController
from logbunker.apps.bunker.controllers.StatusGetController import StatusGetController
from lo... | StarcoderdataPython |
167836 | <reponame>pollen-robotics/reachy_pyluos_hal<filename>reachy_pyluos_hal/reachy.py
"""Reachy wrapper around serial LUOS GateClients which handle the communication with the hardware."""
import sys
import time
import numpy as np
from collections import OrderedDict, defaultdict
from glob import glob
from logging import Lo... | StarcoderdataPython |
91547 | import time
import gex
# pwm frequency sweep
with gex.Client(gex.TrxRawUSB()) as client:
pwm = gex.PWMDim(client, 'dim')
pwm.start()
pwm.set_duty_single(1, 500)
for i in range(2000, 200, -15):
pwm.set_frequency(i)
time.sleep(0.05)
pwm.stop()
| StarcoderdataPython |
3228811 | <filename>clock/db.py
'''
闹钟表
- ID (key)
- USER #id
- CONTENT #闹钟备注
- TYPE #private or group
- C_TIME #默认 时/分
-ONES #一次性闹钟 #默认true
-
CREATE TABLE clocks(
id INTEGER NOT NULL primary key autoincrement,
type CHAR(10),
user INTEGER NOT NULL,
content VARCHAR(20),
c_time TIME ,
ones INTEGER NOT ... | StarcoderdataPython |
3362449 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 26 17:29:54 2020
@author: simon
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial.transform import Rotation as R
def normalise(vector):
return vector / np.sqrt(vector[0]**2 + vector[1]**2 ... | StarcoderdataPython |
179617 | TIMEOUT = 2
| StarcoderdataPython |
3299650 | # Source: https://leetcode.com/problems/house-robber/
# Type: Dynamic Programming
# Time Complexity: O(n)
# Space Complexity: O(n)
## I really suck at DP. Leetcode has marked it at easy. Is it me or Leetcode needs to change its criterias?
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums)... | StarcoderdataPython |
1731146 | import os
from enum import IntEnum
import random
import re
import time
from study_tool.card import Card, CardSide, SourceLocation
from study_tool.card_attributes import CardAttributes
from study_tool.external import googledocs
from study_tool.russian.types import *
from study_tool.russian.word import *
from study_tool.... | StarcoderdataPython |
3707 | #!/usr/bin/env python
import os
import os.path
import yaml
import time
import random
import multiprocessing
import RPi.GPIO as GPIO
from talk import say
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
from adafruit_servokit import ServoKit
Motor1 = {'EN': 27, 'input1': 19, 'input2': 16}
Motor2 = {'EN': 22, 'input1': 2... | StarcoderdataPython |
1738056 | <reponame>mbeckem/tiro
# This module can be used to auto generate tagged unions types for C++.
import cog
from .codegen import camel_to_snake, avoid_keyword, ENV
class Tag:
def __init__(self, name, underlying_type, start_value=None, doc=None):
self.kind = "tag"
self.name = name
self.under... | StarcoderdataPython |
4819132 | def cut_rod(prices, rod_size):
r = s = [0 for i in range(rod_size + 1)]
for j in range(1, rod_size + 1):
max_price = -1
for k in range(1, j + 1):
new_price = 0
if(k < len(prices)):
new_price = prices[k] + r[j - k]
else:
new_pric... | StarcoderdataPython |
21029 | <reponame>beng92/Statify
'''
x Total plays
x Total artists
x Total unique songs
Average song per artist
x Favourite track
Favourite artist (by plays or time)
Favourite album (req. api)
Average/total/unique plays per range
Average/total/unique artists per range
Average/total time listened per range
Favouri... | StarcoderdataPython |
3353511 | <gh_stars>0
import asyncio
import gzip
import json
import os
import random
import re
import string
import tempfile
import logging
import aioboto3
import aiofiles
from tenacity import RetryError, AsyncRetrying, stop_after_attempt, retry_if_exception_type
class AlttprDoor():
def __init__(self, settings=None, spoi... | StarcoderdataPython |
3320182 | <filename>setup.py
"""Setup for the ezkey package."""
import setuptools
with open('README.md') as f:
README = f.read()
setuptools.setup(
author="<NAME>",
author_email="<EMAIL>",
name='ezkey',
license="Apache 2.0",
description='ezkey is a package that allows developers to easily manage locall... | StarcoderdataPython |
1661014 | import asyncio
import nextcord
from nextcord.ext import commands
from ..tools.Embeds import embeds
import uuid
import datetime
import os
from ..tools.Athena import Athena
class team_builder(commands.Cog, embeds):
LOAD = True
NAME = "Team Builder"
def __init__(self, client: Athena):
self.client = ... | StarcoderdataPython |
1642785 | <reponame>trinamic/PyTrinamicMicro
'''
Example using the MAX14912PMB.
This script switches all the outputs to high and then back to low.
Created on 15.02.2021
@author: JH
'''
from pyb import Pin
from PyTrinamicMicro.platforms.motionpy2.modules.max.max14912 import MAX14912
import time
import logging
logger = logging.... | StarcoderdataPython |
86229 | <gh_stars>0
from typing import ClassVar, List, Optional
from ...constants import AclOperation, AclPermissionType, ApiKey, ErrorCode, ResourceType
from ..base import ResponseData
class MatchingAcl:
error_code: ErrorCode
error_message: Optional[str]
resource_type: ResourceType
resource_name: str
r... | StarcoderdataPython |
131945 | #!/usr/bin/env python
from __future__ import division
from past.utils import old_div
import unittest
import os.path
import sys
import numpy
import anuga
from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular_cross
from anuga.shallow_water.shallow_water_domain import Domain
from anuga.abstract_2d_fini... | StarcoderdataPython |
3376726 | # Generated by Django 2.1.1 on 2018-11-22 03:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0003_auto_20181121_2041'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='cell_phone',
... | StarcoderdataPython |
1778983 | """
This file controls all DB setup and session logic.
"""
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from utils import CONFIG, uuid
db_url = CONFIG.get('database',... | StarcoderdataPython |
3272437 | <reponame>Yoooi0/chaturbate-osr
import asyncio
import json
import logging
import math
import random
import re
import requests
import serial
import string
import sys
import time
import websockets
deviceSettings = {
'port': 'COM4',
'interval': 1 / 60,
'range': {
'L0': [0.0, 1.0],
'L1': [0.0, ... | StarcoderdataPython |
161240 | <reponame>lendingblock/lb-py<filename>lendingblock/orders.py
from .component import CrudComponent
class Orders(CrudComponent):
pass
| StarcoderdataPython |
3311804 | <filename>projects/simple_2d_game/main.py
# -*- coding: utf-8-sig -*-
#
# $ brew install hg sdl sdl_image sdl_ttf sdl_mixer portmidi
import sys
import os
import pygame
from pygame.sprite import Group
from settings import Settings
from ship import Ship
from alien import Alien
import game_functions as gf
def run_ga... | StarcoderdataPython |
1645065 | """Platform for sensor integration."""
from __future__ import annotations
import logging
from typing import Final
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (ELECTRIC_POTENTIAL_VOLT, ELECTRIC_CURRENT_AMPERE, POWER_WATT, POWER_KILO_... | StarcoderdataPython |
1658273 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | StarcoderdataPython |
3261503 | <gh_stars>1-10
from rply.词 import 词, 字符位置, BaseBox
Token = 词
SourcePosition = 字符位置 | StarcoderdataPython |
3326396 | import pyspark
from pyspark.sql import SparkSession
from pyspark.sql.types import *
from pyspark.sql.functions import *
# This is our first testing exploration of the data and possible implementations
# Configure spark session
spark = SparkSession\
.builder\
.master('local[2]')\
.appName('accidents... | StarcoderdataPython |
3347631 | <reponame>jarredthejellyfish/lcoin
from datetime import datetime
import imp
from lcoin_wallet import db, login_manager
from flask_login import UserMixin
from itsdangerous import URLSafeTimedSerializer as Serializer
from flask import current_app
@login_manager.user_loader
def load_user(user_id):
return User.query... | StarcoderdataPython |
1766577 | <reponame>t141/scikit-robot
import numpy as np
class Interpolator(object):
def __init__(self):
self.time = 0.0
self.segment_time = 0.0
self.segment = 0
self.segment_num = 0
self.is_interpolating = False
def reset(self, position_list=None,
time_list=None)... | StarcoderdataPython |
150333 | <filename>problem1.py<gh_stars>0
### PROBLEM 1
def main():
print("Name: <NAME>")
print("Favorite Food: Brie Cheese")
print("Favorite Color: Red")
print("Favorite Hobby: Traveling")
if __name__ == "__main__":
main()
#Name: <NAME>
#Favorite Food: Brie Cheese
#Favorite Color: Red
#Favorite Hobby: T... | StarcoderdataPython |
36410 | from __future__ import annotations
import os
import string
import random
import logging
import vapoursynth as vs
from pathlib import Path
from requests import Session
from functools import partial
from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
from typing import Any, Mapping, Callable, Dict, F... | StarcoderdataPython |
1603801 | <gh_stars>1000+
def recite(start, take=1):
pass
| StarcoderdataPython |
3244028 | <reponame>stumpr/py-aws-tools
#!/usr/bin/env python
import boto3, json, argparse
from botocore.exceptions import ProfileNotFound, ClientError
parser = argparse.ArgumentParser(description="Delete policy with specific resource ARN")
parser.add_argument(
'--arn',
type=str,
)
parser.add_argument(
'--assume_role',
... | StarcoderdataPython |
138472 | <gh_stars>1000+
# -----------------
# list comprehensions
# -----------------
# basics:
a = ['' for a in [1]]
#? str()
a[0]
#? ['insert']
a.insert
a = [a for a in [1]]
#? int()
a[0]
y = 1.0
# Should not leak.
[y for y in [3]]
#? float()
y
a = [a for a in (1, 2)]
#? int()
a[0]
a = [a for a,b in [(1,'')]]
#? int()
... | StarcoderdataPython |
1773037 | <reponame>VyomUnadkat/finding-clip-in-movie-using-feature
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 18 11:28:24 2018
@author: vyomunadkat
"""
import numpy as np
from scipy import spatial
#calculating the difference between the f.v.
def mse(imageA, imageB):
err = np.sum((image... | StarcoderdataPython |
1696328 | <gh_stars>0
from typing import *
from electronics_model.PinAssignmentUtil import leaf_circuit_ports, PinName, ConcretePinName
from electronics_model import *
@non_library
class AssignablePinBlock(GeneratorBlock):
"""Provides two features common to microcontrollers:
new_io(tpe): returns a fresh IO port of type tp... | StarcoderdataPython |
44966 | import json
import os
from eg import config
from eg import substitute
from eg import util
from mock import Mock
from mock import patch
PATH_UNSQUEEZED_FILE = os.path.join(
'test',
'assets',
'pwd_unsqueezed.md'
)
PATH_SQUEEZED_FILE = os.path.join(
'test',
'assets',
'pwd_squeezed.md'
)
def _cr... | StarcoderdataPython |
1797239 | <reponame>MerinRose123/celery_caching_example
# Importing LRUcache from celery
from celery.utils.functional import LRUCache
class Config:
DEBUG = False
SERVICE_NAME = 'celery_caching'
REDIS_HOST = "0.0.0.0"
REDIS_PORT = 6379
BROKER_URL = "redis://{host}:{port}/0".format(
host=REDIS_HOST, ... | StarcoderdataPython |
109448 | from django.shortcuts import render, get_object_or_404
from django.views.generic import (TemplateView, DetailView,
ListView, CreateView,
UpdateView,DeleteView,FormView,)
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from ... | StarcoderdataPython |
54798 | <filename>testing/resources/test_pmatrixprint.py
a = PMatrix3D()
a.print()
exit()
| StarcoderdataPython |
139359 | <gh_stars>10-100
class LoginBase():
freeTimeExpires = -1
def __init__(self, cr):
self.cr = cr
def sendLoginMsg(self, loginName, password, createFlag):
pass
def getErrorCode(self):
return 0
def needToSetParentPassword(self):
return 0 | StarcoderdataPython |
3256044 | """
Copyright (c) 2018 <NAME>
Utility functions for reading and writing data files.
For simplicity, each file stores a single JSON object. Admittedly this isn't
great if the files get large, since we need to read the whole thing to get at
any part of it (or to modify any part of it). But in that case, you should
prob... | StarcoderdataPython |
41455 | <filename>bokeh-app/main.py
import pandas as pd
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.models import (Button, CategoricalColorMapper, ColumnDataSource,
HoverTool, Label, SingleIntervalTicker, Slider)
from bokeh.palettes import Spectral6
from ... | StarcoderdataPython |
1656561 | <gh_stars>100-1000
__all__ = []
import torch
from torch import nn
from onnx2torch.node_converters.registry import add_converter
from onnx2torch.onnx_graph import OnnxGraph
from onnx2torch.onnx_node import OnnxNode
from onnx2torch.utils.common import OnnxMapping
from onnx2torch.utils.common import OperationConverterRe... | StarcoderdataPython |
4823085 | """
Module to initiate sight words, place them into managable lists, and call each word at random
"""
import random
sight_list_1 = ['the', 'of', 'and', 'a', 'to', 'in', 'is', 'you', 'that', 'it', 'he', 'was', 'for', 'on', 'are', 'as', 'with', 'his', 'they', 'I', 'at', 'be', 'this', 'have', 'from', 'or', 'one', ... | StarcoderdataPython |
1693852 | import siliconcompiler
# TODO: find pytest-based way to do mocking
import unittest.mock
def test_cli_multi_source():
''' Regression test for bug where CLI parser wasn't handling multiple
source files properly.
'''
chip = siliconcompiler.Chip()
# I think it doesn't matter if these files actually e... | StarcoderdataPython |
1746979 | #!/usr/bin/env python3
import os
from setuptools import find_packages, setup, Extension
CYTHONIZE = True
# We'll cythonize by default since we can rely on Cython being installed at
# install-time: it is a build-requirement, defined in pyproject.toml. If you
# don't want to cythonize, but compile using the .c sources ... | StarcoderdataPython |
35375 | <filename>lc0415_add_strings.py
"""Leetcode 415. Add Strings
Easy
URL: https://leetcode.com/problems/add-strings/
Given two non-negative integers num1 and num2 represented as string,
return the sum of num1 and num2.
Note:
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- ... | StarcoderdataPython |
3311045 | <reponame>cobrab11/black1-bot<gh_stars>1-10
# BS mark.1-55
# /* coding: utf-8 */
# BlackSmith plugin
# acclist_plugin.py
# Coded by: WitcherGeralt (<EMAIL>)
# http://witcher-team.ucoz.ru/
def global_acclist(type, source, body):
adminslist = u'Список администраторов:'
ignorelist = u'Список игнора:'
acclist = u'О... | StarcoderdataPython |
1771551 | <reponame>Timothy-Wangwe/To-do-List-App-Django-
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from accounts.forms import ... | StarcoderdataPython |
179958 | <gh_stars>0
default_app_config = 'rdmo.projects.app_config.ProjectsConfig'
| StarcoderdataPython |
45523 | print(int(input()) - 543)
| StarcoderdataPython |
4806577 | #!/usr/bin/env python
# coding: utf-8
in_file = open('taxon_3.tab', 'r')
out_file_t = open('taxonomy.tsv', 'w')
out_file_t.write('uid | parent_uid | name | rank | sourceinfo | ' + '\n')
next(in_file)
for line in in_file:
line = line.strip('\n')
row = line.split('\t')
parent_id = row[2]
name = row[3]
taxon_id =... | StarcoderdataPython |
4824808 | from rest_framework import serializers
from .models import PingbackNotification
from .models import PingbackNotificationDismissed
class PingbackNotificationSerializer(serializers.ModelSerializer):
i18n = serializers.JSONField(default='{}')
class Meta:
model = PingbackNotification
fields = ('... | StarcoderdataPython |
3303086 | import numpy as np
from scipy.ndimage.filters import gaussian_filter
from scipy.stats import mode
from .libcudawrapper import deskewGPU as deskew
from .util import imread
def threshold_li(image):
"""Return threshold value based on adaptation of Li's Minimum Cross Entropy method.
From skimage.filters.thresho... | StarcoderdataPython |
103585 | #!/usr/bin/env python
from pwn import *
def numbers_from_to(a = 0, b = None):
if b == None:
b = a
return ''.join(str(n) + " " for n in range(a, b + 1))
def binary_search(io, c, nmax, nmin = 0):
if nmin == nmax:
for _ in range(c):
io.sendline(str(nmin))
io.recvline()
io.sendline(str(nmin))
return
mi... | StarcoderdataPython |
111873 | from ccgetusers.generator import GenerateToken
from ccgetusers.customerid import CustomerId
from ccgetusers.users import Users
import sys
def main():
if len(sys.argv) < 4:
print('Must provide CloudCheckr CMx auth endpoint, client id and access key')
print('ccgetusers <cloudcheckr endpoint> <client... | StarcoderdataPython |
3369533 | <reponame>aarcro/django-report-builder<filename>report_builder_demo/urls.py
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url... | StarcoderdataPython |
188914 | frase = "Curso em Video Python"
print(len(frase))# para contar a quatidade de caracteres em frase.
print(frase[3:12])#para separar letras de frase apartir da casa 3 (lembrando que começa de 0 então a posicao e 4) ate a numero 12 sendo que a 12 será excluída.
print(frase[3::2])#Inicia o print da 3 casa da frase até a ... | StarcoderdataPython |
1676163 | <filename>abc158_d.py
S=list(input())
Q=int(input())
T=[]
for _ in range(Q):
q=input()
if q[0]=='1':
S,T=T,S
else:
if q[2]=='1':
T.append(q[4])
else:
S.append(q[4])
print("".join(T[::-1]+S))
| StarcoderdataPython |
1632387 | import sys, os
from socket import *
if(len(sys.argv)>2):
host=sys.argv[1]
port=int(sys.argv[2])
else:
print("Unable to create connection, required parameters 'Host' and/or 'Port' where not provided")
sys.exit(1)
server_address=gethostbyname(host)
connection_socket=socket(AF_INET,SOCK_STREAM)
connection_socket.conn... | StarcoderdataPython |
1640904 | <reponame>henriktao/pulumi-azure
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequenc... | StarcoderdataPython |
1679596 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | StarcoderdataPython |
1705569 | # Create your first MLP in Keras
from keras.models import Sequential
from keras.layers import Dense
import numpy, json
# fix random seed for reproducibility
numpy.random.seed(7)
f = open("matlav", "r")
inp = json.loads(f.read())
f = open("matlov", "r")
outp = json.loads(f.read())
# load pima indians d... | StarcoderdataPython |
1667934 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db.models import AutoField
from django.contrib import admin
from .models import Project, School
class AllFieldsAdmin(admin.ModelAdmin):
@property
def list_display(self):
return [field.name for field in self.model._meta.fields if not isinstance... | StarcoderdataPython |
172755 | <reponame>Jawayria/estore_project<gh_stars>0
from django.urls import path
from rest_framework_simplejwt.views import TokenRefreshView
from .views import LoginView, Signup
app_name = "users"
urlpatterns = [
path("signup/", view=Signup.as_view(), name="signup"),
path("login/", LoginView.as_view(), name="login")... | StarcoderdataPython |
3343622 | import unittest
from aioprometheus.negotiator import negotiate
from aioprometheus.formats import text, binary
class TestNegotiate(unittest.TestCase):
def test_protobuffer(self):
""" check that a protobuf formatter is returned """
headers = (
"proto=io.prometheus.client.MetricFamily;ap... | StarcoderdataPython |
198480 | <filename>MORSEProject/classes/kalman3D.py
import numpy as np
class Kalman3D:
"""
Class that helps estimate current position based on observations.
You need to run update method for calculations to make place
"""
def __init__(self, dt=1/60.0):
"""
Initialize all used matrices.
... | StarcoderdataPython |
130104 | # Copyright (c) Case Western Reserve University 2015
# This software is distributed under Apache License 2.0
# Consult the file LICENSE.txt
# Author: <NAME> <EMAIL>
# Dec 14 2016
# PYTHON 2
import os
import numpy as np
import subprocess as sp
import sys
import time
import datetime as dt
fdate = "20161215"
yr = int(fd... | StarcoderdataPython |
3350715 | <filename>bash_workbench/misc.py<gh_stars>0
import math
def convert_size(size_bytes):
"""https://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor... | StarcoderdataPython |
1686026 | import pytest
import torch
from dreamer.models.action import ActionDecoder
@pytest.mark.parametrize('dist', ['tanh_normal', 'one_hot', 'not_implemented_dist'])
def test_action_decoder(dist):
batch_size = 4
action_size = 10
feature_size = 20
hidden_size = 40
layers = 5
try:
action_dec... | StarcoderdataPython |
82233 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/9/25 21:50
# Author: <NAME>
# @Email : <EMAIL>
# Description:
from uti import ReducedEpsilon
from uti import Status
from solution import Solution
class ColumnGeneration:
def __init__(self, node):
self.node = node
self.rmp = ... | StarcoderdataPython |
3203676 | import os
import collections
import itertools
from . import helpers
__all__ = ('Display',)
class Graphic:
_Visual = collections.namedtuple('Visual', 'dirty ready clean')
__slots__ = ('_io', '_cursor', '_visuals', '_origin', '_width')
def __init__(self, io, cursor):
self._io = io
sel... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.