id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
84219 | from aerosandbox.common import ExplicitAnalysis
import aerosandbox.numpy as np
import subprocess
from pathlib import Path
from aerosandbox.geometry import Airplane
from aerosandbox.performance import OperatingPoint
from typing import Union, List, Dict
import tempfile
import warnings
class AVL(ExplicitAnalysis):
"... | StarcoderdataPython |
190034 | <filename>scanpy/external/pp/_harmony_integrate.py
"""
Use harmony to integrate cells from different experiments.
"""
from typing import Optional
from anndata import AnnData
def harmony_integrate(
adata: AnnData,
key: str,
basis: str = "X_pca",
adjusted_basis: str = "X_pca_harmony",
**kwargs,
):... | StarcoderdataPython |
3374085 | from LECA.consensus import consensus_ages
import cPickle as pickle
import sys, os
### This program will create the consensus (mode) age calls
### by trimming databases that oversplit co-orthologous groups.
###
### **Note: if this script does not find the file LDORESULTS, it will
### silently calculate a consensus wit... | StarcoderdataPython |
1790474 | <reponame>camille1874/FinQA
#coding:utf8
import jieba
import jieba.posseg as pseg
import os,sys
'''
initialize jieba Segment
'''
def jieba_initialize():
jieba.load_userdict(os.path.dirname(os.path.split(os.path.realpath(__file__))[0])+'/resources/QAattrdic.txt')
jieba.initialize()
'''
Segment words by jieba... | StarcoderdataPython |
1791801 | # coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
__version__ = "0.8.4"
| StarcoderdataPython |
3333173 | from decimal import Decimal
class TradeResult(object):
def __init__(
self,
received: float,
remains: float,
order_id: int,
funds: {},
):
self.received = received
self.remains = remains
self.order_id = order_id
self.fun... | StarcoderdataPython |
1614999 | # coding: utf-8
from __future__ import unicode_literals
import logging
from wxpy.utils import handle_response
from .chat import Chat
logger = logging.getLogger(__name__)
class User(Chat):
"""
好友(:class:`Friend`)、群聊成员(:class:`Member`),和公众号(:class:`MP`) 的基础类
"""
def __init__(self, raw, bot):
... | StarcoderdataPython |
37709 | """
Start local development server
"""
import argparse
import logging
import shlex
import subprocess
import webbrowser
from contextlib import suppress
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from ssl import wrap_socket
from tempfile import NamedTemporaryFile
from threading ... | StarcoderdataPython |
143464 | <reponame>Anancha/OpenCV-Python-Tutorial
# -*- coding: utf-8 -*-
# @Time : 2017/7/17 下午12:03
# @Author : play4fun
# @File : 画圆圈.py
# @Software: PyCharm
"""
画圆圈.py:随机覆盖,不同颜色,
"""
from time import sleep
import cv2
import numpy as np
def click_event(event, x, y, flags, param):
'''
用左键点击屏幕,打印坐标
:param... | StarcoderdataPython |
1738802 | <filename>adv/zace.py
from core.advbase import *
from slot.d import *
from slot.a import *
def module():
return Zace
class Zace(Adv):
a1 = ('s',0.2)
conf = {}
conf['slots.a'] = Resounding_Rendition()+Jewels_of_the_Sun()
conf['acl'] = """
`dragon
`s3, not self.s3_buff
`s1
... | StarcoderdataPython |
177963 | <gh_stars>0
# Creating a program that uses the min() without using the min() function. Without knowing the user inputted values of num1 and num2, create a program that outputs the lower value without using the min()
num1 = int(input('Enter a value: '))
num2 = int(input('Enter a value: '))
if num1 <= num2:
print(n... | StarcoderdataPython |
78445 | import pandas as pd
import itertools
cat_features = ['col1', 'co2', 'col3', 'col4', 'col5']
def combine_colums(df, cat_features)
df_combine = pd.DataFrame(index=df.index)
for colA, colB in itertools.combinations(cat_features, 2):
new_col_name = '_'.join([colA, colB])
... | StarcoderdataPython |
1601702 | <filename>blog_app/api/errors/invalid_arguments_for_creation_error.py
class InvalidArgumentsForCreationException(Exception):
code = 422
def __init__(self, errors):
Exception.__init__(self)
self.errors = errors
def to_dict(self):
return {
"success": False,
"e... | StarcoderdataPython |
3293784 | <filename>Deployment Files/WeatherWear/Combos/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from . import WeatherWear as ww
import tensorflow as tf
import requests, ast
from users.models import UserProfile
from os import path
from google.cloud ... | StarcoderdataPython |
4827109 | value = "not-none"
<caret>if value is None:
print("None")
else:
print("Not none") | StarcoderdataPython |
3251015 | from django.shortcuts import render
from django.contrib.auth.models import User, Group
from .models import Pytanie
from rest_framework import viewsets
from rest_framework import permissions
from .serializers import UserSerializer, GroupSerializer,PytanieSerializer
# Create your views here.
class UserViewSet(viewsets.M... | StarcoderdataPython |
163786 | """
Code that goes along with the Airflow located at:
http://airflow.readthedocs.org/en/latest/tutorial.html
"""
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from taxi import get_taxi_data, transform_taxi_data, load_taxi_da... | StarcoderdataPython |
3348016 | # <NAME>
# 1351040
import numpy as np
import cv2
class LBP:
def compute(self, img, keypoints):
img = np.asarray(img)
img = (1 << 7) * (img[0:-2, 0:-2] >= img[1:-1, 1:-1]) \
+ (1 << 6) * (img[0:-2, 1:-1] >= img[1:-1, 1:-1]) \
+ (1 << 5) * (img[0:-2, 2:] >= img[1:-1, 1:-1]) \
... | StarcoderdataPython |
3394342 | """Aula 7 - Operadores aritméticos.
+ = Soma
- = Subtração
* = Multiplicação
/ = Divisão
** = Potenciação
// = Divisão Inteira
% = Resto da Divisão
Ordem de Precedência dos Operadores
1° = ()
2° = **
3° = *, /, //, %
4° = +, -
Dica: end = '' (não quebra a linha)
\n (Quebra a linha)"""
... | StarcoderdataPython |
144998 | import os
import re
import sys, time
import numpy as np
final=''#global vars to save results of op
fresult=''#global vars to save results of for
fcall=''#global vars to save results of call
def check(newcontext):
nc=newcontext
#TODO:cannot deal with multiple problems,need help
lk=nc.count('(')
rk=nc.count(')')
l... | StarcoderdataPython |
3272468 | import boto3
from EOSS.aws.utils import dev_client, prod_client, user_input, pprint
class Cluster:
def __init__(self, dev=False):
if dev:
self.client = dev_client('ecs')
else:
self.client = prod_client('ecs')
self.cluster_name = 'evaluator-cluster'
def get... | StarcoderdataPython |
174275 | import signnow
import json
if __name__ == "__main__":
signnow.Config(
client_id="0fccdbc73581ca0f9bf8c379e6a96813",
client_secret="<KEY>",
base_url="https://api-eval.signnow.com",
)
# Enter your own credentials
username = ""
password = ""
# Create the access_token for ... | StarcoderdataPython |
3219315 | <filename>3rdparty/pymdown-extensions/tools/gen_gemoji.py
"""Generate gemoji data."""
import sys
import os
import json
current_dir = os.path.dirname(os.path.abspath(__file__))
U_JOIN = 0x200d
U_VARIATION_SELECTOR_16 = 0xfe0f
U_EXTRA = (U_JOIN, U_VARIATION_SELECTOR_16)
if sys.maxunicode == 0xFFFF:
# For ease of su... | StarcoderdataPython |
199448 | <gh_stars>1-10
from .base import AST
from .nodes import *
from .suite import *
| StarcoderdataPython |
44529 | <filename>achievements/admin.py
from models import Achievement, Category, Trophy, CollectionAchievement, Progress, ProgressAchievement, Task, TaskAchievement, TaskProgress
from django.contrib import admin
from django import forms
from django.core.exceptions import ValidationError
from django.contrib.admin.widgets impor... | StarcoderdataPython |
4837738 | print(Hello world
)
| StarcoderdataPython |
1752935 |
# ===========================================================
# File Name: pixel_distance.py
# Author: <NAME>, Georgia Institute of Technology
# Creation Date: 04-25-2019
#
# This file is made available under
# the terms of the BSD license (see the COPYING file).
# ===============================================... | StarcoderdataPython |
172135 | <filename>tests/test_entropy_encoders/test_arithmetic_coding.py
from typing import List, Sequence
import hypothesis.strategies as st
from entropy_encoders import arithmetic_coding
from hypothesis import given
EOF = "\n"
text_strategy = st.text(st.characters(blacklist_characters=EOF),
max_size=... | StarcoderdataPython |
1721391 | <filename>Utils/custom_data_augmenter.py<gh_stars>1-10
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
def rotate_segmentation_data(images, masks, percent):
num_of_images = images.shape[0]
# include the origional instances to the final list of augmented data
images_rotated, mask... | StarcoderdataPython |
1672971 | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.optim.lr_scheduler import StepLR
import torchvision
import torchvision.transforms as transforms
from torchvision import models
import tensorly as tl
import tensorly
from itert... | StarcoderdataPython |
1655603 | <gh_stars>1-10
"""
Useful semantics "macro" instructions built on top of
the primitives.
"""
from __future__ import absolute_import
from cdsl.operands import Operand
from cdsl.typevar import TypeVar
from cdsl.instructions import Instruction, InstructionGroup
from base.types import b1
from base.immediates import imm64
f... | StarcoderdataPython |
1704870 | from player import Player
class Batter(Player):
''' A batter and all of his stats as collected from various means and
manipulated in the base Player class most likely
'''
def __init__(self, name, name_display, id):
"""
Return a batter object
:param name:
:param name_... | StarcoderdataPython |
1762156 | <reponame>raza-al-pakistani/raza-al-pakistani--v20022.3.1
# A part of NonVisual Desktop Access (NVDA)
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
# Copyright (C) 2007-2021 NV Access Limited, Babbage B.V.
from typing import Dict
from utils.displayString import Dis... | StarcoderdataPython |
1614611 | import pygame
class Score():
"""表示分数的类"""
def __init__(self, init_settings, screen):
"""导入屏幕和设定"""
self.screen = screen
self.init_settings = init_settings
"""导入图片资源"""
self.images = [
pygame.image.load('resources/sprites/font_048.png'),
... | StarcoderdataPython |
3336300 | # -*- coding: utf-8 -*-
"""
reNamer, Author <NAME>(https://github.com/Eshleron/reNamer)
Requirements:
- json
- os
- pathlib
- random
- sys
- time
- PyQt5
Python:
- 3.5.4
This file (reName.py) is part of reNamer.
"""
import json
import os
from pathlib import Path
import random
import sys
import time... | StarcoderdataPython |
117045 | <filename>examples/distributed_dl/distributed_ml.py
from ray_on_aml.core import Ray_On_AML
from azureml.core import Run
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch.nn.functional as F
... | StarcoderdataPython |
1629107 | from celery.utils.log import get_task_logger
from wikimetrics.api import CohortService
from report import ReportNode
from metric_report import MetricReport
__all__ = ['MultiProjectMetricReport']
task_logger = get_task_logger(__name__)
class MultiProjectMetricReport(ReportNode):
"""
A node responsbile for r... | StarcoderdataPython |
1610238 | #!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing access to third party resources.
Attributes:
LCSI (dict): mapping from verb to a set of classes
BROWN_CLUSTERS (dict): mapping from word to a set of
Brown clusters
CONNS (set): set of explcit connectives
CONNTOK2CONN (defaul... | StarcoderdataPython |
3373813 | import collections
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
USE_WANDB = False # if enabled, logs data on wandb server
class ReplayBuffer:
def __init__(self, buffer_limit):
self.buffer = collections.deque(maxlen=buffer_li... | StarcoderdataPython |
3368821 | <gh_stars>0
import os
import unittest
import k3ut
import k3utfjson
import json
dd = k3ut.dd
this_base = os.path.dirname(__file__)
class TestUTFJson(unittest.TestCase):
def test_load(self):
self.assertEqual(None, k3utfjson.load(None))
self.assertEqual({}, k3utfjson.load('{}'))
# load u... | StarcoderdataPython |
1776911 | <reponame>robert-giaquinto/survae_flows
import argparse
import pickle
import numpy as np
import torch
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
from sklearn.gaussian_process.kernels import RBF, ConstantKernel, Matern
from model.u... | StarcoderdataPython |
3393970 | from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
context = {
'text': 'hello zhiliao, hello ketang'
}
return render_template('index.html', **context)
@app.template_filter('cut')
def cut(value):
value = value.replace('hello', 'welcome')
ret... | StarcoderdataPython |
1731773 | """Implements Document Object Model Level 2 Style Sheets
http://www.w3.org/TR/2000/PR-DOM-Level-2-Style-20000927/stylesheets.html
"""
__all__ = ['MediaList', 'MediaQuery', 'StyleSheet', 'StyleSheetList']
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from .medialist import *
from .mediaquery import *
from .st... | StarcoderdataPython |
3335642 | <reponame>tsbxmw/leetcode
# 给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei),请你判断一个人是否能够参加这里面的全部会议。
# 示例 1:
# 输入: [[0,30],[5,10],[15,20]]
# 输出: false
# 示例 2:
# 输入: [[7,10],[2,4]]
# 输出: true
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/meeting-rooms
# 著作权归领扣网络所有。商业转载请联系官方授权,非商... | StarcoderdataPython |
1731094 | from dataclasses import dataclass
from datetime import date, datetime
import mock
from pdfminer.layout import LTChar, LTCurve, LTFigure, LTImage, LTTextBoxHorizontal, LTTextLineHorizontal
from typing import List
from rdr_service.services.consent import files
from tests.helpers.unittest_base import BaseTestCase
class... | StarcoderdataPython |
3292176 | <reponame>pratiman-91/proplot<gh_stars>100-1000
#!/usr/bin/env python3
"""
Utilities related to matplotlib text objects.
"""
import matplotlib.patheffects as mpatheffects
import matplotlib.text as mtext
from . import ic # noqa: F401
def _transfer_text(src, dest):
"""
Transfer the input text object propertie... | StarcoderdataPython |
68236 | <reponame>kb2ma/openvisualizer
# Copyright (c) 2010-2013, Regents of the University of California.
# All rights reserved.
#
# Released under the BSD 3-Clause license as published at the link below.
# https://openwsn.atlassian.net/wiki/display/OW/License
import logging
from openvisualizer.utils import buf2int, hex2buf... | StarcoderdataPython |
3213267 | <gh_stars>1-10
"""
# f_it package
"""
from .fit import FIt
from .version import version as __version__ # noqa: F401
from .version import version_tuple as __version_info__ # noqa: F401
__all__ = ["FIt"]
| StarcoderdataPython |
62665 | <reponame>sandeep-krishna/100DaysOfCode
'''
<NAME>'s birthday is in next month. This time he is planning to invite N of his friends. He wants to distribute some chocolates to all of his friends after party. He went to a shop to buy a packet of chocolates.
At chocolate shop, each packet is having different number of cho... | StarcoderdataPython |
115408 | <reponame>americanpezza/reqmapper
from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
import progressbar
class SemanticChecker:
def __init__(self, req, minScore=0.75, maxScore=1.0):
self.requirements = req
self.similarities = []
self.threshold = minScore
... | StarcoderdataPython |
172148 | #
# 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"); you may not us... | StarcoderdataPython |
1611170 | from app.core import App
DEFAULT_CYKIT_ADDRESS = 'localhost'
DEFAULT_CYKIT_PORT = 5151
| StarcoderdataPython |
31775 | <reponame>jasondunsmore/python-heatclient
# 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... | StarcoderdataPython |
167352 | <gh_stars>0
class NaturalNumbers:
def __init__(self):
pass
def get_first_n_for(self, n): # Ejemplo
"""
Obtener los primeros n naturales en una lista con for
"""
first_n = [] # Se declara una lista donde almacenaremos los numeros
for i in range(n): # Se itera sobr... | StarcoderdataPython |
4817214 | <reponame>maorp/NeuralGraph<filename>utils/sdf_utils.py<gh_stars>100-1000
import numpy as np
def scale_grid(xyz, x_scale, y_scale, z_scale, disp=1.0):
X, Y, Z = xyz
X = X*x_scale
Y = Y*y_scale
Z = Z*z_scale
points = np.concatenate((X[np.newaxis, ...], Y[np.newaxis, ...], Z[np.newaxis, ...]), axis=... | StarcoderdataPython |
151240 | import dash
from utils.code_and_show import example_app
dash.register_page(
__name__, description="Compare three regression models to predict revenue"
)
filename = __name__.split("pages.")[1]
notes = """
#### Plotly Documentation:
- [Visualize regression in scikit-learn](https://plotly.com/python/ml-regre... | StarcoderdataPython |
1746779 | <reponame>feiwencaho/sharezone
from api.service import dao
from api.utils import map
from api.const import GeoTableId
from django.db import transaction
def publish(user, **kwargs):
"""
发布需求
:param user:
:param kwargs:
:return:
"""
with transaction.atomic():
demand = dao.demand.crea... | StarcoderdataPython |
1645970 | '''
<NAME>
difficulty: 35%
run time: 0:00
answer: 168
***
115 Counting Block Combinations II
NOTE: This is a more difficult version of Problem 114.
A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different ... | StarcoderdataPython |
1613077 | from __future__ import annotations
from copy import deepcopy
from typing import Tuple, Callable
import numpy as np
from IMLearn import BaseEstimator
def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray,
scoring: Callable[[np.ndarray, np.ndarray, ...], float],
... | StarcoderdataPython |
3289236 | from rlil.nn import RLNetwork
from .approximation import Approximation
class VNetwork(Approximation):
def __init__(
self,
model,
optimizer,
name='v',
**kwargs
):
model = VModule(model)
super().__init__(
model,
... | StarcoderdataPython |
3399307 | <gh_stars>1000+
import json
from django.test import TestCase
from suggestion.models import Study
from suggestion.algorithm.abstract_algorithm import AbstractSuggestionAlgorithm
from suggestion.algorithm.skopt_bayesian_optimization import SkoptBayesianOptimization
class RandomSearchAlgorithmTest(TestCase):
def set... | StarcoderdataPython |
1638549 | from ConnectSignal.Lambda import (
connect_slider_moved_abstract,
connect_slider_released_abstract,
connect_def_str_lineedit_abstract,
connect_name_change_abstract
)
from ConnectSignal.ConnectMacros import (
connect_colour,
connect_fill_pattern,
connect_dash,
connect_o_arrow,
connec... | StarcoderdataPython |
3317589 | <filename>code/sample_1-2-8.py
x = [int(i) for i in input().split()]
print(x)
| StarcoderdataPython |
37638 | """
迭代器 --> yield
"""
class CommodityController:
def __init__(self):
self.__commoditys = []
def add_commodity(self, cmd):
self.__commoditys.append(cmd)
def __iter__(self):
index = 0
yield self.__commoditys[index]
index += 1
yield self.__commoditys[in... | StarcoderdataPython |
1725304 | #encoding:utf8
from pymongo import MongoClient
from flask import Flask, request, jsonify
DB_COUNT = 32
dbs = {}
DBNAME = "replay"
COLLECTION = "data"
def _hash(hash_str):
s = 0
for i in range(1, len(hash_str)+1):
c = ord(hash_str[i-1])
s = s + c * i
return (s % DB_COUNT) + 1
def _get_coll... | StarcoderdataPython |
3265877 | from django.contrib.auth.backends import ModelBackend
from app.core.models import Customer
class CustomerUserBackend(ModelBackend):
def authenticate(self, username=None, password=<PASSWORD>, t_password=None, **kwargs):
UserModel = Customer
if username is None:
username = kwargs.get(Use... | StarcoderdataPython |
101774 | <filename>pwtools/test/test_parameter_study.py
import os
import numpy as np
from pwtools import comb, batch, common, sql
from pwtools.test.tools import all_types_equal, assert_all_types_equal
from .testenv import testdir
pj = os.path.join
def check_key_in_file(lines, key, file_target):
"""If line "key=<value>" is ... | StarcoderdataPython |
3254011 | """
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n,
representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, ... | StarcoderdataPython |
1622322 | import numpy
from scipy.misc import imread
from matplotlib import pyplot as plt
from PIL import Image
from PIL import ImageDraw
def upload_recognized_text_lines(file_orf):
color = 0
heights = []
blocks = []
min_x = 100000
min_y = 100000
max_x = 0
max_y = 0
lines = []
for line i... | StarcoderdataPython |
70031 | from django.conf.urls import url
from . import constants, views # isort:skip
urlpatterns = [
url(
r'^create-alias/$',
views.create_alias_view,
name=constants.CREATE_ALIAS_URL_NAME,
),
url(
r'^aliases/$',
views.CategoryListView.as_view(),
name=constants.CA... | StarcoderdataPython |
3350825 | <reponame>rmaguire31/sisr
"""PyTorch Dataset utilities for SiSR super-resolution dataset
"""
import os
import glob
import random
import logging
import torchvision.transforms.functional as TF
from PIL import Image
from torch.utils.data import Dataset as BaseDataset
__all__ = 'Dataset', 'JointRandomTransform'
logg... | StarcoderdataPython |
3230274 | <filename>reservation_rest_api.py
from flask import Flask, request
from reservation_service import get_qnode, read_data, register, delete_namespace
import json
import logging
from tabulate import tabulate
app = Flask(__name__)
ALLOWED_EXTENSIONS = {'xls', 'yaml', 'csv', 'json'}
logger = logging.getLogger()
logger.se... | StarcoderdataPython |
3244742 | # (c) 2012, <NAME> <<EMAIL>>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible i... | StarcoderdataPython |
1784955 | import numpy as np
from basics.orig import update_S, update_V, solve_U, E
from utils.math_utils import U_converged
from utils.metrics import nmi_acc
def iteration(X, U, V, labels, p, logger):
N = len(X)
C = len(V)
gamma, epsilon = p.gamma, p.epsilon
capped = p.capped or True
S = np.ones((N, C)... | StarcoderdataPython |
191355 | <gh_stars>0
"""Config flow for MitBlod integration."""
import pymitblod
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.typing import ConfigType
from homeassistant.config_entries import ConfigFlow, CONN_CLASS_CLOUD_POLL
from homeassistant.con... | StarcoderdataPython |
1701074 |
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pylab as plt
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from AI_scientist.util import plot_matrices, make_dir, get_args, Early_Stopping, record_data
from AI_scientist.settings.filepath import variational_model_... | StarcoderdataPython |
26280 | # Copyright (c) 2021 <NAME>. All Rights Reserved.
import pymel.core as pm
import piper_config as pcfg
import piper.mayapy.util as myu
import piper.mayapy.convert as convert
import piper.mayapy.attribute as attribute
from .rig import curve # must do relative import in python 2
def get(node_type, ignore=None, search... | StarcoderdataPython |
136750 | <gh_stars>10-100
import random as rand
class Qbit:
def __init__(self, index, prev_1q_gate):
self.index = index
self.prev_1q_gate = prev_1q_gate
self.gate_dict = {'T':('Y','X'), 'Y':('X','T'), 'X': ('T','Y')}
def h(self):
self.prev_1q_gate = 'H'
return self.index
d... | StarcoderdataPython |
126099 | CLIENT_ID = "mxxgwertsps7ry9zsdkk7r3"
CLIENT_SECRET = "<KEY>" | StarcoderdataPython |
42810 | <filename>hawkbot/__main__.py
from . import bot
from configparser import ConfigParser
import sys
def get_config(filename):
config = ConfigParser()
config.read(filename)
return config
def main():
config = get_config(sys.argv[1])
bot.config = config
bot.run(config['login']['token'])
if __name__ == '__main__':... | StarcoderdataPython |
161022 | <gh_stars>0
# Standard libraries
import io
import os
import re
from setuptools import setup, find_packages
from typing import List
# Constants
PATH_ROOT = os.path.dirname(__file__)
def _load_requirements(path_dir: str, file_name: str = "requirements.txt", comment_char: str = "#") -> List[str]:
"""Load requiremen... | StarcoderdataPython |
1661479 | <reponame>codepipe/netapp-ansible<gh_stars>10-100
#!/usr/bin/python
import sys
import json
from ansible.module_utils import ntap_util
try:
from NaServer import *
NASERVER_AVAILABLE = True
except ImportError:
NASERVER_AVAILABLE = False
if not NASERVER_AVAILABLE:
module.fail_json(msg="The NetApp Manag... | StarcoderdataPython |
1635984 | <reponame>GabrielMMelo/turing-machine<filename>src/tm.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from .reader import Reader
class Tm():
"""Classe que representa uma máquina de Turing determinística para computação de funções numéricas."""
def __init__(self, filename):
"""
... | StarcoderdataPython |
72089 | from functools import partial
from django.db import models
from model_utils.managers import InheritanceManager
from coberturas_medicas.models import Cobertura
from core.models import Persona, Profesional
from dj_utils.mixins import ShowInfoMixin
from dj_utils.models import BaseModel, uploadTenantFilename
class Pac... | StarcoderdataPython |
3324992 | <gh_stars>0
import googlemaps
from datetime import datetime
import time
gmaps = googlemaps.Client(key='<KEY>')
arrTime = int(datetime(2019, 8, 5, 7, 0, 0).timestamp())
destination = 'Universidad De Los Andes, Bogota Colombia'
direction = 'Cr 50 # 106-06, Bogota Colombia'
start_time = time.time()
loc = gmaps.geocode... | StarcoderdataPython |
1672736 | import numpy as np
def convolution2d_multichannel(image, kernel, bias):
_, y, x = image.shape
# kernel shape: (output channels, input channels, x, y)
chO, chI, _, _ = kernel.shape
new_image = np.empty([chO, y, x])
# for adding the images when num channel out < channel in
layer_image = np.emp... | StarcoderdataPython |
1674916 | from pyexcelerate import Workbook
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # data is a 2D array
wb = Workbook()
wb.new_sheet("sheet name", data=data)
wb.save("output.xlsx")
| StarcoderdataPython |
1618344 | '''
Matheus estava conversando com a sua noiva via mensagem de texto, quando ela lhe enviou a seguinte mensagem:
1-4-3
Ele não entendeu a mensagem, então ele perguntou o que isso significava, e ela respondeu que era 'I Love You" e logo ele percebeu
que cada número separado por um ' - ' é a quantidade de caracteres d... | StarcoderdataPython |
3328457 | class Idol:
"""Represents an Idol/Celebrity."""
def __init__(self, **kwargs):
self.id = kwargs.get('id')
self.full_name = kwargs.get('fullname')
self.stage_name = kwargs.get('stagename')
self.former_full_name = kwargs.get('formerfullname')
self.former_stage_name = kwargs.... | StarcoderdataPython |
1742359 | <reponame>dangervon/ironic<filename>ironic/tests/unit/drivers/modules/ibmc/test_management.py
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | StarcoderdataPython |
1789444 | <reponame>phzwart/qlty
import torch
import einops
def weed_sparse_classification_training_pairs_2D(tensor_in, tensor_out, missing_label, border_tensor):
"""
After tensors have been unstitched, we want want to be able to remove patches that have no data.
To this extent, we inspect every patch and remove any... | StarcoderdataPython |
4839253 | <reponame>deeuu/supriya
import collections
from supriya import CalculationRate
from supriya.ugens.Filter import Filter
class BRF(Filter):
"""
A 2nd order Butterworth band-reject filter.
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> b_r_f =supriya.ugens.BRF.ar(source=source)
>>>... | StarcoderdataPython |
3270063 | <gh_stars>0
from plaster.tools.pipeline.pipeline import PipelineTask
from plaster.run.prep.prep_result import PrepResult
from plaster.run.sim.sim_result import SimResult
from plaster.run.survey_nn.survey_nn_params import SurveyNNParams
from plaster.run.survey_nn.survey_nn_worker import survey_nn
class SurveyNNTask(Pi... | StarcoderdataPython |
110013 | def checkio(f, g):
def call(function, *args, **kwargs):
try: return function(*args, **kwargs)
except Exception: return None
def h(*args, **kwargs):
value_f, value_g = call(f, *args, **kwargs), call(g, *args, **kwargs)
status = ""
if (value_f is None and value_g... | StarcoderdataPython |
3344212 | <filename>services/spider/worker/__init__.py
# -*- coding: utf-8 -*-
import os
from celery import Celery
##################
# Celery配置
from kombu import Queue
from webs import create_app
class CeleryConfig(object):
# 任务与劣化为json,从Celery4.0开始,默认序列化器将为json
task_serializer = 'json'
# 结果序列化为json
result... | StarcoderdataPython |
3287833 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import TYPE_CHECKING
from cdm.enums import CdmObjectType
from cdm.enums.cdm_operation_type import OperationTypeConvertor, CdmOperationType
from cdm.pe... | StarcoderdataPython |
123697 | #!/usr/bin/env python
"""
Copyright (c) 2020-End_Of_Life
See the file 'LICENSE' for copying permission
"""
# import standard library required
import argparse
import sys
# import tool required
from route.route import route
from route.execute import execute
from chemsynth.chemsynth import Chemsynth, Chem... | StarcoderdataPython |
113399 | #!/usr/bin/python3
import hid
import traceback
hid_max_pkt_size = 64
if __name__ == '__main__':
import argparse
import sys
import binascii
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--descriptor', help='Print Descriptor', action='store_true')
args = parser.parse_args(... | StarcoderdataPython |
1692103 | from PoolThread import PoolThread
from Stage import Stage
from Task import Task
| StarcoderdataPython |
154787 | import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues()
self.description = "GUI to profilers such as Valgrind"
self.defaultTarget = 'master'
def setDependencies(self):
self.runtimeDependencies["libs/qt5/qtbase"] = None
self.... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.