id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
58920 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def grpc_rules_repository():
http_archive(
name = "rules_proto_grpc",
urls = ["https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz"],
sha256 = "d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd93... | StarcoderdataPython |
1671111 | <gh_stars>1-10
from flask import Flask
from flask import render_template
from flask import request
from flask import url_for
from flask import has_request_context, request
from flask.logging import default_handler
import logging
class RequestFormatter(logging.Formatter):
def format(self, record):
if has... | StarcoderdataPython |
148056 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: app/views/miniprogram_api.py
import os
import sys
basedir = os.path.join(os.path.dirname(__file__),"..") # 根目录为app
cachedir = os.path.join(basedir,"cache")
textdir = os.path.join(basedir,"text")
import re
from collections import OrderedDict
import simplejso... | StarcoderdataPython |
97466 | from . import config
import networkx as nx
import torch
import torch.nn
import torch_geometric as tg
import torch_geometric.data
import torch_geometric.utils
from tqdm.auto import tqdm
def batch_of_dataset(dataset):
loader = tg.data.DataLoader(dataset, batch_size=len(dataset))
for g, h, lb, ub in loader:
... | StarcoderdataPython |
1668529 | <reponame>krokce/rapo
"""Contains application logger."""
import pepperoni
from .config import config
logger = pepperoni.logger(file=True)
logger.configure(format='{isodate}\t{thread}\t{rectype}\t{message}\n')
if config.has_section('LOGGING'):
LOGGING = config['LOGGING']
logger.configure(console=LOGGING.get... | StarcoderdataPython |
1635574 | # Copyright 2016 - Wipro Limited
#
# 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 writin... | StarcoderdataPython |
20456 | <reponame>frc1678/server-2021-public
#!/usr/bin/env python3
# Copyright (c) 2019 FRC Team 1678: Citrus Circuits
import pytest
import numpy as np
import os, sys
current_directory = os.path.dirname(os.path.realpath(__file__))
parent_directory = os.path.dirname(current_directory)
grandparent_directory = os.path.dirname(p... | StarcoderdataPython |
1704012 | <filename>mon-put-rq-stats.py
#!/usr/bin/env python
"""
Usage: mon-put-rq-stats.py [--url REDIS_URL] [--env ENV] [--region REGION]
[--pid PIDFILE] [--interval INTERVAL]
[--debug] [--no-cloudwatch]
mon-put-rq-stats.py -h | --help
mon-put-rq-stats -v | -... | StarcoderdataPython |
3376493 | import os
import importlib_metadata
def get_source_version():
d = dict(MAJOR='6', MINOR='0', MICRO='0', EXTRA='none')
here = os.path.abspath(os.path.dirname(__file__))
try:
f = open(os.path.join(here, '..', '..', 'CMakeLists.txt'))
except FileNotFoundError:
return None
for line in ... | StarcoderdataPython |
194372 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | StarcoderdataPython |
30365 | <gh_stars>1-10
# Copyright (C) 2016-2018 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd 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 lat... | StarcoderdataPython |
3338277 | from graph import *
class PathFinder:
"""
Class container for pathfinding solution.
"""
def __init__(self):
self.canPassHomeNodes = False
self.useCyclicBFS = False
# convert the complex Graph object to a simple dictionary to
# faciliate pathfinding without cycles
def _Grap... | StarcoderdataPython |
1622754 | <reponame>materialsproject/maggpy<gh_stars>0
# coding: utf-8
"""
Module defining a FileStore that enables accessing files in a local directory
using typical maggma access patterns.
"""
import hashlib
import warnings
from pathlib import Path
from datetime import datetime, timezone
from typing import Dict, List, Option... | StarcoderdataPython |
16996 | <reponame>alixedi/data-hub-api-cd-poc
from elasticsearch_dsl import Boolean, Date, Double, Integer, Keyword, Long, Object, Text
from datahub.search import dict_utils
from datahub.search import fields
from datahub.search.models import BaseESModel
DOC_TYPE = 'investment_project'
def _related_investment_project_field... | StarcoderdataPython |
3358805 | from torch import nn
from .base_models import BaseEncoderMaskerDecoder
from asteroid_filterbanks import make_enc_dec
from asteroid_filterbanks.transforms import mag, magreim
from ..masknn import norms, activations
from ..utils.torch_utils import pad_x_to_y
import warnings
class DeMask(BaseEncoderMaskerDecoder):
"... | StarcoderdataPython |
4829916 | # coding:utf8
from datetime import datetime
from app import db
class User(db.Model):
"""
Informations of users.
"""
__tablename__ = "user"
# __table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True) # user number
name = db.Column(db.String(100), unique=True) ... | StarcoderdataPython |
162004 | <gh_stars>10-100
#!/usr/bin/env python3
"""\
Usage:
zip_demos.py [<directory>]
"""
import docopt
from pathlib import Path
from zipfile import ZipFile
def demo_uses_asset(asset, content):
asset = Path(asset)
if f"'{asset.name}'" in content:
return True
if asset.suffix == '.py':
retur... | StarcoderdataPython |
4818521 | <filename>orchestration/hca_manage/validation.py
import logging
from typing import Any, Optional
from dagster_utils.contrib.google import parse_gs_path
from google.cloud.storage import Client
from hca_manage.common import DefaultHelpParser
from hca.staging_area_validator import StagingAreaValidator
class HcaValidat... | StarcoderdataPython |
34211 | from typing import Optional, List
from aiogram import types, Dispatcher, filters
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import StatesGroup, State
from aiogram.types import ReplyKeyboardMarkup
from handlers.common_actions_handlers import process_manual_enter, process_option_sel... | StarcoderdataPython |
3201989 | <filename>goss-testing/scripts/python/check_ncn_uan_ip_dns.py<gh_stars>1-10
#!/usr/bin/env python3
#
# MIT License
#
# (C) Copyright 2014-2022 Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files ... | StarcoderdataPython |
179460 | <reponame>kagemeka/atcoder-submissions
import sys
from bisect import bisect_left as bi_l
INF = float("inf")
n, *c = map(int, sys.stdin.read().split())
def main():
res = [INF] * n
for x in c:
i = bi_l(res, x)
res[i] = x
ans = n - bi_l(res, INF)
print(ans)
if __nam... | StarcoderdataPython |
118753 | # The MIT License
#
# Copyright (c) 2008 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | StarcoderdataPython |
2028 | import os
import sys
from . import HendrixTestCase, TEST_SETTINGS
from hendrix.contrib import SettingsError
from hendrix.options import options as hx_options
from hendrix import ux
from mock import patch
class TestMain(HendrixTestCase):
def setUp(self):
super(TestMain, self).setUp()
self.DEFAULTS... | StarcoderdataPython |
3392230 | <reponame>cubrink/doltpy
from doltcli import Dolt, Commit, DoltException, DoltHubContext # type: ignore
| StarcoderdataPython |
3384710 | # Generated by Django 3.1.2 on 2020-10-08 18:43
import cropperjs.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('recipe', '0002_auto_20201008_1340'),
]
operations = [
migrations.AlterField(
model_name='recipe',
na... | StarcoderdataPython |
1618078 | <filename>tests/test_round_index.py
# -*- coding: utf-8 -*-
import shlex
import subprocess
from unittest import TestCase
import pandas
from pandas.testing import assert_frame_equal
from tstoolbox import tstoolbox, tsutils
class Testround_index(TestCase):
def setUp(self):
dr = pandas.date_range("2000-01... | StarcoderdataPython |
1796950 | """
Orange Canvas Graphics Items
"""
from .nodeitem import NodeItem, NodeAnchorItem, NodeBodyItem, SHADOW_COLOR
from .nodeitem import SourceAnchorItem, SinkAnchorItem, AnchorPoint
from .linkitem import LinkItem, LinkCurveItem
from .annotationitem import TextAnnotation, ArrowAnnotation
| StarcoderdataPython |
1631138 | #!/usr/bin/env python
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import argparse
import os
import os.path as osp
from chainer import cuda
import chainer.serializers as S
from chainer import Variable
import numpy as np
from scipy.misc import imread
fro... | StarcoderdataPython |
3223295 | # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import pytest
from datadog_checks.nginx import Nginx
from . import common
@pytest.mark.e2e
@pytest.mark.skipif(common.USING_VTS, reason="Non-VTS test")
def test_e2e(dd_agent_check, instance):
aggregator ... | StarcoderdataPython |
1625822 | <filename>aiocouch/couchdb.py
# Copyright (c) 2019, ZIH,
# Technische Universitaet Dresden,
# Federal Republic of Germany
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistribution... | StarcoderdataPython |
1745785 | <filename>huygens/interf/__init__.py
'''
===================================
Interfacing with Compiled Libraries
===================================
Functions
=========
c_vector -- Produce a ctype's object to pass as a C pointer (a vector)
c_matrix -- Produce a ctype's object to pass as a C pointer to a pointer ... | StarcoderdataPython |
1724202 | from nose.tools import assert_equal
from networkx import asyn_lpa, Graph
def test_empty_graph():
# empty graph
test = Graph()
# ground truth
ground_truth = set()
communities = asyn_lpa.asyn_lpa_communities(test)
result = {frozenset(c) for c in communities}
assert_equal(result, ground_tru... | StarcoderdataPython |
1792435 |
import os
import sys
import fnmatch
from setuptools import setup, find_packages
# For version info
import metrilyx
def fileListBuilder(dirPath, regexp='*'):
matches = []
for root, dirnames, filenames in os.walk(dirPath):
for filename in fnmatch.filter(filenames, regexp):
matches.append(o... | StarcoderdataPython |
1714775 | <filename>Course I/Алгоритмы Python/Part2/семинары/pract5/защита/main.py
import time
import numpy as np
from computer_module import ComputerGameClass
from elements_module import BoardClass
from user_module import UserAnalyserClass
from util_module import UtilClass
# Белые - это синие
# Черные - это красные
class Jou... | StarcoderdataPython |
56991 | class Solution(object):
def XXX(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def backtrace(nums,track):
if len(nums) == len(track):
res.append(track[:])
return
for i in range(len(nums)):
... | StarcoderdataPython |
164949 | <reponame>Sheidaas/gamee<gh_stars>0
class GuiAbstractObject:
def is_clicked(self, mouse):
area = (self.position[0] * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
self.position[1] * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
... | StarcoderdataPython |
3397975 | from dater.dateset import DataSet
import numpy as np
class DynMemNetDataSet(DataSet):
def __init__(self):
pass
def load_train(self):
pass
def load_dev(self):
pass
def load_train_dev(self):
pass
def load_test(self):
pass
def set_predict_params(self):... | StarcoderdataPython |
1787587 | # The following code has been modified from that provided at github.com/piborg/diablo
# by <NAME>
#!/usr/bin/env python
###
#
# diabloSequence.py: A script for controlling motors with the Diablo in a sequence.
#
# 2019-04-26
#
###
# Import library functions we need
from __future__ import print_function
from diablo im... | StarcoderdataPython |
4828506 | # Copyright 2018 Open Source Robotics Foundation, 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... | StarcoderdataPython |
122997 | <filename>enter.py<gh_stars>0
from IBI_raspisan import get_updates, handle_updates
import time
updates = get_updates()
while True:
new_updates = get_updates()
if len(new_updates['result']) > len(updates['result']):
handle_updates(new_updates, len(new_updates['result']) - len(updates['result']))
... | StarcoderdataPython |
15118 | <reponame>NumanIbnMazid/numanibnmazid.com<filename>backend/utils/management/commands/generate_dummy_skills.py
from portfolios.factories.skill_factory import create_skills_with_factory
from django.db import transaction
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Generate... | StarcoderdataPython |
3358057 | import home
from ws.handler.event.enum.appliance.light import forced
class Handler(forced.Handler):
KLASS = home.appliance.thermostat.presence.event.forced.event.Event
TEMPLATE = "event/forced_enum.html"
KEEPING = "keeping"
FORCED_KEEPING = "Forced keeping"
ICON_KEEPING = "fas fa-sort"
def ... | StarcoderdataPython |
3204228 | """Upload script result to Cyberwatch for air gapped scans"""
import os
import argparse
from configparser import ConfigParser
from cbw_api_toolbox.cbw_api import CBWApi
def connect_api():
'''Connect to the API and test connection'''
conf = ConfigParser()
conf.read(os.path.join(os.path.abspath(os.path.dir... | StarcoderdataPython |
4838879 | # Generated by Django 4.0 on 2022-02-05 13:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0002_bookinstance_borrower_alter_author_date_of_birth_and_more'),
]
operations = [
migrations.AlterModelOptions(
name='bookinst... | StarcoderdataPython |
3204902 | <filename>tests/test_util.py
import hashlib
from os import makedirs, symlink
from shutil import rmtree
from os.path import join, basename
from unittest.mock import patch
from egcg_core import util
from tests import TestEGCG
fastq_dir = join(TestEGCG.assets_path, 'fastqs')
def test_find_files():
expected = [join(... | StarcoderdataPython |
1673832 | from __future__ import print_function
import argparse
import shutil
import torch
import torchvision
import random
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.utils.tensorbo... | StarcoderdataPython |
105703 | <gh_stars>0
import pythagore
problem_type = input("Type 1 for right triangle checker. Type 2 for hypotenuse calc. for right triangle. Type 3 for missing arm value calc. for right triangle. Type 4 for volume of a cylinder calc. Type 5 for cone volume calc. Type 6 for volume of a sphere calc.")
if problem_type == "1":
... | StarcoderdataPython |
1662843 | <filename>experiments/analyze/VisualizeDeepConvRFMap.py
# general imports
import warnings
import matplotlib.pyplot as plt
import seaborn as sns
import torchvision.datasets as datasets
import numpy as np
from sklearn.ensemble import RandomForestClassifier
sns.set()
warnings.filterwarnings("ignore")
cifar_data_path =... | StarcoderdataPython |
400 | <filename>beansdbadmin/core/client.py
#!/usr/bin/python
# encoding: utf-8
'''a rich client
1. for one server (instead of multi like in libmc.Client)
2. encapsulate @, ?, gc ...
use is instead of libmc.Client
'''
import telnetlib
import logging
import libmc
import string
import urllib
import itertools
import w... | StarcoderdataPython |
1624072 | <reponame>sadikkuzu-mba/pyJiraAHE<filename>JiraAHE.py
from jira import JIRA
from getpass import getpass
username = "<EMAIL>"
password = "<PASSWORD>" # Number1 as usual;)
urlJ = "https://aheinsis.atlassian.net/"
def getText(txt):
try:
ret = getpass(txt + " >> ")
except:
ret = None
return r... | StarcoderdataPython |
132723 | <filename>automated_analysis.py
import argparse
import csv
from collections import OrderedDict
import sys
from core_data_modules.cleaners import Codes
from core_data_modules.logging import Logger
from core_data_modules.traced_data.io import TracedDataJsonIO
from core_data_modules.util import IOUtils
from core_data_mod... | StarcoderdataPython |
4842472 | <reponame>edmundsj/xsugar<gh_stars>0
"""
Tests data reading and writing operation, along with condition generation
"""
import pytest
import numpy as np
import pandas as pd
from pandas.testing import assert_frame_equal
import os
from shutil import rmtree
from numpy.testing import assert_equal, assert_allclose
from xsuga... | StarcoderdataPython |
3394694 | #!/usr/bin/env python3
import asyncio
from caproto.server import ioc_arg_parser, run
from collections import defaultdict
from caproto import (ChannelString, ChannelEnum, ChannelDouble,
ChannelChar, ChannelData, ChannelInteger,
ChannelType)
from route_channel import (StringRout... | StarcoderdataPython |
20510 | <gh_stars>1-10
import httpx
import pathlib
import re
import datetime
from bs4 import BeautifulSoup
root = pathlib.Path(__file__).parent.resolve()
def formatGMTime(timestamp):
UTC_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
timeStr = datetime.datetime.strptime(timestamp, UTC_FORMAT) + datetime.timedelta(hours=2, minutes=30... | StarcoderdataPython |
4807866 | from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['fbprophet','dask[complete]']
setup(
name='prophet_gcp',
version='0.1',
author = '<NAME>',
author_email = '<EMAIL>',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
descripti... | StarcoderdataPython |
36903 | import pytest
import pandas as pd
from src.preprocess import check
class Test_check_column_names:
def test_check_column_names(self):
records = pd.DataFrame({'a': [1]})
config = pd.DataFrame({'column': ['a'], 'dataset': ['ACAPS']})
res = check.check_column_names(records, config, log=False... | StarcoderdataPython |
171808 | import sys, os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CURRENT_DIR, "..", ".."))
import constants
import requests
HTTP_ERROR_CODE_START = 400
HTTP_ERROR_MESSAGE_FORMAT= "Site '%s' returned error '%d'"
REQUEST_ERROR_FORMAT = "Requesting connection to '%s' errored!"
HYP... | StarcoderdataPython |
168840 | <filename>story/models.py
from django.db import models
from .urlgenerator import create_urlcode
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from datetime import datetime
from story.resetkey import secure_key
from django.db.models import F
class Story(models.Model):
cl... | StarcoderdataPython |
3324296 | <reponame>0xflotus/CUP
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Copyright: [CUP] - See LICENSE for details.
# Authors: <NAME> (@mythmgn),
"""
misc classes for internal use
"""
import os
import sys
class CAck(object):
"""
ack class
"""
def __init__(self, binit=False):
self._rev = binit
... | StarcoderdataPython |
20430 | <reponame>lambdamusic/wittgensteiniana
"""
Using
http://thejit.org/static/v20/Docs/files/Options/Options-Canvas-js.html#Options.Canvas
"""
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
import json
... | StarcoderdataPython |
1672910 | from marshmallow import EXCLUDE, Schema, fields
from application.models import Cards, Meta, Sets
class SetsSchema(Schema):
cs_id = fields.Int()
cs_name = fields.Str()
mtgjson_code = fields.Str()
related_mtgjson_codes = fields.List(fields.Str())
class Meta:
ordered = True
set_schema = ... | StarcoderdataPython |
4843113 | import argparse
import calendar
import dotenv
import json
import libraries.api
import libraries.handle_file
import libraries.record
import logging
import logging.config
import os
import pandas as pd
import requests
import time
from csv import writer
from oauthlib.oauth2 import BackendApplicationClient, TokenExpiredErro... | StarcoderdataPython |
4824999 | <reponame>akashkj/commcare-hq
import json
from datetime import date
from io import BytesIO
from django.http import (
Http404,
HttpResponse,
HttpResponseBadRequest,
HttpResponseServerError,
JsonResponse,
)
from django.urls import reverse
from django.utils.decorators import method_decorator
from djan... | StarcoderdataPython |
3374124 | <gh_stars>0
#!/usr/bin/env python3
''' EC² TTLDM-35 - TTL Military Logic Delay Module '''
from Chipdesc.chip import Chip
class TTLDM35(Chip):
''' EC² TTLDM-35 - TTL Military Logic Delay Module '''
symbol_name = "DLY_35"
checked = "MEM32 0029"
symbol = '''
+--------+
| |
| xnn |... | StarcoderdataPython |
4821572 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import uuid
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
... | StarcoderdataPython |
1682340 | # This example requires the micropython_dotstar library
# https://github.com/mattytrentini/micropython-dotstar
from machine import SPI, Pin
import tinypico as TinyPICO
from micropython_dotstar import DotStar
import time, random, micropython
# Configure SPI for controlling the DotStar
# Internally we are using softwar... | StarcoderdataPython |
107437 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_general_log_parser
----------------------------------
Tests for `general_log_parser` module.
"""
import sys, os, re
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import unittest
from general_log_parser import parser
clas... | StarcoderdataPython |
3386428 | <reponame>juergenhoetzel/craft<filename>bin/Utils/CraftManifest.py<gh_stars>0
import collections
import datetime
import json
import os
from CraftCore import CraftCore
import utils
class CraftManifestEntryFile(object):
def __init__(self, fileName : str, checksum : str, version : str="") -> None:
self.file... | StarcoderdataPython |
3322571 | # -*- coding:utf-8 -*-
# @Script: utils.py
# @Author: <NAME>
# @Email: <EMAIL>
# @Create At: 2020-04-10 03:21:53
# @Last Modified By: <NAME>
# @Last Modified At: 2020-09-17 15:25:00
# @Description: Utils to search and replace file content and get ip address information.
import glob
import mmap
import subprocess
import... | StarcoderdataPython |
1780877 | <gh_stars>0
# Colors based on the Material design scheme
colors = {
'red': '#B71C1C',
'green': '#2E7D32',
'gray': '#263238'
}
def escape_slack_characters(raw: str) -> str:
"""Escape the special characters that are used by Slack
in their messaging API.
See `Slack API docs <https://api.slack.c... | StarcoderdataPython |
3307506 | from itertools import repeat
def zeros_imul(n):
l = [0]
l *= n
return l
def zeros_mul(n):
return n * [0]
def zeros_repeat(n):
return list(repeat(0, n))
def zeros_slow(n):
return [0 for _ in range(n)]
| StarcoderdataPython |
164264 | import sys
import util
from node import Node
from state import State
def applicable(state, actions):
''' Return a list of applicable actions in a given `state`. '''
app = list()
for act in actions:
if State(state).intersect(act.precond) == act.precond:
app.append(act)
return app
de... | StarcoderdataPython |
1760872 | from PIL import Image
from os import path
import sys
if len(sys.argv) == 2:
try:
im = Image.open(path.abspath(sys.argv[1]))
px = im.load()
setColor = set({})
for x in range(im.width):
for y in range(im.height):
setColor.add(px[x, y])
print(len(se... | StarcoderdataPython |
1660274 |
AUTO_SPLIT_LINES = True
_has_readline = False
try:
import readline
_has_readline = True
except ModuleNotFoundError:
pass
_has_prompt_toolkit = False
try:
import prompt_toolkit
import prompt_toolkit.completion
_has_prompt_toolkit = True
except ModuleNotFoundError:
pass
if _has_readline... | StarcoderdataPython |
3226882 | # ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: <NAME>
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2021 Aarno Labs LLC
#
# Permission is hereby granted, free of charge, to... | StarcoderdataPython |
3394206 | from .models import Subject, SchoolType, SchoolSubType, SchoolLevel, SubjectGroup
import os
import csv
def init_subjects():
"""
Zdroj: https://docs.google.com/spreadsheets/d/1msJu1AX_-wYLbhvz8rqsZxFMBwX7-xzghCAFHeeBQEI/edit#gid=2044127896
List: Číselník předmětů
"""
subjects_list = []
filepat... | StarcoderdataPython |
3314455 | <gh_stars>0
'''
function to test pretrained models on the test set and show the graph
of actual values and predictions
'''
import pandas as pd
from furiosanet import test, get_layers_from_file
def main():
'''
test models saved in the csv
'''
models = pd.read_csv("model-evaluation.csv", index... | StarcoderdataPython |
4828988 | <filename>web/teenage_jinja_turtles/challenge/views/errors.py
from flask import Blueprint, abort
import logging as log
logging = log.getLogger('gunicorn.error')
error = Blueprint('error', __name__)
@error.app_errorhandler(400)
def handle_400(error):
logging.warning(error)
return error.description o... | StarcoderdataPython |
86402 | <filename>HandGesture.py
import cv2
import numpy as np
import hogsvm2
import pickle
import time
from skimage import feature
def HOG(img, imgResize=(64, 128), bin=9, cell=(8, 8), block=(2, 2), norm="L2", sqrt=True, visualize=False):
if visualize == False:
hog = feature.hog( cv2.resize( img, imgResize),
... | StarcoderdataPython |
60500 | #!/usr/bin/env python3
import hashlib
import re
import requests
import sys
from pprint import pprint as pp
from .exceptions import PCloudException
from .connection import AbstractPCloudConnection
from .pcloudbin import PCloudBinaryConnection
PCLOUD_SERVER_SUFFIX = '.pcloud.com' # only allow downloads from pcloud s... | StarcoderdataPython |
1709881 | from django.apps import AppConfig
class IncidentsConfig(AppConfig):
name = 'incidents'
| StarcoderdataPython |
3236200 | <filename>Python/BEGINNER/1005.py
A = float(input())
A = round(A,1)
B = float(input())
B = round(B,1)
MEDIA = ((A * 3.5)+(B * 7.5))/(3.5+7.5)
print(MEDIA) | StarcoderdataPython |
1612773 | '''
>>> student_function('example')
Traceback (most recent call last):
...
ValueError
'''
from test_util import doctester
test_passed = doctester("student_module", total_points=3)
| StarcoderdataPython |
168326 | import datetime
import json
from source.util.util_base.db import (get_multi_data, get_single_value,
update_data)
from source.util.util_data.basic_info import BasicInfo
class NoteData:
def __init__(self, db_conn):
self.db_conn = db_conn
async def note_insert(self... | StarcoderdataPython |
3331593 | <gh_stars>1-10
import numpy as np
import gym
from gym import spaces
from gym.utils import seeding
from swarms.commons.utils import EzPickle
from swarms import base
# from ma_envs.envs.environment import MultiAgentEnv
from swarms.agents.point_agents.pursuer_agent import PointAgent
from swarms.agents.point_agents.evader_... | StarcoderdataPython |
1610945 | """Parser for BlueMaestro BLE advertisements."""
import logging
from struct import unpack
_LOGGER = logging.getLogger(__name__)
def parse_bluemaestro(self, data, source_mac, rssi):
"""Parse BlueMaestro advertisement."""
msg_length = len(data)
firmware = "BlueMaestro"
device_id = data[4]
bluemaest... | StarcoderdataPython |
3343011 | from django.contrib.auth import views as auth_view
from django.urls import path
from .views import login_view, logout_view, signup_view
# ****** Url Patterns ******
urlpatterns = [
path('signup/', signup_view, name='signup'),
path('login/', login_view, name='login'),
path('logout/', logout_view, name='log... | StarcoderdataPython |
156023 | <reponame>ckamtsikis/cmssw<filename>JetMETCorrections/MCJet/python/RelValQCD_cfi.py
import FWCore.ParameterSet.Config as cms
readFiles = cms.untracked.vstring()
source = cms.Source ("PoolSource",fileNames = readFiles)
readFiles.extend( (
" /store/relval/CMSSW_3_4_0_pre2/RelValQCD_FlatPt_15_3000/GEN-SIM-RECO... | StarcoderdataPython |
1665268 | #!/bin/python
# Copyright (c) 2015-2017, Open Communications Security
# 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 copyright notice,... | StarcoderdataPython |
139374 | <reponame>nghiattran/mentality
from lib.neuron import Neuron
class Layer(object):
def __init__(self, setting):
self.neurons = []
if type(setting) is int:
self.name = ''
for i in range(setting):
self.neurons.append(Neuron(self))
elif type(setting) is... | StarcoderdataPython |
1748248 | #
# 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 applicable law or agreed to ... | StarcoderdataPython |
1688387 | <reponame>foxytrixy-com/foxylib<filename>foxylib/tools/function/loop/loop_tool.py
import time
class LoopTool:
class ExitException(Exception):
pass
@classmethod
def failcount2secs_default(cls, failcount):
secs = min(2 ** failcount, 60)
return secs
@classmethod
def func2loo... | StarcoderdataPython |
188702 | <gh_stars>1-10
from os import path, makedirs
from datetime import datetime
from io import BytesIO
from base64 import b64encode
from urllib.parse import quote
from time import sleep
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as Fi... | StarcoderdataPython |
1739168 | <gh_stars>0
from selenium import webdriver
from seleniumbase.__version__ import __version__
from seleniumbase.core.browser_launcher import get_driver # noqa
from seleniumbase.fixtures import js_utils # noqa
from seleniumbase.fixtures import page_actions # noqa
from seleniumbase.fixtures.base_case import BaseCase # ... | StarcoderdataPython |
4834334 | import logging
import re
from sqlalchemy import create_engine
from sqlalchemy.engine.reflection import Inspector
import sqlalchemy_utils
logger = logging.getLogger(__name__)
def hint_match(record, hints):
for hint in hints:
if re.match(hint, record):
return True
return False
def try_... | StarcoderdataPython |
4829352 | <filename>apps/payments/api/serializers.py<gh_stars>1-10
"""
Payments API
"""
from rest_framework import serializers
from apps.users.api.serializers import UserSerializer
from apps.purchases.api.serializers import PurchaseOrderSerializer
from apps.inventory.api.serializers import InventoryItemSerializer
from ..models i... | StarcoderdataPython |
1663837 | <filename>custom_dynamics/enums.py
from enum import Enum
class MillerDynamics(Enum):
"""
Selection of dynamics to perform the miller ocp
"""
EXPLICIT = "explicit"
ROOT_EXPLICIT = "root_explicit"
IMPLICIT = "implicit"
ROOT_IMPLICIT = "root_implicit"
IMPLICIT_TAU_DRIVEN_QDDDOT = "implic... | StarcoderdataPython |
98803 | <reponame>markliuyuxiang/web-avatarify
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .api import style_gan
service = os.getenv("SERVICE")
if service == "avatarify":
from .api import avatarify
else:
from .api import avatarify_relay as avatarify
app = FastAPI()... | StarcoderdataPython |
1763808 | import pathlib
import typing
from typing import Type
import numpy as np
from flytekit.core.context_manager import FlyteContext
from flytekit.core.type_engine import TypeEngine, TypeTransformer, TypeTransformerFailedError
from flytekit.models.core import types as _core_types
from flytekit.models.literals import Blob, ... | StarcoderdataPython |
1656339 | <reponame>miaucl/iot-pi-cam
#!/usr/bin/python
"""
Raspberry Pi Power Button Script.
Author: miaucl
Description: This script listens to a power button connected on PIN XXX and enables shutdown and reboot functionality for a raspbian dist using python 2/3.
Setup: The PIN XXX is configured with a pull up resistor and sho... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.