id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
11338018
from __future__ import unicode_literals import dataent def execute(): dataent.reload_doc("core", "doctype", "docperm") # delete same as cancel (map old permissions) dataent.db.sql("""update tabDocPerm set `delete`=ifnull(`cancel`,0)""") # can't cancel if can't submit dataent.db.sql("""update tabDocPerm set `c...
StarcoderdataPython
249525
#!/usr/bin/env python # -*- coding: utf-8 -*- # When using bytestrings in Python 2, Windows requires full unicode # filenames and paths. Therefore any bytestring paths *must* be utf-8 # encoded as they will need to be converted on the fly to full unicode # for Windows platforms. # # Both Linunx and Mac OS X pl...
StarcoderdataPython
1944746
<filename>src/schemathesis/specs/graphql/schemas.py from functools import partial from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, cast from urllib.parse import urlsplit import attr import graphql from hypothesis import strategies as st from hypothesis.strategies import SearchStrategy from hyp...
StarcoderdataPython
4940740
# Generated by Django 3.1.5 on 2021-02-06 16:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_publication_file'), ] operations = [ migrations.RemoveField( model_name='presentation', name='authors',...
StarcoderdataPython
178316
import os, pickle,uuid class ControlBase(object): _value = None _label = None _controlHTML = "" def __init__(self, *args, **kwargs): self._id = uuid.uuid4() self._value = kwargs.get('default', None) self._parent = 1 self._label = kwargs.get('label...
StarcoderdataPython
3331268
""" nmeta flows.py Unit Tests Note: no testing of max_interpacket_interval and min_interpacket_interval as they become imprecise due to floating point and when tried using decimal module found that would not serialise into Pymongo db. Note that packets + metadata are imported from local packets_* modules TBD duplica...
StarcoderdataPython
11295633
<filename>simple_notes/notes/tasks.py from celery import shared_task from .utils import send_email from django.utils.translation import gettext as _ from .models import Reminder @shared_task def send_email_task(subject: str, email: str, content: str): print(f'SEND_EMAIL_TASK: Sending an email to {email}') ...
StarcoderdataPython
6669364
<reponame>Samuel-Melo890/Python-Desafios<gh_stars>0 def tabela(list): print(f''' 0 1 2 0 | {list[0][0]} | {list[0][1]} | {list[0][2]} | 1 | {list[1][0]} | {list[1][1]} | {list[1][2]} | 2 | {list[2][0]} | {list[2][1]} | {list[2][2]} | ''') from os import system from module.interface import * import random f...
StarcoderdataPython
12876
import os import databases import sqlalchemy DB_CONNECTOR = os.getenv('APP_DB_CONNECTOR') DB_USERNAME = os.getenv('APP_DB_USERNAME') DB_PASSWORD = os.getenv('APP_DB_PASSWORD') DB_HOST = os.getenv('APP_DB_HOST') DB_PORT = os.getenv('APP_DB_PORT') DB_DATABASE = os.getenv('APP_DB_DATABASE') DB_URL = f'{DB_CONNECTOR}://...
StarcoderdataPython
15270
# Lint as: python3 # Copyright 2019 DeepMind Technologies Limited. 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 # # ...
StarcoderdataPython
29107
<filename>itertable/gis/mixins.py<gh_stars>10-100 import fiona from shapely import wkt, geometry from ..loaders import FileLoader from ..parsers.base import BaseParser from ..mappers import TupleMapper class FionaLoaderParser(FileLoader, BaseParser): """ Composite loader & parser mixin for GIS data, powered b...
StarcoderdataPython
1775943
import pytest from indy import pool from indy.error import ErrorCode, IndyError @pytest.mark.asyncio async def test_create_pool_ledger_config_works(pool_ledger_config): pass @pytest.mark.asyncio async def test_create_pool_ledger_config_works_for_empty_name(): with pytest.raises(IndyError) as e: awa...
StarcoderdataPython
4800915
<reponame>atentas/ennemi<filename>tests/unit/test_entropy_estimators.py # MIT License - Copyright <NAME> and contributors # See the LICENSE.md file included in this source code package """Tests for ennemi._estimate_single_mi() and friends.""" import math from math import log import numpy as np from scipy.special impo...
StarcoderdataPython
1986178
import torch.nn as nn import torch from torch.autograd import Variable import torch.nn as nn import matplotlib.pyplot as plt import numpy as np # logistic regression model def createlogisticRegression(): linear = nn.Linear(2, 1, bias = True) sigmoid = nn.Sigmoid() model_logistic_regression = nn.Sequentia...
StarcoderdataPython
1978659
<gh_stars>0 import torch class GlobalConfig: seed = 1992 num_classes = 10 batch_size = 128 EPOCHS = 70 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # data input_image_size = (3, 32, 32) # trainloader = train_loader # testloader = test_loader classes = ...
StarcoderdataPython
6409398
<reponame>TrinhQuocNguyen/labelme_DOTA<gh_stars>1-10 # -*- coding: utf-8 -*- from PyQt4.QtGui import * from PyQt4.QtCore import * import sys QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8")) from libs.shape import Shape class MouseEvent(QMainWindow): def __init__(self, parent=None): super(MouseEve...
StarcoderdataPython
4893088
import argparse import cv2 import numpy as np import imutils args={} """ ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) """ args["image"] = "../jp.png" image = cv2.imread(args["image"]) cv2.imshow("original", image) cv2.waitKey() ...
StarcoderdataPython
83022
# Copyright (c) 2009-2021 The Regents of the University of Michigan # This file is part of the HOOMD-blue project, released under the BSD 3-Clause # License. """Test that `LocalSnapshot` and `LocalSnapshotGPU` work.""" from copy import deepcopy import hoomd from hoomd.data.array import HOOMDGPUArray import numpy as n...
StarcoderdataPython
8132721
import sms sms.send_sms("+639959064795", "BAL")
StarcoderdataPython
8127890
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.prestige import prestige def test_prestige(): """Test module prestige.py by downloading prestige.csv and testing shape of extracted data h...
StarcoderdataPython
3476489
import re from heapq import heappop, heappush from collections import Counter, defaultdict def calc(n): return n // 3 - 2 def solve(d): return sum(calc(n) for n in d) def read_and_solve(): with open('input_1.txt') as f: data = [int(line.rstrip()) for line in f] return solve(data) if ...
StarcoderdataPython
8167819
<gh_stars>0 # coding=utf-8 """ <NAME>, CC3501, 2019-2 vertices and indices for simple shapes """ import numpy as np # A simple class container to store vertices and indices that define a shape class Shape: def __init__(self, vertices, indices, textureFileName=None): self.vertices = vertices self....
StarcoderdataPython
324415
# -*- coding: utf-8 -*- """ Created on Sep 20, 2012 @author: moloch Copyright 2012 Root the Box 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/licen...
StarcoderdataPython
4904684
<filename>chat/consumers.py from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from django.core.serializers import serialize from django.utils import timezone from django.core.paginator import Paginator import json import asyncio from chat.models import Ro...
StarcoderdataPython
1748545
# Copyright (c) 2014 Red Hat, 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 writ...
StarcoderdataPython
1952375
<gh_stars>10-100 import numpy as np import sys import matplotlib.pyplot as plt from matplotlib import cm import tensorflow.keras.layers as layers from tensorflow.keras.models import Model, load_model from tensorflow.keras.optimizers import Adam import os import colorsys import progressbar LATENT_DIM = int(sys.argv[1])...
StarcoderdataPython
5016765
<filename>examples/ttgo_tdisplay_rp2040/truetype/chango.py<gh_stars>10-100 """ chango.py Test for font2bitmap converter for the driver. See the font2bitmap program in the utils directory. """ from machine import Pin, SoftSPI import st7789py as st7789 import gc from truetype import chango_16 as font_16 from tr...
StarcoderdataPython
3222524
# Для записи цифр римляне использовали буквы латинского алфафита: # I, V, X, L, C, D, M. Например: # # 1 обозначалась с помощью буквы I # 10 с помощью Х # 7 с помощью VII # Число 2020 в римской записи — это MMXX (2000 = MM, 20 = XX). # # Реализуйте функцию to_roman, которая переводит арабские числа в римские. # Функция...
StarcoderdataPython
8084261
from scrounger.core.module import BaseModule # helper functions from scrounger.utils.android import ApktoolYaml from scrounger.utils.config import Log from scrounger.modules.misc.android.app.manifest import Module as ManifestModule from os.path import exists class Module(BaseModule): meta = { "author": "...
StarcoderdataPython
1695472
from script.model.sklearn_like_model.NetModule.InceptionSructure.BaseInceptionNetModule import \ BaseInceptionNetModule from script.util.Stacker import Stacker from script.util.tensor_ops import * class InceptionV4NetModule(BaseInceptionNetModule): def stem(self, stacker, name='stem'): with tf...
StarcoderdataPython
11237665
import fontforge from sys import argv from typing import Iterable from os import path import json DEFAULT_CONFIG_PATH = './font-subset.json' def open_font(font_path) -> fontforge.font: return fontforge.open(font_path) def subset_of_font(source_font: fontforge.font, subset: Iterable[str]) -> fontforge.font: # sel...
StarcoderdataPython
3334013
<reponame>blorente/Open-Publisher #!/usr/bin/env python3 from pathlib import Path import argparse import logging import subprocess import os import shutil from layouts.epub import EPUB_LAYOUT from layouts.paperback import PAPERBACK_LAYOUT project_dir = Path(__file__).parent.parent POSSIBLE_FORMATS = ["epub", "paper...
StarcoderdataPython
6600030
import json def load_commands(): with open('command_mapping.json') as data_file: command_mapping = json.load(data_file) return command_mapping # structure for storing the graph # TODO storing graphs and adding data/determining if the graph is being connected - no way to tell if node is different from ...
StarcoderdataPython
1968667
import numpy as np import rllab.spaces def build_space(shape, space_type, info={}): if space_type == 'Box': if 'low' in info and 'high' in info: low = info['low'] high = info['high'] msg = 'shape = {}\tlow.shape = {}\thigh.shape={}'.format( shape, low.sh...
StarcoderdataPython
3439980
# -*- coding: utf-8 -*- import urllib, urllib2, re, os, sys, math import xbmcgui, xbmc, xbmcaddon, xbmcplugin from urlparse import urlparse, parse_qs #nie chciało mi się więc # @autor - http://svn.sd-xbmc.org/ # Umieszczam stosowne info w changelogu if sys.version_info >= (2, 7): import json as json else: i...
StarcoderdataPython
3564569
<gh_stars>0 # Generated by Django 2.0 on 2017-12-19 13:24 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Author', ...
StarcoderdataPython
6478465
<gh_stars>10-100 """Import metric implementations so they can register themselves.""" from metrics import base from metrics import absolute_coverage from metrics import cherrypick_issue_count from metrics import circleci_flakiness from metrics import circleci_greenness from metrics import circleci_presubmit_latency fro...
StarcoderdataPython
9717735
<reponame>vovchykbratyk/geoindexer """Documentation to follow""" from area import area from collections import OrderedDict from datetime import datetime import fiona from fiona.crs import from_epsg from handlers import Container, Exif, Lidar, Log, Raster, Shapefile import json import os from pathlib import Path import...
StarcoderdataPython
349085
import codecs import os from setuptools import setup, find_packages def read(fname): return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read() PACKAGE = "pinax_theme_foundation" NAME = "pinax-theme-foundation" DESCRIPTION = "Pinax theme based on Zurb's Foundation" AUTHOR = "<NAME>" AUTHOR_EMAIL ...
StarcoderdataPython
3283627
<reponame>madtyn/mvcPython<filename>view/widgets/timepicker.py import time import datetime as dt import tkinter as tk from tkinter import ttk class Timepicker(ttk.Frame): DAY_HOURS = 24 MAX_HOUR = 23 MAX_MINUTES = 59 def __init__(self, parent, hour=None, minute=None, *args, **kwargs): super(...
StarcoderdataPython
4971254
<filename>vizsgaremek/tc01_registration_test.py<gh_stars>0 def test_registration(): import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager options = Options() options.add_argument("--headless") ...
StarcoderdataPython
3221604
<gh_stars>0 # Parameter: # config-file: path to cfg file # weight_path: path to the pretrained weight # dataset_path: path to a directory of images # This script predicts bboxes of every image in the dataset path, # write the ground truth into yolo format .txt filess import argparse import glob import multiprocessing...
StarcoderdataPython
1825228
<filename>service/FunRep/ml.py from .util import * from .similarity import * import os import numpy as np from . import lang from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from gensim import corpora, models, similarities def cosine_kNearest(method, s...
StarcoderdataPython
9735289
<filename>src/contato.py class Contato: def __init__(self) -> None: self.__name = str() self.__email = str() self.__phone = str() self.__message = str() def __str__(self): return f'''Name: {self.name}\nEmail: {self.email}\nTelephone: {self.phone}\nMessage: {self.mess...
StarcoderdataPython
3335008
<reponame>enqack/price-blotter<gh_stars>0 from __future__ import print_function import sys from tabulate import tabulate def print_title(s): """ Print a string as a title with a strong underline Args: s: string to print as a title """ print(s) print(len(s) * "=") p...
StarcoderdataPython
6568489
import unittest from lbrynet.daemon.Daemon import sort_claim_results class ClaimsComparatorTest(unittest.TestCase): def test_sort_claim_results_when_sorted_by_claim_id(self): results = [{"height": 1, "name": "res", "claim_id": "ccc", "nout": 0, "txid": "fdsafa"}, {"height": 1, "name": ...
StarcoderdataPython
11304634
""" A frequent baseline is to take the first three sentences of the article, which works especially well with news articles. For our pre-processed data this should be relatively easy to extract, since it is already sentence-split, and we can therefore simply copy the first few lines. However, we first need to verify th...
StarcoderdataPython
198490
<gh_stars>1000+ import re from functools import lru_cache from validate_email import validate_email import ipaddress try: import urlparse except ImportError: import urllib.parse as urlparse import uuid import struct from jinja2 import Template import time import sys printer = "" # Well known regex mapping. re...
StarcoderdataPython
182892
<reponame>JuniorCru/coastline import json from . import config # Currently EnvState class is just a dict sub-class. # # A dict-like interface may be all we need, but we use a sub-class so we # can change construction later, possibly use an IoC container or type # checking, etc. class EnvState(dict): def __init__(...
StarcoderdataPython
8109564
import numpy as np import matplotlib import matplotlib.pyplot as plt from scipy.interpolate import griddata npzfile = np.load("/home/henry/dev/roomba/logger/2018-08-05_123107_wifi.npz") points = npzfile["points"] * 11.8 # convert to mm values = npzfile["values"] minx=np.amin(points, axis=0)[0] maxx=np.amax(points,...
StarcoderdataPython
1990947
<reponame>salmanAndroidDev/shoply from decimal import Decimal from django.conf import settings from coupons.models import Coupon from shop.models import Product class Cart: """Handy class to store cart data into session""" def __init__(self, request): self.session = request.session cart = s...
StarcoderdataPython
3430822
from .scicar import scicar_mouse_kidney
StarcoderdataPython
11211107
<filename>source/bot/database/models/guild.py<gh_stars>0 import sqlalchemy from sqlalchemy import Column, Integer, String from sqlalchemy.orm import relationship from bot.database import tableBase class Guild(tableBase): __tablename__ = 'guild' guild_id = Column(String(20), primary_key=True) te...
StarcoderdataPython
1882536
import re, argparse def replace_include(infile, outfile): with open(infile, 'r') as data: lines = data.readlines() for line in lines: if re.search("!include", line): idx = lines.index(line) extfile = line.split(' ')[-1].split('\n')[0] with...
StarcoderdataPython
8171795
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-20 16:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('mfctracker', '0003_branch_is_trunk'), ] ...
StarcoderdataPython
210155
path_lbls = "../data/test_labels.npy" path_inpt = "../trial/kudo18.npy" ############ # analysis # ############ from sklearn import metrics import matplotlib.pyplot as plt import numpy as np inpt = np.load(path_inpt) # load labels true_lbl = np.load(path_lbls) topic, stance, reason = zip(*[lbl.split("-") for lbl in ...
StarcoderdataPython
4964623
<reponame>bacuarabrasil/krenak<filename>api/krenak_api/apps/common/models/__init__.py from .core import CoreManager, CoreModel, CoreQuerySet __all__ = ["CoreModel", "CoreManager", "CoreQuerySet"]
StarcoderdataPython
1712148
<filename>mtp_noms_ops/apps/security/views/views.py<gh_stars>1-10 from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.views.generic import TemplateView class PolicyChangeView(TemplateView): if settings.NOVEMBER_SECOND_CHANGES_LIVE: title = _('What the Nov 2n...
StarcoderdataPython
1724670
# -*- coding: utf-8 -*- """ Created on Sun Jan 28 16:39:43 2018 Covariance Matrix Decomposition @author: Satie """ import numpy as np from numpy.linalg import matrix_rank from multiprocessing import Pool class Decomposer(object): def __init__(self, data, preavg, delta)...
StarcoderdataPython
9620396
<filename>huxley/api/views/register.py # Copyright (c) 2011-2017 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). from django.db import transaction from rest_framework import generics, response, status from rest_framework.authentication import S...
StarcoderdataPython
5093907
import mmh3 # type: ignore from neo3.core import serialization, types, Size as s, utils from neo3 import vm class StorageKey(serialization.ISerializable): def __init__(self, id_: int, key: bytes): self.id = id_ self.key = key def __len__(self): return s.uint32 + len(self.key) de...
StarcoderdataPython
5051536
<reponame>gatech-sysml/sam import argparse import os from pathlib import Path import GPUtil import numpy as np import torch from model.smooth_cross_entropy import smooth_crossentropy from model.wide_res_net import WideResNet_Embeds from sam import SAM from utility.bypass_bn import disable_running_stats, enable_runnin...
StarcoderdataPython
3576368
import src.GameOfLife as GoL import src.BriansBrain as BB from src import App from src.const import * def GameOfLife(): grid = App.new_grid() # Spawn a really long vertical line with 10 dead cells on top and bottom for row in range(10, CELLMAP_HEIGHT-10): App.set_cell(grid, CELLMAP_WIDTH//2, ...
StarcoderdataPython
6649366
import pandas as pd import yaml import argparse from sklearn.model_selection import train_test_split from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping from fast_image_classification.models import get_model_classification from fast_image_classification.training_utilities import ( ...
StarcoderdataPython
11344839
from pathlib import Path from rlbot.parsing.bot_config_bundle import BotConfigBundle from autoleague.paths import WorkingDir BotID = str # type alias def make_bot_id(working_dir: WorkingDir, bot_config: BotConfigBundle) -> BotID: path = Path(bot_config.config_directory) / bot_config.config_file_name retur...
StarcoderdataPython
137771
from ..utils import to_value, len_batch from .callback_tensorboard import CallbackTensorboardBased from ..train import utilities from ..train import outputs_trw as O import functools import collections import torch import numpy as np import logging logger = logging.getLogger(__name__) def get_as_image(images): ...
StarcoderdataPython
357835
import json import logging from gala_wit import GalaWit from intenthandlers.utils import get_highest_confidence_entity from intenthandlers.misc import say_quote from intenthandlers.misc import randomize_options from intenthandlers.misc import flip_coin from intenthandlers.conversation_matching import onboarding_conver...
StarcoderdataPython
347481
from distillation.datasets.imagenet_dataset import ImageNet from distillation.datasets.cifar_dataset import CIFAR100 from distillation.datasets.mit67_datasets import MITScenes def dataset_factory(dataset_name, *args, **kwargs): datasets_collection = {} datasets_collection['ImageNet'] = ImageNet data...
StarcoderdataPython
7109
import numpy as np img_dtype = np.float32 imgX, imgY, imgZ = (256, 256, 150) imgs_path_withfaces = '../dataset/withfaces' imgs_path_nofaces = '../dataset/nofaces' imgX_dwt1, imgY_dwt1, imgZ_dwt1 = (128, 128, 75) imgs_path_withfaces_dwt = './dataset/withfaces' imgs_path_nofaces_dwt = './dataset/nofaces' dwt_flag = (...
StarcoderdataPython
1790861
#!/usr/bin/env python3 # precision.py - Precision program by Sergey 2015 # AlgoArt - The Art of Algorithms (github.com/algoart/algoart) """ Arbitrary precision math calculations. decimal.getcontext().prec = p - setting the precision (Default: 40) pi() - Calculates Pi with required precision PI - precalculated valu...
StarcoderdataPython
6529214
<reponame>nparkstar/nauta<filename>applications/cli/commands/experiment/tests/test_view.py # # Copyright (c) 2019 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ht...
StarcoderdataPython
1898570
import os import argparse import sys import pickle from pathlib import Path from jax import random from sklearn.decomposition import PCA from generate_data import gen_source_data from models import init_invertible_mlp_params, invertible_mlp_fwd from train import train def parse(): """Argument parser for all co...
StarcoderdataPython
3420832
<filename>flask_flatpages/page.py<gh_stars>100-1000 """Define flatpage instance.""" import yaml from werkzeug.utils import cached_property class Page(object): """Simple class to store all necessary information about a flatpage. Main purpose is to render the page's content with a ``html_renderer`` functi...
StarcoderdataPython
6488832
from distutils.core import setup with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name='vimspector', python_requires=">=3.6.*", packages=[ 'module', 'module.foobar' ], install_requires=requirements, entry_points={ 'console_scripts': [...
StarcoderdataPython
258682
<reponame>xiaohalo/LeetCode from __future__ import print_function # Time: O(n) # Space: O(1) # # Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. # # If the last word does not exist, return 0. # # Note: A word is defined as a characte...
StarcoderdataPython
243820
# Основной каркас программы from app.player import Player from app.rate import Rate from app.track import Track from app.session import Session from app.file import File from app.utils import * from app.make import * from app.string import * from app.default import default__info # данные программы (дефолт/из файла) ...
StarcoderdataPython
6465593
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsServerResponse. From build dir, run: ctest -R PyQgsServerResponse -V .. note:: This program 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 2 of t...
StarcoderdataPython
3436529
# 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 # # 示例 1: # # 输入: coins = [1, 2, 5], amount = 11 # 输出: 3 # 解释: 11 = 5 + 5 + 1 # 示例 2: # # 输入: coins = [2], amount = 3 # 输出: -1 # 说明: # 你可以认为每种硬币的数量是无限的。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/coin-change # 著作权归领扣网络所有...
StarcoderdataPython
5083075
""" This test is only for Chrome! (Verify that your chromedriver is compatible with your version of Chrome.) """ import colorama from seleniumbase import BaseCase class ChromedriverTests(BaseCase): def test_chromedriver_matches_chrome(self): if self.browser != "chrome": print("\n This test i...
StarcoderdataPython
12826675
<reponame>mhorowitz/pykrb5 # Copyright (c) 2013, <NAME> # 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, # this list of ...
StarcoderdataPython
11333213
<gh_stars>0 import os import sys import shutil import subprocess import config from utils import colors from template import next_step def log_error(logfile='error.log', error="", msg="", exit_on_error=True): if not error: return with open(logfile, 'w') as fd: fd.write(error.decode('utf-8'...
StarcoderdataPython
4934341
"""! @brief Examples of usage and demonstration of abilities of CURE algorithm in cluster analysis. @authors <NAME> (<EMAIL>) @date 2014-2020 @copyright BSD-3-Clause """ from pyclustering.utils import read_sample from pyclustering.utils import timedcall from pyclustering.samples.definitions import S...
StarcoderdataPython
1919668
# -*- coding: utf-8 -*- from os import listdir import pandas import numpy as np from sklearn.externals import joblib DIR = '/home/emil/Code/Kaggle/driver telematics analysis/' drivers = listdir(DIR + 'drivers') countdriver = len(drivers) result = np.empty((0,77)) drivernames = np.empty((countdriver)) countdone =...
StarcoderdataPython
269717
<reponame>toonarmycaptain/deal<gh_stars>0 # built-in import sys from io import StringIO from pathlib import Path from textwrap import dedent # external import pytest # project import deal from deal._cli._test import ( fast_iterator, format_coverage, format_exception, has_pure_contract, run_cases, sys_path, te...
StarcoderdataPython
9765815
<reponame>rancher/management-api<filename>tests/integration/core/common_fixtures.py<gh_stars>1-10 import base64 import cattle import os import pytest import random import time import inspect from datetime import datetime, timedelta import requests import fcntl import logging @pytest.fixture(scope='session', autouse=o...
StarcoderdataPython
135049
<reponame>flyingraijin98/Naive-Bayes-Spam-Classifier<filename>index.py from collections import Counter import pandas as pd import stop_words import random class NLP(): def __init__(self): self.vocab = None def count_vectorizer(self, text, train=True, stop_word=None, view=False): ...
StarcoderdataPython
4814011
#!/usr/bin/env python import os, sys import json from .common import parse_input def write_metadata_file(dest_dir: str, source: dict, attribute: str): with open(os.path.join(dest_dir, attribute), 'w') as metadata_file: metadata_file.write(source[attribute]) def in_(dest_dir, stdin): config = pars...
StarcoderdataPython
4987960
<filename>example/datasets.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: <NAME> @ UvA """ import pandas as pd ### REGRESSION def abalone(wd): ''' 4176 x 7 The first categorical feature is removed http://archive.ics.uci.edu/ml/datasets/Abalone ''' df = pd.read_csv(wd+'abalone...
StarcoderdataPython
1697402
import json import functools IOS_OSS_APPS_DATASET = "../oss_ios_apps/contents_july_2018.json" @functools.lru_cache() def get_project(gh_user, gh_project): """Ola.""" project_name = f"{gh_user}/{gh_project}" datastore = _read_app_dataset() projects = datastore['projects'] return next( (proj...
StarcoderdataPython
8131789
from __future__ import print_function import os import sys import time import pickle import itertools import numpy as np import theano import lasagne from lasagne.utils import floatX from utils import BColors, print_net_architecture import theano.tensor as T from data_pool import DataPool from ba...
StarcoderdataPython
1831533
import RPi.GPIO as GPIO import time sleep_time = 0.5 led_pin = 12 GPIO.setmode(GPIO.BOARD) GPIO.setup(led_pin, GPIO.OUT) def led_blink(sleep_time): GPIO.output(led_pin, True) time.sleep(sleep_time) GPIO.output(led_pin, False) time.sleep(sleep_time) try: while True: led_blink(sleep_time) except KeyboardInte...
StarcoderdataPython
3353662
import os, sys import torch def read_policy(filename, section='init', debug=False, verbose=print): if not os.path.isfile(filename): verbose("file no exist: %s" % filename) return [] policies = [] attr = None valid = False found = False # found policy for the section with open...
StarcoderdataPython
327584
# pylint: disable=invalid-name """ Tests for shilellagh.adapters.api.gsheets.fields. """ import datetime import dateutil.tz from shillelagh.adapters.api.gsheets.fields import GSheetsBoolean from shillelagh.adapters.api.gsheets.fields import GSheetsDate from shillelagh.adapters.api.gsheets.fields import GSheetsDateTim...
StarcoderdataPython
3521090
import boto3 import grovepi import random import time pir_sensor = 8 motion=0 grovepi.pinMode(pir_sensor,"INPUT") from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient mqtt = AWSIoTMQTTClient mq = mqtt("zombie_sensor") mq.configureEndpoint("YOUR.ENDPOINT",8883) mq.configureCredentials("YOUR/ROOT/CA/PATH", "PRIVATE/KEY...
StarcoderdataPython
5190918
<reponame>rhubarbdog/mpr121-keypad<gh_stars>1-10 # gnd rq 3.3v sda scl import pyb import pyboard_keypad as keypad import time i2c = pyb.I2C(2, pyb.I2C.MASTER) switch = pyb.Switch() keypad = keypad.KEYPAD(i2c, 'Y12') ALL_KEYS = [ j+1 for j in range(9) ] + ['*', 0, '#'] while not switch.value(): if keypad.keypad....
StarcoderdataPython
12827456
from django.apps import AppConfig class TogglReportAppConfig(AppConfig): name = 'toggl_report_app'
StarcoderdataPython
1923648
<gh_stars>0 import os from dash_extensions.enrich import DashProxy, MultiplexerTransform # import dash from flask import Flask from flask_login import login_required import dash_bootstrap_components as dbc def create_app(): server = Flask(__name__) server.secret_key = os.environ.get("FLASK_SECRET_KEY", "") ...
StarcoderdataPython
11346200
<reponame>gregbuehler/DeepChat import torch import logging import transformers from abc import ABC, abstractmethod class AbstractModel(ABC): """ Base abstract class for the model """ @abstractmethod def predict(self, user_input, conversation): raise NotImplementedError() @abstrac...
StarcoderdataPython
3507121
<gh_stars>0 # !/usr/bin/env python3 # -*- Coding: UTF-8 -*- # # -*- System: Linux -*- # # -*- Usage: *.py -*- # # Owner: Cloud-Technology LLC. # Source: gitlab.cloud-technology.io # License: BSD 3-Clause License """ ... """ # ============================================================================= # Lo...
StarcoderdataPython
1898306
import os import copy import pickle from threading import main_thread import numpy as np from torch.optim import lr_scheduler import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms import torch_xla import torch_xla.de...
StarcoderdataPython