id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
6597504 | # Copyright 2022 The TensorFlow Authors. 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
374264 | <reponame>flty/python<gh_stars>0
#!/usr/bin/python3
# -*- coding: utf8 -*-
#-- CHEASHEET -----------------------------------------------------------------#
# HOWTO: http://sublimetext.info/docs/en/reference/syntaxdefs.html
# REGEX: http://manual.macromates.com/en/regular_expressions
# Syntax Definition
syntax = {
... | StarcoderdataPython |
9643673 | <gh_stars>0
"""
author: <NAME>
all tasks to run are included in this file
"""
import os
import time
import threading
from cv2 import cuda_BufferPool
import RPi.GPIO as GPIO
from flask import Flask, render_template, redirect
import go_to_bed
### constants ###
MIN_DELAY = 10 # delay for tasks... | StarcoderdataPython |
5141483 | # Copyright (c) 2017 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE
from unittest import mock
from django.contrib.auth.models import User
from django.urls import reverse
import promgen.templatetags.promgen as macro
from promgen import models, prometheus
from promgen.tes... | StarcoderdataPython |
3235326 | from ..app import Blueprint
from scanner.core.plugincall import callfunction
user = Blueprint('user', __name__)
plugin=callfunction()
@user.route("/home",methods=["get","post"])
def home():
return str(plugin.pocscan("http://cn.changhong.com/"))
| StarcoderdataPython |
9785661 | from math import log10
from numpy.core.shape_base import block
from utility_functions import PSNR, PSNRfromL1, local_to_global, make_coord, ssim3D, str2bool, ssim, PSNRfromMSE
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.distributed as dist
import torch.multiprocessing as mp
i... | StarcoderdataPython |
8004845 | import numpy as np
class KMeans():
"""Implementation of the KMeans Algorithm"""
def __init__(self, n_cluster, max_iter=100, e=0.0001):
"""constructor
Args
----
- n_cluster(int): "k" in K-Means
- max_iter(int): Maximum number of iterations to consider before re... | StarcoderdataPython |
6628221 | import unittest
from guiengine import *
def initpygame():
pygame.init()
pygame.display.set_mode((800, 600))
class TestEventBus(unittest.TestCase):
def gen_cb(self, number):
def cb(data):
if data == 1:
self.called[number] = True
return cb
def setUp(self... | StarcoderdataPython |
5135925 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
host = ''
port = 6666
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
while True:
conn, addr = sock.accept()
while True:
data = conn.recv(3)
print data
if not data:
... | StarcoderdataPython |
370462 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-28 17:56
from __future__ import unicode_literals
from django.db import migrations
import taggit_autosuggest.managers
class Migration(migrations.Migration):
dependencies = [
('blog', '0010_post_slug'),
]
operations = [
migr... | StarcoderdataPython |
187013 | from . import views
from django.urls import path,include
app_name = "book"
urlpatterns = [
path('', views.index, name = 'homepage'),
path('add',views.create_book,name = "book-add"),
path('register',views.register,name = 'register'),
path('login',views.login_user, name = 'login'),
path('logout',vie... | StarcoderdataPython |
8189675 | from unittest.mock import patch
import pytest
from prediction_techniques.neural_networks import mlp
from gamestonk_terminal import load
@pytest.fixture
def stock():
def load_stock(name, start='2020-06-04'):
return load(['-t', name, '-s', start], '', '', '', '')
return load_stock
@pytest.mark.e2e... | StarcoderdataPython |
6409535 | <reponame>BlazingMammothGames/MammothBlenderTools<gh_stars>1-10
import bpy
from bpy.props import *
from bpy_extras.io_utils import ExportHelper
import json
import base64
import struct
import bmesh
import zlib
import os
# adapted from https://github.com/Kupoman/blendergltf
# helper class for dealing with vertices
clas... | StarcoderdataPython |
11259850 | """Tests for the Somfy config flow."""
import asyncio
import logging
import time
import pytest
from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.config import async_process_ha_core_config
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.helpers.network im... | StarcoderdataPython |
330672 | from keras.preprocessing.text import Tokenizer, one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras import layers
import numpy as np
from numpy import array
from keras.layers import Dense
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.m... | StarcoderdataPython |
5023164 | <reponame>ghn/django-template<filename>{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/config/settings/heroku.py
from . import get_env_variable
from .base import * # noqa
import django_heroku
django_heroku.settings(locals())
DEBUG = False
| StarcoderdataPython |
8131633 | '''
(c) University of Liverpool 2019
All rights reserved.
@author: neilswainston
'''
# pylint: disable=broad-except
# pylint: disable=invalid-name
# pylint: disable=wrong-import-order
from rdkit.Chem import inchi, rdmolfiles
from liv_ms.data import rt
import pandas as pd
def get_rt_data(filename, num_spec=1e32, re... | StarcoderdataPython |
3276244 | # Generated by Django 3.1.3 on 2020-12-05 19:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('store', '0005_auto_20201203_1948'),
]
operations = [
migrations.RenameField(
model_name='branchcategory',
old_name='bc_type'... | StarcoderdataPython |
1887203 | <gh_stars>0
#!/usr/bin/python
"""Calculates optical properties of large hexagonal ice grains.
This file calculates the optial properties (single scattering albedo, assymetry
parameter, mass absorption coefficient and extinction, scattering and absorption cross
sections) for ice grains shaped as arbitrarily large hexa... | StarcoderdataPython |
1613074 | import os
import mimetypes
import arrow
def datetimeformat(date_str):
"""Filtro para melhorar a exibição de informações do tipo data"""
dt = arrow.get(date_str)
return dt.humanize()
def file_type(key):
"""Filtro"""
file_info = os.path.splitext(key)
file_extension = file_info[1]
try:
return mimetypes.types_ma... | StarcoderdataPython |
9613192 | <reponame>haifangong/TRFE-Net-for-thyroid-nodule-segmentation
import argparse
import glob
import os
import random
import socket
import time
from datetime import datetime
import numpy as np
# PyTorch includes
import torch
import torch.optim as optim
# Tensorboard include
from tensorboardX import SummaryWriter
from to... | StarcoderdataPython |
5123661 | <filename>helpers/redownload.py
import json
import operator
from pathlib import Path
import textwrap
from datetime import date
import re
def getCurrentMemoryUsage():
''' Memory usage in Bytes '''
import psutil
import os
process = psutil.Process(os.getpid())
return process.memory_info().rss
def r... | StarcoderdataPython |
244893 | """
1628. Design an Expression Tree With Evaluate Function
Medium
Given the postfix tokens of an arithmetic expression, build and return the binary expression tree that represents this expression.
Postfix notation is a notation for writing arithmetic expressions in which the operands (numbers) appear before their op... | StarcoderdataPython |
8021956 | from datetime import datetime, timedelta
from collections import OrderedDict
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse, reverse_lazy
from django.db.models import Count, Avg, Min, Max
from django.http import Http404, HttpResponseRedirect
from django.shortcuts... | StarcoderdataPython |
11259184 | # coding=utf-8
# Copyright 2020 The Google Research 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 applicab... | StarcoderdataPython |
5032691 | from pypykatz.commons.common import KatzSystemArchitecture, WindowsMinBuild, WindowsBuild
from pypykatz.commons.win_datatypes import ULONG, LUID, KIWI_GENERIC_PRIMARY_CREDENTIAL, POINTER, DWORD, PVOID, PSID, GUID, DWORD64
from pypykatz.lsadecryptor.package_commons import PackageTemplate
class CloudapTemplate(PackageTe... | StarcoderdataPython |
89703 | <reponame>CoderHongKong/python-study
# -*- coding: UTF-8 -*-
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name:
# Purpose:
#
# Author: hekai
#-------------------------------------------------------------------------------
arrs = ['a', 'b', 'c', ['x... | StarcoderdataPython |
1734695 | #bin/usr/python3
#Created by : @e_f_l_6_6_6
import os
os.system('pip install colorama')
os.system('pip install hashlib')
time.sleep(2)
import hashlib
import colorama
import time
from bunner import *
import random
banner()
os.system('termux-open-url https://t.me/elf_security_cyber')
time.sleep(5)
w... | StarcoderdataPython |
1608458 | #!/usr/bin/env python
""" this node publishes the frame of the ball with a parent of the camera_depth_optical_frame"""
from __future__ import print_function
import rospy
import tf2_ros
import tf2_geometry_msgs
import geometry_msgs.msg
if __name__ == '__main__':
rospy.init_node('my_static_tf2_broadcaster')
b... | StarcoderdataPython |
6448074 | #!/usr/bin/python
import matplotlib
import numpy as np
class Angle(object):
def __init__(self, a):
self.__list = [[1, 0], [0, 1], [-1, 0], [0, -1]]
self.__index = 0
self.angle = [1, 0]
for i in [0, 1, 2, 3]:
if a == self.__list[i]:
self.__index = i
... | StarcoderdataPython |
6612368 | from time import sleep
data = input('\033[1;30;107mDigite algo:\033[m ')
print('\033[1;35;107mIDENTIFICANDO PROPRIEDADES...\033[m')
sleep(3)
print('\n\033[1;30;107mÉ string.\033[m')
if data.isnumeric():
print('\033[1;30;107mÉ numérico.\033[m')
if data.isalpha():
print('\033[1;30;107mÉ alfabético.\033[m')
if dat... | StarcoderdataPython |
3201424 | from .client import Client
from .consts import *
class EttAPI(Client):
def __init__(self, api_key, api_seceret_key, passphrase, use_server_time=False):
Client.__init__(self, api_key, api_seceret_key, passphrase, use_server_time)
# query accounts
def get_accounts(self):
return self._reque... | StarcoderdataPython |
1754912 | <filename>host/sds.py
#! /usr/bin/python
import os
import sys
import numpy
import time
from subprocess import Popen, PIPE
import random
GPA = tuple([ 0 + i for i in range(32) ])
GPB = tuple([ 32 + i for i in range(16) ])
GPC = tuple([ 64 + i for i in range(16) ])
GPD = tuple([ 96 + i for i in range(16) ])
GPE = tuple(... | StarcoderdataPython |
8168283 | # This file was automatically created by FeynRules 2.3.36
# Mathematica version: 11.3.0 for Linux x86 (64-bit) (March 7, 2018)
# Date: Wed 24 Feb 2021 15:52:48
from object_library import all_orders, CouplingOrder
QCD = CouplingOrder(name = 'QCD',
expansion_order = 99,
hierarc... | StarcoderdataPython |
1631461 | from flask import Flask
from flask import g
app = Flask(__name__)
# 保存一些临时的数据, 配合钩子函数使用
@app.route("/")
def index():
print(g.isvip)
g.name = 'zhangsan'
print(g.name)
return 'ok'
@app.before_request # 在每一次请求之前执行
def request_before():
vip = True # 从数据库查,需要很多代码实现
g.isvip = vip
@app.before_fi... | StarcoderdataPython |
4861610 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
""" Implements JSON text format support. """
f... | StarcoderdataPython |
4865516 | <reponame>jramirez857/projects<gh_stars>10-100
import mlflow
from nbconvert import HTMLExporter
from sklearn_evaluation import NotebookIntrospector
def store_report(product, params):
if params['track']:
nb = NotebookIntrospector(product)
run_id = nb['mlflow-run-id'].strip()
# https://nbco... | StarcoderdataPython |
3245108 | <reponame>miracvbasaran/PipelineDP<filename>examples/movie_view_ratings/run_without_frameworks.py
# Copyright 2022 OpenMined.
#
# 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://w... | StarcoderdataPython |
318543 | from niftivis.niftivis import make_thumbnails
__version__ = "2021.04.13"
__all__ = ["make_thumbnails"]
| StarcoderdataPython |
3240152 | from flask_mail import Mail, Message
import configparser, jinja2, re
# ENQUIRY TYPES
# Connect
# 0 General enquiry
# 1 General feedback
# Partnership
# 2 Collaboration and partnership
# 3 Marketing and sponsorship
# 4 Student-alumni relations
# Outreach
# 5 Event publicity
# 6 Recruitment notice
# Help
#... | StarcoderdataPython |
11383794 | <filename>fa_test.py
# -*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
from utils.scripts_utils import dynamic_memory_allocation, basic_train_parser
from utils.config_manager import Config
from ctc_segmentation import ctc_segmentation, determine_utterance_segments
from ctc_segmentation import CtcSegment... | StarcoderdataPython |
5132061 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
import re
import shutil
import subprocess
from collections import defaultdict
import subprocess
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import SingleLetterAlphabet
impo... | StarcoderdataPython |
252158 | <gh_stars>0
from django.test import TestCase
from django.urls import reverse, resolve
from purchase import views
class PurchaseUrlsTest(TestCase):
'''
Test all urls in the purchase applciation
'''
def test_new_order_resolved(self):
'''
Test new order url
'''
url = reve... | StarcoderdataPython |
291941 | from flask_restx import fields
from . import api
sampledata = api.model(
"SampleData",
{
"id": fields.Integer(),
"date": fields.String(),
"channel": fields.String(),
"country": fields.String(),
"os": fields.String(),
"impressions": fields.Integer(),
"clic... | StarcoderdataPython |
11258858 | # ============================================================================
# ============================================================================
# Copyright (c) 2021 <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... | StarcoderdataPython |
9694046 | <filename>aiohappybase/__init__.py
"""
AIOHappyBase, a developer-friendly Python library to interact asynchronously
with Apache HBase.
"""
__all__ = [
'DEFAULT_HOST',
'DEFAULT_PORT',
'Connection',
'Table',
'Batch',
'ConnectionPool',
'NoConnectionsAvailable',
]
from . import _load_hbase_thr... | StarcoderdataPython |
1826700 | <reponame>rahulsingh50/Computer-Vision-Projects<gh_stars>1-10
import cv2
import numpy as np
def sketch(frame):
'''
Generate sketch given an image
@paramaters: frame
'''
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_blur = cv2.GaussianBlur(gray, (5,5), 0)
edges = cv2.Canny(gray_blur, 10, 70)
ret, mask = ... | StarcoderdataPython |
3363771 | import numpy as np
import plotly.express as px
class Simulation:
def __init__(self):
self.init_temp = 1
self.n_x = 40
self.n_y = 40
self.reset()
def reset(self):
self.heat_sources = []
self.T = np.ones((self.n_x * self.n_y)) * self.i... | StarcoderdataPython |
3488205 | <gh_stars>0
# Faça um Programa que peça a idade e a altura de 5 pessoas, armazene cada informação no seu respectivo vetor. Imprima a idade
# e a altura na ordem inversa a ordem lida.
lista_idade, lista_altura = [], []
for i in range(1, 6):
idade = int(input('Informe a idade: '))
lista_idade.append(idade)
... | StarcoderdataPython |
1712126 | # Copyright (c) 2019 StackHPC Ltd.
#
# 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 |
1803570 | <gh_stars>10-100
#!/usr/bin/env python
import os, subprocess, sys, time, bz2
from random import randint
"""Check if bowtie2 is installed. Stops programm if not"""
def check_bowtie2():
platform = sys.platform.lower()[0:3]
try:
if platform == 'win':
bowtie2 = subprocess.Popen(['where', 'b... | StarcoderdataPython |
3225605 | <gh_stars>0
import threading
import random
import time
#used help from: http://rosettacode.org/wiki/Dining_philosophers#Python !!
class Philosopher(threading.Thread):
running = True
def __init__(self, name, l_fork, r_fork):
threading.Thread.__init__(self)
self.name = name
self.l_f... | StarcoderdataPython |
5065485 | # coding: utf-8
"""
"""
import pytest
import io
import sys
from sampledb.logic.instruments import create_instrument
import sampledb.__main__ as scripts
from ..test_utils import app_context
@pytest.fixture
def instruments():
return [
create_instrument(name, 'Example Instrument Description')
for n... | StarcoderdataPython |
232827 | <filename>source/MCPM/__init__.py
from os import path
from .version import __version__
MODULE_PATH = path.abspath(__file__)
for i in range(3):
MODULE_PATH = path.dirname(MODULE_PATH)
| StarcoderdataPython |
165622 | from egpo_utils.egpo.egpo import EGPOTrainer
from egpo_utils.human_in_the_loop_env import HumanInTheLoopEnv
from egpo_utils.train.utils import initialize_ray
initialize_ray(test_mode=False)
def get_function(ckpt):
trainer = EGPOTrainer(dict(
env=HumanInTheLoopEnv,
# ===== Training =====
... | StarcoderdataPython |
9739917 | import os
from logger import log
class DocumentReader(object):
def __init__(self, document_path):
self.document_path = document_path
if not os.path.isfile(self.document_path):
raise SystemExit("File not found: %s" % self.document_path)
log.info("Reading file: %s.", s... | StarcoderdataPython |
5004791 | """
# !/usr/bin/env python
-*- coding: utf-8 -*-
@Time : 2022/3/15 下午6:27
@Author : Yang "Jan" Xiao
@Description : RNN
"""
import torch
import torch.nn as nn
from torchaudio.transforms import MFCC
class RNN(nn.Module):
def __init__(self, input_size, num_classes, hidden_size=512, n_layers=1):
super(RN... | StarcoderdataPython |
64860 | # Copyright 2021 Sony Group Corporation.
#
# 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 ... | StarcoderdataPython |
32190 | class PrivilegeNotHeldException(UnauthorizedAccessException):
"""
The exception that is thrown when a method in the System.Security.AccessControl namespace attempts to enable a privilege that it does not have.
PrivilegeNotHeldException()
PrivilegeNotHeldException(privilege: str)
PrivilegeNotHeldExcepti... | StarcoderdataPython |
11386719 | #!/usr/bin/python3
import sys
from sys import argv, exit, stderr
import os
import nbformat as nbf
import yaml
from collections import OrderedDict
import numpy as np
import re, ast
def represent_dictionary_order(self, dict_data):
return self.represent_mapping('tag:yaml.org,2002:map', dict_data.items())
def setup_y... | StarcoderdataPython |
11208327 | from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from filebrowser_safe.functions import convert_filename
from django.utils.translation import ugettext_lazy as _
from django.db import models
from zipfile import ZipFile
from StringIO import StringIO
import os
from mezza... | StarcoderdataPython |
3224093 | <reponame>cassiobotaro/Rivendell<filename>learningopencv/avivideo.py
import sys
import cv2
ENTER = 13
capture = cv2.VideoCapture('Lupi.AVI')
if capture is None:
print("Video not found.", file=sys.stderr)
sys.exit(1)
captured, frame = capture.read()
key = 0
while captured and key != ENTER:
cv2.imshow('v... | StarcoderdataPython |
323636 | <reponame>ikota3/images_to_pdf
import os
import fire
import img2pdf
from validator import is_dir, is_extension, is_bool
from typing import Union
from utils import natural_keys, show_info, setup_logger, append_prefix, UserResponse, ask
logger = setup_logger(__name__)
class PDFConverter():
def __init__(
... | StarcoderdataPython |
88275 | import typing
from smartcast import is_dict, is_int, is_bool, is_str, is_float, is_union, is_list
def test_is_union():
assert is_union(typing.Optional[int])
assert is_union(typing.Union[int, str])
def test_is_list():
assert is_list(typing.List)
assert is_list(typing.List[int])
assert is_list(list)... | StarcoderdataPython |
1865103 | <gh_stars>10-100
import numpy as np
class NormalizeImagePreprocessor:
"""
Converts image from byte format (values are integers in {0, ..., 255} to normalized float format (values are
floats in the interval [0, 1].
"""
def __init__(self):
pass
def __call__(self, image):
image =... | StarcoderdataPython |
4902035 | #-*-coding:utf8-*-
import sys, time, traceback, random, os, json
from threading import Thread
from subprocess import *
from Queue import Queue
def run_cmd(cmd):
print cmd
p = Popen(cmd,shell=True)
p.wait()
return
# cmd upload local files to remote files
def scp2remote(srcFile, node, destFile):
c... | StarcoderdataPython |
8055106 | <gh_stars>0
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "${prefix}/include".split(';') if "${prefix}/include" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;std_msgs;controller_manager;control_toolbox;pluginlib;hardware_interface;transmission_int... | StarcoderdataPython |
195098 | <reponame>vector-ai/vectorhub
from ...import_utils import *
if is_all_dependency_installed('audio-encoder'):
import librosa
import soundfile as sf
import tempfile
import shutil
import os
from urllib.request import urlopen, Request
from urllib.parse import quote
import io
import numpy as np
from ...base impor... | StarcoderdataPython |
11388826 | # encoding: UTF-8
"""
Created on 2018/09/20
@author: Freeman
布林带过滤策略:
参数组合:(, , )
每次交易n手
"""
import numpy as np
import talib
from pymongo import MongoClient, ASCENDING
import datetime
from vnpy.trader.vtObject import VtBarData
from vnpy.trader.vtConstant import EMPTY_STRING
from vnpy.trader.app.ctaStr... | StarcoderdataPython |
6409301 | <filename>other/dingding/dingtalk/api/rest/OapiEduCircleTopiclistRequest.py<gh_stars>0
'''
Created by auto_sdk on 2020.11.02
'''
from dingtalk.api.base import RestApi
class OapiEduCircleTopiclistRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.biz_type = None
self.class_id = None
... | StarcoderdataPython |
4824099 | <gh_stars>1-10
#!/usr/bin/env python2
# Copyright (c) 2017 The Zcash developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test Proton interface (provides AMQP 1.0 messaging support).
#
# Requirements:
# Python library ... | StarcoderdataPython |
1749293 | <filename>Chapter 8/large_shirts.py
def make_shirt(size = 'L', message = 'I love Python'):
print(f'This shirt is size: {size}, and has a message: {message}.')
# large shirt and a medium shirt with the default message
make_shirt()
make_shirt(size = 'M')
# shirt of any size with a different message.
make_shirt(size... | StarcoderdataPython |
11300509 | import argparse
import json
import sys
import signal
import logging
from datetime import datetime
from os import path
IMU_TOPIC = "imu".encode('utf-8')
def signal_handler_exit(sig, frame):
print('* msb_imu: bye')
sys.exit(0)
def dump_config_file(config : dict):
with open(config['dump_config_file'], 'w')... | StarcoderdataPython |
4822737 | <filename>src/modules/apputils/config/__init__.py
# 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 Licens... | StarcoderdataPython |
3266859 | <gh_stars>1-10
import os, sys, math
neighbours = [(0,-1), (-1,0), (1,0), (0,1)]
def main():
input_values = []
lows = []
with open("input.txt", 'r') as file:
for line in file.readlines():
input_values.append([int(x) for x in line if(x !='\n')])
#print(input_values)
for i in range(len(input_values)):
... | StarcoderdataPython |
1915638 | from flask_wtf import FlaskForm
from wtforms.validators import InputRequired, DataRequired, Optional, Email
from wtforms import BooleanField, StringField, RadioField, SelectField
class SubscribeForm(FlaskForm):
email = StringField('Email', [InputRequired(), Email()])
| StarcoderdataPython |
1838198 | <filename>patterns/behavioral/chain_of_responsibility.py
from abc import abstractmethod
from typing import List
class Handler:
"""Abstract handler."""
def __init__(self, successor: "Handler") -> None:
self._successor: Handler = successor
def handler(self, request: int) -> None:
if not se... | StarcoderdataPython |
314035 | <filename>data/python_scripts/teams.py
import json
f = open('games.json', 'r')
data = json.load(f)
teamDict = {}
for game in data:
team1ID = str(game["team1_id"])
team2ID = str(game["team2_id"])
team1Name = game["team1_name"]
team2Name = game["team2_name"]
teamDict[team1ID] = team1Name
teamDi... | StarcoderdataPython |
11338703 | from distutils.core import setup
setup(
name='streamed_job',
version='0.1.0',
author='<NAME>',
author_email='<EMAIL>',
packages=['streamed_job'],
scripts=['bin/run_streamed_job.py'],
url='http://www.fakeurl.nowhere',
license='LICENSE.txt',
description='Run a process with a timeout a... | StarcoderdataPython |
9762455 | <reponame>HardwareDesignWithPython/HDPython
import unittest
import os
import shutil
from HDPython import *
import HDPython.examples as ahe
from HDPython.tests.helpers import remove_old_files
import HDPython.tests.core_tests as core_t
import HDPython.tests.ex1 as ex1
import HDPython.tests.RamHandler as RamHandler
... | StarcoderdataPython |
1825572 | <filename>LeetCode_Solutions/804. Unique Morse Code Words.py
# Source : https://leetcode.com/problems/unique-morse-code-words/
# Author : foxfromworld
# Date : 03/11/2021
# First attempt
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
code = [".-","-...","-.-.","-..",".","..... | StarcoderdataPython |
8191582 | # -*- coding: utf-8 -*-
from random import choice
import pickle
import threading
import time
import jieba
from gensim.models.doc2vec import Doc2Vec, LabeledSentence
from sklearn.externals import joblib
import numpy as np
from bert_serving.client import BertClient
from retrieval_documents import Retrieval
from fuzzy... | StarcoderdataPython |
1910396 | <gh_stars>10-100
import re
from exporters.persistence import PERSISTENCE_LIST
class PersistenceConfigDispatcher(object):
def __init__(self, uri):
self.uri = uri
self.persistence_dispatcher = self.get_module_from_uri()
def get_module_from_uri(self):
persistence_regexes = {m.uri_regex:... | StarcoderdataPython |
8182869 | <reponame>metamapper-io/metamapper
# Generated by Django 3.0.10 on 2022-03-09 19:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sso', '0001_initial'),
('authentication', '0002_workspace_team_members'),
]
... | StarcoderdataPython |
11373801 | '''
Module which runs the game
'''
def main():
print('Game started!') | StarcoderdataPython |
3272507 | <reponame>Raspberry-Pi-Club/Dr.Reddy<filename>sqllite_test.py<gh_stars>0
import sqlite3
SQLConnection = sqlite3.connect('C:\wamp\www\Piyu-UI\database\interface.db')
c = SQLConnection.cursor()
#Getting Insertion time
insertionTime = ''
for row in c.execute("SELECT datetime('now','localtime')"):
insertionTime = ro... | StarcoderdataPython |
327499 | <gh_stars>1-10
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
TODO: add short description
"""
from .queries import *
from .result import *
from .simbad_votable import *
mirrors = {'harvard': 'http://simbad.harvard.edu/simbad/sim-script?script=',
'strasbourg': 'http://simbad.u-strasbg.fr... | StarcoderdataPython |
5097880 | import json
import getpass
import shortuuid # type: ignore
from datetime import datetime
from functools import lru_cache
from collections import defaultdict
from typing import Any, Dict, Generator, Generic, List, Optional, Set, Tuple, Union
from followthemoney.types import registry
from nomenklatura.entity import CE
... | StarcoderdataPython |
1957231 | <gh_stars>10-100
import os
import sys
import numpy as np
from scipy import spatial as ss
import pdb
import cv2
from utils import hungarian,read_pred_and_gt,AverageMeter,AverageCategoryMeter
gt_file = 'val_gt_loc.txt'
pred_file = 'tiny_val_loc_0.8_0.3.txt'
flagError = False
id_std = [i for i in range(3110,3610,1)]
id... | StarcoderdataPython |
1787247 | def unify_faces(face_data):
ans = face_data['faceLandmarks']
for mark in ans:
ans[mark]['x'] -= face_data['faceRectangle']['left']
ans[mark]['x'] *= 1000 / face_data['faceRectangle']['width']
ans[mark]['y'] -= face_data['faceRectangle']['top']
ans[mark]['y'] *= 1000 / face_data['... | StarcoderdataPython |
376371 | <reponame>uit-cosmo/fpp-closed-expresions<gh_stars>1-10
"""
Excess time statisitics
In all cases, the signal z should have been normalized as (z-<z>)/z_rms
"""
import numpy as np
import mpmath as mm
import warnings
def eT(X, g):
"""
Returns the fraction of time above threshold for the normalized shot noise p... | StarcoderdataPython |
3392999 | <filename>src/aioprometheus/asgi/starlette.py
from starlette.requests import Request
from starlette.responses import Response
from aioprometheus import REGISTRY, render
async def metrics(request: Request) -> Response:
"""Render metrics into format specified by 'accept' header.
This function first attempts t... | StarcoderdataPython |
395764 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-02-05 08:12
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
mi... | StarcoderdataPython |
8007009 | <reponame>remram44/find_projections
import matplotlib
import matplotlib.pyplot as plt
def print_projection(pr):
print pr.get_class(),pr.get_att1(),\
pr.get_att2(),pr.get_total(),\
pr.get_att1_start(),pr.get_att1_end(),\
pr.get_att2_start(),pr.get_att2_end(),\
pr.get_pos(),pr.get... | StarcoderdataPython |
6473360 | <reponame>chenrui333/cartridge-cli
from utils import run_command_and_get_output
def test_version_command(cartridge_cmd):
for version_cmd in ["version", "-v", "--version"]:
rc, output = run_command_and_get_output([cartridge_cmd, version_cmd])
assert rc == 0
assert 'Tarantool Cartridge CLI v... | StarcoderdataPython |
4835758 | <filename>sicwebapp/page/migrations/0014_rename_package_careerful_package.py
# Generated by Django 4.0 on 2022-05-22 20:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('page', '0013_careerful'),
]
operations = [
migrations.RenameField(
... | StarcoderdataPython |
68480 | <filename>pymed/pymed.py
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import json
import re
import textwrap
from copy import deepcopy
from .constants import PMD
from Bio import Entrez, Medline
try:
from itertools import izip_longest
except ImportError:
from itertools im... | StarcoderdataPython |
3456088 | <reponame>mtk-watch/android_external_v8
# Copyright 2006-2009 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above c... | StarcoderdataPython |
9633161 | # flake8: noqa: F405
import re
import pytest
from rich.console import Console
from rich.table import Table
from pyinaturalist.formatters import *
from test.sample_data import *
# Lists of JSON records that can be formatted into tables
TABULAR_RESPONSES = [
j_comments,
[j_controlled_term_1, j_controlled_term_... | StarcoderdataPython |
1847754 | #coding:utf-8
import unittest
from cvtron.modeling.detector.slim_object_detector import SlimObjectDetector
class TestDetector(unittest.TestCase):
def test_detector(self):
sod = SlimObjectDetector()
sod.set_label_map('/media/sfermi/Programming/project/web/cvtron/cvtron-serve/cvtron-serve/tmp/img_d_b... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.