id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6690974 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from math import log
import operator
import pickle
# Based on ID3 algorithm(适用于标称型数据,即离散值)
'''
ID3 以信息熵的下降速度为选取测试属性的标准,即在每个节点选取还尚未被用来划分的具有最高信息增益的属性作为划分标准,然后继续这个过程,直到生成的决策树能完美分类训练样例。
'''
# 基于信息增益 - 划分数据集前后信息发生的变化
def createDataSet():
dataSet = [
... | StarcoderdataPython |
6587807 | <reponame>oserikov/dream
import logging
from df_engine.core import Context, Actor
from common.dff.integration import condition as int_cnd
logger = logging.getLogger(__name__)
# ....
def example_lets_talk_about():
def example_lets_talk_about_handler(ctx: Context, actor: Actor, *args, **kwargs) -> str:
r... | StarcoderdataPython |
3279330 | # coding=utf-8
"""Sopel Spelling correction module
This module will fix spelling errors if someone corrects them
using the sed notation (s///) commonly found in vi/vim.
"""
# Copyright 2011, <NAME>, yanovich.net
# Copyright 2013, <NAME>, embolalia.com
# Licensed under the Eiffel Forum License 2.
# Contributions from: ... | StarcoderdataPython |
87814 | # Importamos smtplib
import smtplib
# Importamos los modulos necesarios
from email.mime.text import MIMEText
def send_mail(user, pwd, to_who, subjet, message):
# Creamos el mensaje
msg = MIMEText(message)
# Conexion con el server
msg['Subject'] = subjet
msg['From'] = user
msg['To'] = to_who... | StarcoderdataPython |
8078221 | num = int(input('Insira aqui um número (0~9999):'))
#print('A unidade é igual a: {}'.format(num[3]))
#print('A dezena é igual a: {}'.format(num[2]))
#print('A centena é igual a: {}'.format(num[1]))
#print('A milhar é igual a: ()'.format(num[0]))
u = num//1%10
d = num//10%10
c = num//100%10
m = num//1000%10
print('A u... | StarcoderdataPython |
1910106 | import sys
import time
import json
import os
import threading
import Queue
import logging
from sys import stdin, stdout
from datetime import datetime
import pymongo
from nyamuk.nyamuk import *
from nyamuk.event import *
class mqtt_rx_thread(threading.Thread):
def __init__(self, threadID, queueLock, workQueue, stat... | StarcoderdataPython |
11379824 | from erddapClient import ERDDAP_Tabledap
from collections import OrderedDict
from ..waterframe import WaterFrame
def from_erddap(server, dataset_id, variables=None, constraints=None, rcsvkwargs={}, auth=None):
"""
Get a WaterFrame from an ERDDAP server tabledap dataset.
Parameters
----------
... | StarcoderdataPython |
1985258 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from flowai.constants.url import URL
from flowai.constants.model import Model
import requests
import json
from os.path import join
class AppBase(object):
def __init__(self, model_name):
pass
def predict_by_url(self):
pass
def is_valid_api_key(api_... | StarcoderdataPython |
3319777 | import os
import matplotlib.pyplot as plt
import numpy as np
from pyplanscoring.core.calculation import DVHCalculation, PyStructure
from pyplanscoring.core.dicom_reader import PyDicomParser
from pyplanscoring.core.types import Dose3D, DoseUnit
def plot_dvh(dvh, title):
x_label = 'Dose [Gy]'
y_label = 'Volum... | StarcoderdataPython |
322516 | # Copyright 2016 NTT DATA
# 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 b... | StarcoderdataPython |
97592 | <reponame>Mikuana/oops_fhir
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.v3_role_link_status import (
v3RoleLinkStatus as v3RoleLinkStatus_,
)
__all__ = ["v3RoleLinkStatus"]
_resource = _ValueSet.parse_fi... | StarcoderdataPython |
8002724 | """
Copyright (c) 2014-2015, The University of Texas at Austin.
All rights reserved.
This file is part of BLASpy and is available under the 3-Clause
BSD License, which can be found in the LICENSE file at the top-level
directory or at http://opensource.org/licenses/BSD-3-Clause
"""
from blaspy im... | StarcoderdataPython |
290059 | <reponame>pawelkopka/kopf<filename>tests/e2e/conftest.py
import glob
import os.path
import pathlib
import subprocess
import pytest
root_dir = os.path.relpath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
examples = sorted(glob.glob(os.path.join(root_dir, 'examples/*/')))
assert examples # if empty, it... | StarcoderdataPython |
5134983 | <reponame>NIkolayrr/python_fundamentals_exam
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-08-24 11:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cars', '0003_auto_20180823_2305'),
]
... | StarcoderdataPython |
5099464 | # -*- coding: iso-8859-1 -*-
"""
MoinMoin - PHP session cookie authentication
Currently supported systems:
* eGroupware 1.2 ("egw")
* You need to configure eGroupware in the "header setup" to use
"php sessions plus restore"
@copyright: 2005 MoinMoin:AlexanderSchremmer (Thanks ... | StarcoderdataPython |
9691635 | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# MODULE INFORMATIONS ----------------------------------------------------------
DOCUMENTATION = '''
---
module: make
short_description: Perform make
author:
- "<NAME>"
'''
EX... | StarcoderdataPython |
8112571 | <gh_stars>1-10
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import has_request_context, render_temp... | StarcoderdataPython |
5001536 | """Server start parameters."""
from ipaddress import IPv4Address, IPv6Address, ip_address
from typing import NamedTuple, Iterator, Optional
from dzdsu.constants import CONFIG_FILE
__all__ = ['ServerParams']
class ServerParams(NamedTuple):
"""Available server start parameters."""
config: str = CONFIG_FILE... | StarcoderdataPython |
11348340 | # coding=utf-8
'''
Created on 2015-9-24
@author: Devuser
'''
from doraemon.home.pagefactory.pageworker import DevicePageWorker
from doraemon.home.viewmodels.home_left_nav_bar import HomeTaskLeftNavBar
from doraemon.home.viewmodels.home_sub_nav_bar import HomeTaskSubNavBar
from doraemon.home.pagefactory.home_template_p... | StarcoderdataPython |
6517544 | <reponame>deloragaskins/deepchem
# flake8: noqa
try:
from deepchem.metalearning.maml import MAML, MetaLearner
except ModuleNotFoundError:
pass
| StarcoderdataPython |
3313220 | <reponame>bds-ailab/logflow
import unittest
import torch.multiprocessing
from unittest.mock import mock_open, patch
from logflow.relationsdiscover.Saver import Saver
from logflow.relationsdiscover.Model import LSTMLayer
from logflow.relationsdiscover.Result import Result
from logflow.relationsdiscover.Cardinality impor... | StarcoderdataPython |
6614506 | <gh_stars>0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import tempfile
import argparse
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
import pandas a... | StarcoderdataPython |
4999528 | <filename>authors/apps/authentication/tests/test_auth.py
from rest_framework import status
from authors.apps.authentication.tests.base_test import BaseTest
class TestGetUser(BaseTest):
"""Test for the login functionality of the app."""
def test_get_users(self):
token = self.authenticate_user(self.a... | StarcoderdataPython |
2449 | <gh_stars>0
__all__ = ['EnemyBucketWithStar',
'Nut',
'Beam',
'Enemy',
'Friend',
'Hero',
'Launcher',
'Rotor',
'SpikeyBuddy',
'Star',
'Wizard',
'EnemyEquipedRotor',
'CyclingEnemyObject',
... | StarcoderdataPython |
9617493 | ####################################
# Train LBMNet using kitti dataset #
####################################
import os
import cv2
import time
import random
import numpy as np
import torch
from torch import nn
import torch.optim as optim
import torch.nn.utils as torch_utils
from torch.utils.data import D... | StarcoderdataPython |
1730568 | import torch
import torch.nn as nn
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x):
return self.fn(x) + x
class ConvMixer(nn.Module):
def __init__(self, dim, depth,
kernel_size = 9, patch_size = 7, num_classes = 1000... | StarcoderdataPython |
5132871 | <reponame>bushubeke/python-compose
#pip install SQLAlchemy==1.4.3 aiosqlite
import aiosqlite
from sqlalchemy import create_engine
from sqlalchemy.dialects.sqlite import pysqlite
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
DATABASE_URL =... | StarcoderdataPython |
3512979 | <gh_stars>10-100
import numpy as np
import pandas as pd
from faerun import Faerun
import pickle
faerun = Faerun(view="free", clear_color="#222222")
t = np.linspace(0, 12.0, 326)
s = np.sin(np.pi * t)
c = np.cos(np.pi * t)
sizes = np.linspace(0.1, 2.0, 326)
data = {"x": t, "y": s, "z": c, "c": t / max(t) * 100.0, "s... | StarcoderdataPython |
4949510 | <gh_stars>0
import numpy as np
import scipy.sparse as sp
def reorder(edge_index, edge_weight=None, edge_features=None):
"""
Sorts index in lexicographic order and reorders data accordingly.
:param edge_index: np.array, indices to sort in lexicographic order.
:param edge_weight: np.array or None, edge ... | StarcoderdataPython |
11214854 | import os
from utils import cpp, table_reader
import glob
def main():
constructs = table_reader.csv_to_list_of_tuples(
csv_filepath="construct_codes.csv",
tuple_name="Construct",
)
header_writer = cpp.HeaderWriter(
name="construct_codes",
)
header_writer.write("constexpr ... | StarcoderdataPython |
1674287 | <gh_stars>1-10
# pylint: disable-msg=E1101,W0612
import operator
import nose # noqa
from numpy import nan
import numpy as np
import pandas as pd
from pandas import Series, DataFrame, bdate_range, Panel
from pandas.tseries.index import DatetimeIndex
import pandas.core.datetools as datetools
import pandas.util.testin... | StarcoderdataPython |
194642 | # stdlib
import subprocess
# third party
from PyInquirer import prompt
import click
# grid relative
from ..deploy import base_setup
from ..tf import *
from ..utils import Config
from ..utils import styles
from .provider import *
class GCloud:
def projects_list(self):
proc = subprocess.Popen(
... | StarcoderdataPython |
12864386 | #-*-coding: utf-8 -*-
"""
/dms/edumediaitem/views_manage.py
.. enthaelt den View fuer die Management-Ansicht des Medienpaketes
Django content Management System
<NAME>
<EMAIL>
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 11.09.200... | StarcoderdataPython |
12862112 | <gh_stars>0
x = (input("enters hours"))
y = (input("enters rate"))
def compute_pay(hours, rate):
"""The try block ensures that the user enters a
value between from 0-1 otherwise an error message pops up"""
try:
hours = float(x)
rate = float(y)
if hours <= 40:
pay= float(... | StarcoderdataPython |
4959184 | <filename>k8smtool/__init__.py
from .filter import Filter
from .table import Table
| StarcoderdataPython |
9620194 | <gh_stars>0
from django.urls import path
from . import views
app_name = 'lists'
urlpatterns = [
path('', views.my_list, name='my_list'),
path('remove/<int:pk>/', views.remove_item, name='remove'),
path('update/<int:pk>/', views.update_item, name='update'),
] | StarcoderdataPython |
3378925 | <filename>initialise_short.py
from armor import pattern
from armor import defaultParameters as dp
from armor.defaultParameters import *
from armor.misc import *
| StarcoderdataPython |
3405 | """Set the build version to be 'qa', 'rc', 'release'"""
import sys
import os
import re
import logging
log = logging.getLogger()
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
def get_build_type(travis_tag=None):
if not travis_tag:
return "qa"
log.debug("getting build type for ta... | StarcoderdataPython |
234104 | #! /usr/bin/python3
import json
import requests
class hdns():
def __init__(self, token):
self.baseUrl = "https://dns.hetzner.com/api/v1"
self.token = token
def getAllZones(self):
__name__ = "getAllZones"
try:
response = requests.get(
url="{baseUrl}/... | StarcoderdataPython |
1946508 | import sys
sys.setrecursionlimit(2**20)
def solve(correct, student, j, i, end):
if (i == end or j == end):
return(0)
best = solve(correct, student, j + 1, i, end)
aux, aux2 = solve(correct, student, j, i + 1, end), 0
if (correct[j] == student[i]):
aux2 = solve(correct, student, j + 1, i... | StarcoderdataPython |
5012664 | from rest_framework.fields import Field
class IsCommunityReportedField(Field):
def __init__(self, **kwargs):
kwargs['source'] = '*'
kwargs['read_only'] = True
super(IsCommunityReportedField, self).__init__(**kwargs)
def to_representation(self, value):
request = self.context.ge... | StarcoderdataPython |
9772323 | <filename>python-language/fip.py
from functools import lru_cache
@lru_cache(None)
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n -2)
for i in range(300):
print(i, fib(i)) | StarcoderdataPython |
1976463 | import numpy as np
from PIL import Image
import torch
from torchvision import models
import torchvision.transforms as T
import os
def get_image(path, crop = []):
img = Image.open(path)
img = img.rotate(90, expand = 1)
return img.crop(crop)
def crop_grid(img, box_size = [900,500], top_offset = 0):
# ca... | StarcoderdataPython |
4870171 | <reponame>lukius/ptc<filename>test/test_retransmission.py
import socket
import threading
import time
from base import ConnectedSocketTestCase, PTCTestCase
from ptc.constants import INITIAL_RTO, CLOCK_TICK,\
MAX_RETRANSMISSION_ATTEMPTS,\
BOGUS_RTT_RETRANSMISSIONS
from... | StarcoderdataPython |
5161054 | """
VQA2.0 dataset class
"""
import os
import pickle
from random import randint
from PIL import Image
import numpy as np
import torch.utils.data as data
from Utils.util import pad_sentence
def default_loader(path):
return Image.open(path).convert('RGB')
class VQADataset(data.Dataset):
def __init__(self... | StarcoderdataPython |
6540026 | <gh_stars>1-10
import pytest
from pynormalizenumexp.expression.abstime import AbstimePattern
from pynormalizenumexp.expression.base import NumberModifier
from pynormalizenumexp.utility.dict_loader import ChineseCharacter, DictLoader
@pytest.fixture(scope="class")
def dict_loader():
return DictLoader("ja")
clas... | StarcoderdataPython |
4896782 | <gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sqlalchemy as sa
from h.models import Group, User
from h.models.group import ReadableBy
from h.util import group as group_util
class GroupService:
def __init__(self, session, user_fetcher):
"""
Create a new group... | StarcoderdataPython |
6469979 | #!/usr/bin/env python3
import sys, requests
from requests.auth import HTTPBasicAuth
team = sys.argv[1]
repo = sys.argv[2]
##Login
username = None
password = <PASSWORD>
full_repo_list = []
# Request 100 repositories per page (and only their slugs), and the next page URL
#next_page_url = 'https://api.bitbucket.org/2... | StarcoderdataPython |
6533943 | <reponame>rouseguy/cricket-analytics
import streamlit as st
from streamlit_folium import folium_static
import folium
import altair as alt
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.cm import hot, viridis, Blues, plasma, magma, Greens
import plo... | StarcoderdataPython |
8007251 | def SendMail():
import smtplib
sender = "<EMAIL>"
password = "<PASSWORD>"
receiver = "<EMAIL>"
content = "Subject:TEMPERTURE ALERT\n\nhello mr B4T\nyour temperature is too high.check your room please."
mail = smtplib.SMTP_SSL("smtp.gmail.com")
mail.login(sender, password)
mail.sendmail(s... | StarcoderdataPython |
1638611 | <filename>app/api/auth.py
from flask import current_app, request
from app.db import get_db
import bcrypt
import jwt
from datetime import datetime, timezone, timedelta
def token_required(access=True):
def wrapper(view):
def wrapped_view(*args, **kwargs):
header = request.headers.get('Authoriza... | StarcoderdataPython |
1890856 | #/usr/bin/env python
# vim: set fileencoding=utf-8
from ghost import Ghost
from config import COOKIE_FILE, LOGIN_ID, LOGIN_PW
import urllib2
import cookielib
import Cookie
class NaverCrawler:
# 새 크롤러를 만듭니다.
def __init__(self, id, pw, displayFlag = False):
# 새 Ghost instance를 만들어서 사용합니다.
self.g... | StarcoderdataPython |
240082 | from collections import defaultdict
from common.attacks.tools.hash import CollisionGeneratorBase
class MulticollisionGenerator(CollisionGeneratorBase):
# Based on Joux's "Multicollisions in iterated hash functions. Application
# to cascaded constructions. "
def _get_rand_message_and_state(self,... | StarcoderdataPython |
12844625 | from pprint import pprint
from st2common.runners.base_action import Action
class PrintConfigAction(Action):
def run(self):
print("=========")
pprint(self.config)
print("=========")
| StarcoderdataPython |
6703113 | from TextSearchEngine.mergeResults import mergeResults
from TextSearchEngine.findInTextJson import findInTextJson
import re
def EXACT_WORD(word, caseSensitive = False):
def matcherFunction(text):
flags = 0
if not caseSensitive:
flags = re.IGNORECASE
result = re.search(r'\b'+ wo... | StarcoderdataPython |
9669592 | <reponame>llduncan/usgs-map-gwmodels
"""
Functions for making plots that compare model input to source data
"""
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mfsetup.units import convert_volume_units, convert_time_units
def plot_wateruse(wel_files, perioddata, ad... | StarcoderdataPython |
5105967 | <filename>easy_test/metas/meta_delete.py
from easy_test.metas.meta_html import HtmlMeta
from easy_test.util import contains_option
class DeleteMeta(HtmlMeta):
def validate(cls, meta, module, name):
super().validate(cls, meta, module, name)
# url
if not contains_option(meta, 'url'):
... | StarcoderdataPython |
9656569 | <reponame>bpbpublications/Programming-Techniques-using-Python
from threading import Condition, Thread
from time import sleep
import random
mylist = []
def my_producer():
mycond_obj.acquire() # C1
print("Items producing starts!!!!") # C2
for i in range(1, 6):
myitem = random.randint(1... | StarcoderdataPython |
9756031 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-25 23:16
from __future__ import unicode_literals
from decimal import Decimal
from django.db import migrations, models
import django.db.models.deletion
import djmoney.models.fields
class Migration(migrations.Migration):
initial = True
dependencie... | StarcoderdataPython |
3340909 | <filename>classifaedes/hparams_lib_test.py
# Copyright 2019 Verily Life Sciences LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Un... | StarcoderdataPython |
6603832 | <gh_stars>1000+
# Generated by Django 3.2.11 on 2022-01-31 12:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('integrations', '0009_migrate_headers_data'),
]
operations = [
migrations.RemoveField(
model_name='httpexchange'... | StarcoderdataPython |
4806456 | from bs4 import BeautifulSoup
import re
with open('full-emoji-list.html') as f:
html = f.read()
html = re.sub(r"<td class.*?src='data:image/png;base64.*?</td>", '', html)
html = re.sub(r"\n{2,}", '\n', html)
soup = BeautifulSoup(html, 'html.parser')
lines = []
rows = soup.find_all('tr')
size = len(rows)
for i, ro... | StarcoderdataPython |
3496228 | import sys
import logging
from aiohttp.web import run_app
from sqli.app import init as init_app
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
app = init_app(sys.argv[1:])
run_app(app,
host=app['config']['app']['host'],
port=app['config']['app']['port'])
| StarcoderdataPython |
8084686 | import uuid
from pathlib import Path
from typing import Any
import pytest
from tests.e2e.conftest import Helper
@pytest.fixture
def secret_name() -> str:
return "secret" + str(uuid.uuid4()).replace("-", "")[:10]
@pytest.mark.e2e
def test_create_list_delete(helper: Helper, secret_name: str) -> None:
cap = ... | StarcoderdataPython |
3566027 | import torch
from torch import nn
class BaseTripletLoss(nn.Module):
"""Class of Abstract Loss for Triplet"""
def __init__(self, margin: float = 1, regularizers: list = []):
"""Set margin size and ReLU function
Args:
margin (float, optional): safe margin size. Defaults to 1.
... | StarcoderdataPython |
5871 | # Copyright 2015, Rackspace, US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | StarcoderdataPython |
1722986 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import chess.pgn
import json
import re
import io
def main():
""" Main program """
with open('openings.json', encoding='utf-8') as f:
openings = json.load(f)
openings_by_name, openings_by_pgn = {}, {}
for opening in openings:
# Get name, E... | StarcoderdataPython |
1850128 | import math
from coord import *
class Bot:
"""Abstract class to represent a swarm robot and its position in the frame"""
def __init__(self, tl, tr, br, bl, bot_id=None, offset=None):
# Corners
self.__tl = tl
self.__tr = tr
self.__br = br
self.__bl = bl
# ID fr... | StarcoderdataPython |
6402730 | <gh_stars>0
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Fieldset, Field
from crispy_forms.bootstrap import FormActions
from .models import Etfar
class EtfarForm(forms.ModelForm):
class Meta:
model = Etfar
fields = ('event',... | StarcoderdataPython |
1793038 | <reponame>GmZhang3/data-science-ipython-notebooks<filename>python/python101/basis/distince_test.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
from sklearn.cluster import DBSCAN
def distince(vect1,vect2):
dist = (vect1-vect2)*((vect1-vect2).T)
return dist[0,0]
if __name__ == "__main__":
v1... | StarcoderdataPython |
367437 | """
pytest configuration for figcon
"""
from pathlib import Path
import pytest
from figcon import Figcon
# --------- Add key paths to pytest namespace
TEST_PATH = Path(__file__).parent
PKG_PATH = TEST_PATH.parent
TEST_DATA_PATH = TEST_PATH / 'data'
@pytest.fixture
def default_config_1():
""" return a path to ... | StarcoderdataPython |
11326024 | class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return (num - 1) & num == 0 and (num - 1) % 3 == 0
| StarcoderdataPython |
4887844 | <reponame>tefra/xsdata-w3c-tests
from output.models.sun_data.wildcard.ps_contents.ps_contents00301m.ps_contents00301m1_xsd.ps_contents00301m1 import (
A,
Date,
)
__all__ = [
"A",
"Date",
]
| StarcoderdataPython |
1956681 | from collections import defaultdict
import json
import os
import sys
import argparse
def format_answer_id(doc_id, pass_id, sent_id):
return f'{doc_id}-C{pass_id:03}-S{sent_id:03}'
def format_answer_span_id(doc_id, pass_id, sent_start_id, sent_end_id):
start_id = format_answer_id(doc_id, pass_id, sent_start_id)
e... | StarcoderdataPython |
11340553 | # Copyright 2017 <NAME>, <EMAIL>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee
# is hereby granted, provided that the above copyright notice and this permission notice appear in all
# copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WAR... | StarcoderdataPython |
1935579 | <gh_stars>1-10
"""
Decorators for registering tests in different dictionaries.
This simplifies running all the tests as a group, since different tests may
need to be run in different ways.
"""
from functools import wraps
WORD_TESTS = {}
WORD_SET_TESTS = {}
PARAGRAPH_TESTS = {}
def word_test(fn):
WORD_TESTS[fn._... | StarcoderdataPython |
4927229 | #!/usr/bin/env python
# encoding:utf8
"""
Watch_Dogs
远程监控客户端api调用
"""
import yaml
import time
import requests
from conf import setting
Setting = setting.Setting()
logger_client = Setting.logger
class Watch_Dogs_Client(object):
"""远程监控客户端"""
def __init__(self, remote_host, remote_port=8000):
"""构造... | StarcoderdataPython |
3440853 | from vit.formatter.urgency import Urgency
class UrgencyReal(Urgency):
pass
| StarcoderdataPython |
156719 | <filename>JugandoCodewars/RomanNumeralsHelper.py
# Create a RomanNumerals class that can convert a roman numeral to and from an integer value.
# It should follow the API demonstrated in the examples below.
# Multiple roman numeral values will be tested for each helper method.
# Modern Roman numerals are written by ... | StarcoderdataPython |
4947890 | import typing
from abc import ABC, abstractmethod
from tottle.types.methods import *
from tottle.types.methods import chat
if typing.TYPE_CHECKING:
from tottle.api import API
class APICategories(ABC):
@property
def chats(self) -> chat.ChatCategory:
return chat.ChatCategory(self.api_instance)
... | StarcoderdataPython |
396206 | #!/usr/bin/env python
# encoding: utf-8
'''
asreml.Gmatrix -- shortdesc
asreml.Gmatrix is a description
It defines classes_and_methods
@author: user_name
@copyright: 2020 organization_name. All rights reserved.
@license: license
@contact: user_email
@deffield updated: Updated
'''
import sys
import ... | StarcoderdataPython |
8134565 | <gh_stars>100-1000
__author__ = '<NAME>'
| StarcoderdataPython |
8199846 | import typing as tp
import uvicorn
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
from _logging import CONSOLE_LOGGING_CONFIG, FILE_LOGGING_CONFIG
from dependencies import (
get_employee_by_card_id,
get_revision_pending_... | StarcoderdataPython |
6638794 | <filename>reviewboard/reviews/evolutions/file_attachment_comment_diff_id.py
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('FileAttachmentComment', 'diff_against_file_attachment',
models.ForeignKey, null=True,
related_model='attachment... | StarcoderdataPython |
6507759 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
sys.path.append("./src")
from setup_snicar import *
from classes import *
from column_OPs import *
from biooptical_funcs import *
from toon_rt_solver import toon_solver
from adding_doubling_solver import adding_doubling_solver
from validate_inputs i... | StarcoderdataPython |
11282993 | <filename>jack/readers/knowledge_base_population/shared.py
import tensorflow as tf
from jack.core import TensorPort
class KBPPorts:
triple_logits = TensorPort(tf.float32, [None, None], "triple_logits",
"Represents output scores for each candidate", "[batch_size]")
| StarcoderdataPython |
9657364 | """Let users access their own personal Spotify account."""
__requires__ = ['plumeria.core.oauth']
import random
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.message.lists import build_list
from plumeria.core.oauth import oauth_manager, catch_token_expiration
from plum... | StarcoderdataPython |
6503041 | import cv2
from utils import get_3d_sample, get_2d_sample, BGR_2_gray, get_2d_neighbor
import numpy as np
import cupy as cp
import matplotlib.pyplot as plt
def ncc(X, Y):
if isinstance(X, np.ndarray):
X = cp.array(X)
if isinstance(Y, np.ndarray):
Y = cp.array(Y)
n = int(np.prod(X.shape))
... | StarcoderdataPython |
6615057 | from typing import Dict, List, Optional, Set
from omnilingual import LanguageCode
from pydantic import BaseModel
class SourceWord(BaseModel):
language: LanguageCode
word: Optional[str]
full: bool
tags: Set[str] = set()
class Sense(BaseModel):
definitions: Dict[LanguageCode, List[str]]
t... | StarcoderdataPython |
1848781 | <reponame>arthurguerra/cursoemvideo-python<filename>exercises/CursoemVideo/ex113.py
def leiaInt(msg):
while True:
n = str(input(msg))
try:
int(n)
break
except Exception as erro:
print('\033[1;31mErro: por favor, digite um número inteiro válido.\033[m')
... | StarcoderdataPython |
3597067 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pin-generator.ui'
#
# Created: Mon Jul 12 16:10:58 2010
# by: PyQt4 UI code generator 4.7.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_PinGenerator(object):
def setupUi(self, ... | StarcoderdataPython |
4879019 | <reponame>jimmymalhan/Coding_Interview_Questions_Python_algoexpert<filename>4.hacker_rank/A.30 Days of Code/012_inheritance.py<gh_stars>1-10
# Grading Scale
# O | 90 <= a <= 100
# E | 80 <= a < 90
# A | 70 <= a < 80
# P | 55 <= a < 70
# D | 40 <= a < 55
# T | a < 40
class Person:
def __init__(self, firstName, lastN... | StarcoderdataPython |
5128163 | #!/usr/bin/env python
import sys
import pygtk
pygtk.require('2.0')
import gtk
# get the clipboard
clipboard = gtk.clipboard_get()
# read the clipboard text data. you can also read image and
# rich text clipboard data with the
# wait_for_image and wait_for_rich_text methods.
text = clipboard.wait_for_text()
print t... | StarcoderdataPython |
6579845 | '''
General-purpose numerical routines, relating to angular functions defined on
surfaces of spheres, used in other parts of the module.
'''
# Copyright (c) 2015 <NAME>. All rights reserved.
# Restrictions are listed in the LICENSE file distributed with this package.
import math, numpy as np
from scipy import special... | StarcoderdataPython |
12839452 | # -*- coding: utf-8 -*-
"""
Test base class with commonly used methods and variables
"""
import json
import re
import unittest
import httpretty
class TestGithubBase(unittest.TestCase):
"""Test Github actions and backing library."""
OAUTH2_TOKEN = '<PASSWORD>'
ORG = 'NOT_REAL'
URL = 'http://localhost... | StarcoderdataPython |
271769 | # by amounra 0613 : http://www.aumhaa.com
import Live
import os, __builtin__, __main__, _ast, _codecs, _functools, _md5, _random, _sha, _sha256, _sha512, _socket, _sre, _ssl, _struct, _symtable, _weakref, binascii, cStringIO, collections, datetime, errno, exceptions, gc, imp, itertools, marshal, math, sys, time #_typ... | StarcoderdataPython |
8125240 | <reponame>runette/jump-195016
#!/usr/bin/env python
# Copyright 2018 <NAME>
#
# 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 requ... | StarcoderdataPython |
6505026 | <gh_stars>1000+
#!/usr/bin/python
#
# This example shows how to use MITIE's text_categorizer from Python.
#
#
import sys, os
# Make sure you put the mitielib folder into the python search path. There are
# a lot of ways to do this, here we do it programmatically with the following
# two statements:
parent = os.pa... | StarcoderdataPython |
11274190 | <reponame>saucetray/st2<gh_stars>1-10
# Copyright 2019 Extreme Networks, 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 req... | StarcoderdataPython |
6647954 | from __future__ import print_function
from builtins import zip
import os
import pytest
from fasttrips import Run
# TEST OPTIONS
test_thetas = [1.0, 0.5, 0.2]
test_size = 5
disperson_rate_util_multiplier_factor = 10.0
# DIRECTORY LOCATIONS
EXAMPLE_DIR = os.path.join(os.getcwd(), 'fasttrips', 'Examples', 'Spr... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.