id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
313089
<reponame>hirmeos/metrics<filename>src/plugins/generic/generic.py from generic.mount_point import GenericDataProvider class GenericEventDataProvider(GenericDataProvider): """ Data Provider class which inherits from GenericDataProvider. It is used to fetch from a particular source and format it into a list...
StarcoderdataPython
8184415
import time import spidev import RPi.GPIO as GPIO __version__ = '0.0.3' class APA102(): def __init__(self, count=1, gpio_data=14, gpio_clock=15, gpio_cs=None, brightness=1.0, force_gpio=False, invert=False, spi_max_speed_hz=1000000): """Initialise an APA102 device. Will use SPI if it's available...
StarcoderdataPython
5041323
""" The CONFIG object is created and exported once __at import time__ Calling CONFIG["KEY"] directly should be sufficient in most cases, except when a config value has changed since importing CONFIG. In that case, create_config_dict() can provide an updated config dict Priority (highest to lowest): ...
StarcoderdataPython
3482364
import cv2 import numpy as np def nothing(x): pass #img = cv2.imread('img.jpeg',-1) cap=cv2.VideoCapture(0) cv2.namedWindow('image') cv2.resizeWindow('image',600,350) #Creating trackbar cv2.createTrackbar('lh','image',0,255,nothing) cv2.createTrackbar('uh','image',0,255,nothing) cv2.createTrackbar('ls','image'...
StarcoderdataPython
12831213
<gh_stars>1-10 from twisted.logger import FileLogObserver, FilteringLogObserver, globalLogPublisher, InvalidLogLevelError, \ Logger, LogLevel, LogLevelFilterPredicate from twisted.python.logfile import DailyLogFile from heufybot.bot import HeufyBot from heufybot.utils.logutils import consoleLogObserver, logFormat f...
StarcoderdataPython
8012331
#!/usr/bin/env python import argparse import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning import operator def str2bool(v): if isinstance(v, bool): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f"...
StarcoderdataPython
6562158
from django.urls import path from . import views urlpatterns = [ path("", views.profile, name="profile"), path("order_history/<order_number>", views.order_history, name="order_history"), ]
StarcoderdataPython
149899
<gh_stars>10-100 # Generated by Django 3.1 on 2020-08-08 16:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="City", fields=[ ( ...
StarcoderdataPython
130764
<reponame>Paul-St-Young/QMC #!/usr/bin/python import h5py import numpy as np import matplotlib.pyplot as plt import pandas import argparse from scipy.optimize import curve_fit def gofrGrabber(h5file,myi,myj): # get gofr list with label "gofr_ion0_myi_myj" dr = 0.0 r = [] GR = [] f = h5py.Fil...
StarcoderdataPython
4857901
<filename>Python Fundamentals/1. Basic Syntax, Conditional Statements and Loops/Exercise/07. Maximum Multiple.py divisor = int(input()) bound = int(input()) max_multiplier = 0 for current_number in range(divisor + 1, bound + 1): if current_number % divisor == 0: max_multiplier = current_number print(max_m...
StarcoderdataPython
4935219
# GHC Codepath - Sandbox - 8 # Module SE101 #!/bin/python3 import math import os import random import re import sys # Calculator to parse natural language and speak in natural language # - Only given 2 operands and all operands < 100 # sample input: # "add two and seven" # "subtract six from four" # sample output...
StarcoderdataPython
10681
<gh_stars>10-100 #!/usr/bin/env python3 # Copyright 2018 Brocade Communications Systems LLC. 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 also obtain a copy of the License at # http://www.apache.or...
StarcoderdataPython
11250509
<gh_stars>0 #Function to capture all the copyright notice from the license file tag = Html tags!! copy_right = None copyright_list = [] is_copyright = False def capture_copyright(tag, copy_right, copyright_list, is_copyright): re_copyright = re.compile(r'copyright (\([Cc@]\)|\d+).*', re.IGNORECASE) re_junk...
StarcoderdataPython
1752174
<gh_stars>0 """ Definition of the Lorenz96 model. Created on 2019-04-16-12-28 Author: <NAME>, <EMAIL> Update with julia/numba implementations and refactored by David Greenberg 02-2020 """ import sys import numpy as np from delfi.simulator.BaseSimulator import BaseSimulator from scipy.integrate import solve_ivp import...
StarcoderdataPython
82441
<reponame>mrdulin/python-codelab<filename>src/stackoverflow/60539392/test_main.py from main import my_func import unittest from unittest.mock import patch class TestMain(unittest.TestCase): @patch('main.MyClass') def test_my_func(self, MockMyClass): mock_my_class_instance = MockMyClass.return_value ...
StarcoderdataPython
150748
import tensorflow.keras from tensorflow.keras import layers import os import matplotlib.pyplot as plt from PIL import Image #from numpy import asarray import numpy as np from tensorflow.keras import backend as K from tensorflow.keras.applications.vgg16 import preprocess_input from tensorflow.keras.preproc...
StarcoderdataPython
4908667
import psycopg2 import testing.postgresql import pytest import pandas as pd from datetime import timedelta import src.ooni.utils as ooni_utils import src.ooni.types as ooni_types import src.shared.types as shared_types import src.shared.utils as shared_utils # TODO make DRY with other test - test utils? @pytest.fix...
StarcoderdataPython
3354133
<gh_stars>0 # Merge subchunks into single data. from datetime import datetime from pathlib import Path import pandas as pd import os import glob from tqdm import tqdm import seaborn as sns import matplotlib.pyplot as plt from config import ELASPIC_RESULTS_FOLDER_PATH as ERFP import logging from log_script import Co...
StarcoderdataPython
12811541
import code import sys from cleo import Command BANNER = """Masonite Python {} Console This interactive console has the following things imported: container as 'app' Type `exit()` to exit.""" class TinkerCommand(Command): """ Run a python shell with the container pre-loaded. tinker """ def...
StarcoderdataPython
5110388
<reponame>kolbt/whingdingdilly ''' # This is an 80 character line # PURPOSE: The intent of this file is to get out a few basic values as text files File : Column 1 Column 2 Column 3 Column 4 gas_pa#_pb#_xa#.txt : time gas...
StarcoderdataPython
8181155
#-*- coding: utf-8 -*- from flask.ext import restful class History(restful.Resource): def get(self): return {'open': 30, 'close': 40}
StarcoderdataPython
261665
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton from django.core.paginator import Page def list_inline_buttons(list_buttons): markup = InlineKeyboardMarkup() for name, callback_data in list_buttons: button = InlineKeyboardButton(name, callback_data=callback_data) markup.ad...
StarcoderdataPython
1680615
<gh_stars>1-10 # Generated by Django 3.1.2 on 2021-06-09 05:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0047_merge_20210609_0534'), ('core', '0047_merge_20210609_0531'), ] operations = [ ]
StarcoderdataPython
9653777
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
StarcoderdataPython
1707526
""" allow a user to enter URL's and receive information on the responsivness \ of that URL """ import sys import urllib2 import json import re from constants import URL_REGEX from constants import NEW_LINE URL_FORMAT_PATTERN = re.compile(URL_REGEX) def make_http_url_requests(): """ for an entered URL, atte...
StarcoderdataPython
3274551
from abc import ABC import torch_geometric as pyg import torch import torch.nn.functional as F import torch.nn as nn import torch_geometric.nn as gnn import torch_geometric.data as tgd from torch_geometric.data import InMemoryDataset import torch_geometric.utils as utils from torch.autograd.function import Fun...
StarcoderdataPython
8113695
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
StarcoderdataPython
4847515
<reponame>yishantao/DailyPractice<filename>Python/pandas/group_by.py # -*- coding:utf-8 -*- """This module is used to test groupby""" import numpy as np import pandas as pd data = pd.DataFrame( {'name': ['zhangsan', 'zhangsan', 'lisi', 'lisi', 'zhangsan'], 'category': ['one', 'two', 'one', 'two', 'one'], 'nu...
StarcoderdataPython
102891
#!/usr/bin/python3 import argparse import os import subprocess import tarfile import tempfile from pathlib import Path from typing import List parser = argparse.ArgumentParser( description='Run k-core decomposition on hypergraphs in a TAR file and report decompositions with interesting cuts.') parser.add_argument...
StarcoderdataPython
1738935
""" Copyright 2013 <NAME> This file is part of CVXPY. CVXPY is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY is distributed in the ho...
StarcoderdataPython
3261651
""" This file is about how to load data from sklearn. Library : sklearn Moduale : datasets Class : load_boston Object : boston_data data : Boston Data For House Prices """ # Import important libraries from sklearn.datasets import load_boston # Object of load_boston boston_data = load_boston() # Get X data an...
StarcoderdataPython
9695480
from typing import Text def good_phone(phone: Text) -> bool: if not phone: return False if len(phone) != 13: return False if not phone.startswith("+375"): return False if not phone[4:].isdigit(): return False return True
StarcoderdataPython
6662943
<filename>raphael/app/modules/user/models.py<gh_stars>0 # encoding: utf-8 from __future__ import division, absolute_import, with_statement, print_function import collections from raphael.utils.dao.context import DBContext from raphael.utils.dao import query from raphael.utils import strings, cache, num, encrypt, time...
StarcoderdataPython
313464
<reponame>dev-ciberc/ciberc-ca import json import os import pandas as pd class PingMerge: def __init__(self, file_src, file_dst) -> None: # -- # final dataframe compared and validated self.data = None # -- # contains the upload data of the files self.file_src = fi...
StarcoderdataPython
1856497
<reponame>jovi521/swsw import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.basemap import Basemap import sys import os import time from fy4a import FY4A_AGRI_L1 def create_img(file_path, geo_range, save_dir): ''' file_path:需要解析的文件路径 geo_range:需要裁剪的区域范围和粒度,格式:最小纬度,最大纬度,最小经度,最大经度,粒度...
StarcoderdataPython
88365
import pandas as pd import numpy as np import re from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import OneHotEncoder from sklearn.decomposition import PCA , TruncatedSVD import joblib from sklearn.manifold import TSNE # import seaborn as sns import matplotlib.pyplot as ...
StarcoderdataPython
4826825
<filename>tests/test_0341-parquet-reader-writer.py # BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE from __future__ import absolute_import import sys import os import pytest import numpy import awkward1 pyarrow_parquet = pytest.importorskip("pyarrow.parquet") def test_wr...
StarcoderdataPython
9772064
# %% import pandas as pd # %% full_df = pd.read_csv("train/iris.csv") # %% sample = full_df.groupby("class").apply(lambda x: x.sample(n=10)) # %% sample.drop(columns=["class"], inplace=True) # %% sample.to_json("test_batch_inference_input.jsonlines", orient="records", lines=True) # %%
StarcoderdataPython
1621062
from typing import List, Tuple import pp from pp.component import Component @pp.autoname def coupler_straight( length: float = 10.0, width: float = 0.5, gap: float = 0.27, layer: Tuple[int, int] = pp.LAYER.WG, layers_cladding: List[Tuple[int, int]] = [pp.LAYER.WGCLAD], cladding_offset: float =...
StarcoderdataPython
12850893
import os import random import numpy as np import pandas as pd def set_random_seed(seed=42): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.random.seed(seed) def set_display_options(): pd.set_option("max_colwidth", 1000) pd.set_option("max_rows", 50) pd.set_option("max_column...
StarcoderdataPython
6403829
from exapi.models_mappers.hitbtc.base.interface import IHitbtcBaseModelsMapper from exapi.models_mappers.hitbtc.base.mapper import HitbtcBaseModelsMapper
StarcoderdataPython
3282286
<filename>CmBoy.py #!/usr/bin/env python3 import json import argparse from cm_boy.CmAlgo import CmAlgo from cm_boy.CmBark import CmBark from cm_boy.CmClient import CmClient from cm_boy.CmFilter import CmFilter from cm_boy.CmSession import CmSession def main(forward_args=None): """ a good boy that first gets...
StarcoderdataPython
5047748
from typing import Dict import argparse import logging from overrides import overrides from allennlp.commands.subcommand import Subcommand from allentune.commands.report import Report from allentune.commands.search import Search from allentune.commands.plot import Plot logger = logging.getLogger(__name__) # pylint: ...
StarcoderdataPython
4904148
<reponame>Samuel-Melo890/Python-Desafios print('='*8,'Tratando Vários Valores v1.0','='*8) n = qn = s = 0 while n != 999: n = int(input('Digite um número inteiro qualquer [999 é a condição de parada]: ')) if n != 999: qn += 1 s += n print('Você digitou {} números e o valor da soma entre eles fo...
StarcoderdataPython
8187961
<gh_stars>10-100 import pickle from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from toontown.toonbase import TTLocalizer class DistributedLeaderBoardAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory('Distribute...
StarcoderdataPython
5008487
## @ingroupMethods-Noise-Fidelity_One-Noise_Tools # print_airframe_output.py # # Created: Oct 2020, <NAME> # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- import numpy as np from SUAVE.Core ...
StarcoderdataPython
5137801
""" Created by howie.hu at 2022-01-21. Description: 执行备份动作 - 文章备份命令: PIPENV_DOTENV_LOCATION=./pro.env pipenv run python src/backup/action.py - 准备数据命令: PIPENV_DOTENV_LOCATION=./pro.env pipenv run python src/collector/collect_factory.py Changelog: all notable changes to this file will be docum...
StarcoderdataPython
83051
<filename>apps/usuarios/models.py # from django.db import models # Create your models here. # comentarios, sera un capo de texto mas relacion comentario a comentario # los itens que pueden ser comentados tendran la llave foranea # el delete no en casacada
StarcoderdataPython
1773228
<reponame>TouchPal/guldan<filename>app/db.py<gh_stars>10-100 # -*- coding: utf-8 -*- import contextlib import logging import random from flask import request, g from sqlalchemy import create_engine as sqlalchemy_create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_ses...
StarcoderdataPython
8190391
<reponame>ldbc/sigmod2014-pc-graphblas from abc import ABC, abstractmethod from collections import namedtuple import logging from loader.data_loader import DataLoader Test = namedtuple('Test', ['inputs', 'expected_result']) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(leveln...
StarcoderdataPython
6507203
<gh_stars>0 #Given an array and an integer k, rotate the array by k spaces. Do this without generating a new array and without using extra space. #Here's an example and some starter code def rotate_list(nums, k): # Fill this in. l = len(nums) m = k%l for i in range(m): firstNum = nums[0] ...
StarcoderdataPython
76642
<gh_stars>1-10 from django.db import models class Titleable(models.Model): title = models.CharField( verbose_name='Название', max_length=200, blank=True ) class Meta: abstract = True class Textable(models.Model): text = models.TextField( verbose_name='Текст'...
StarcoderdataPython
289260
from cloudshell.shell.core.driver_context import ResourceCommandContext, AutoLoadDetails, AutoLoadAttribute, \ AutoLoadResource from collections import defaultdict class LegacyUtils(object): def __init__(self): self._datamodel_clss_dict = self.__generate_datamodel_classes_dict() def migrate_autol...
StarcoderdataPython
3553156
<filename>seedsource_core/django/seedsource/management/commands/populate_climate_data.py import os import numpy import pyproj from django.core.management.base import BaseCommand from django.db import transaction from ncdjango.models import Service, Variable from netCDF4 import Dataset from trefoil.geometry.bbox import...
StarcoderdataPython
298590
import os import json import numpy as np import pandas as pd save_as_csv = False print_latex = True def print_scores(model_desc: dict) -> None: return " ".join( [f"{key}@{k}={model_desc[key][i][1]}" for key in ("hit", "ndcg") for i, k in enumerate(model_desc['ks'])]) def print_mean(models: list) -> str...
StarcoderdataPython
5038617
<filename>scripts/analysis/submit.py #!/usr/bin/env python import os import sys import subprocess from datetime import datetime from datetime import timedelta import time import time year=2014 month=9 count=0 for month in range(7,11): for day in xrange(31): day += 1 start=datetime(year, month, da...
StarcoderdataPython
9659198
#!/usr/bin/env python #----------------------------------------------------------------------------- # Title : PyRogue feb Module #----------------------------------------------------------------------------- # File : _feb.py # Created : 2017-02-15 # Last update: 2017-02-15 #------------------------------...
StarcoderdataPython
6499179
# Copyright 2017 Scalyr 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 writing, so...
StarcoderdataPython
8058495
<filename>nSum.py """ You are given an array of n integers and a number k. Determine whether there is a pair of elements in the array that sums to exactly k. For example, given the array [1, 3, 7] and k = 8, the answer is “yes,” but given k = 6 the answer is “no.” Ex) --------------------------------------------...
StarcoderdataPython
5054610
<filename>pandas/reset_dataframe_index.py original_df = original_df.set_index("序号")
StarcoderdataPython
5031436
<filename>models/modules/rnlu.py import torch from torch.autograd.function import InplaceFunction from torch.autograd import Variable import torch.nn as nn import math class BiReLUFunction(InplaceFunction): @classmethod def forward(cls, ctx, input, inplace=False): if input.size(1) % 2 != 0: ...
StarcoderdataPython
11265196
<reponame>sunlightlabs/foodtrucks #!/bin/python import re import sys transformations = { re.compile(r'l\'?enfant', re.I): lambda complete, extracted: len(extracted.strip())>0 and extracted + " S.W." or "L'Enfant Plaza Metro", re.compile(r'mcpherson', re.I): lambda complete, extracted: len(extracted.strip())>...
StarcoderdataPython
6491756
""" ------------------------------------------------------------------------- AIOpening - __init__.py Defines all RL algorithms that live in aiopening created: 2017/09/01 in PyCharm (c) 2017 Sven - ducandu GmbH ------------------------------------------------------------------------- """ from .a3c import A3...
StarcoderdataPython
12861744
from suppy.utils.stats_constants import DIVERGENCE, TYPE from typing import Any, Dict from suppy.simulator.atomics.atomic import Atomic class DivergenceAtomic(Atomic): def __init__(self, uid: str, seh, name: str): Atomic.__init__(self, uid, seh, name, 0, 0) def get_stats(self) -> Dict[str, Any]: ...
StarcoderdataPython
3553800
<filename>exoplanet-ml/astronet/ops/testing.py # Copyright 2018 The Exoplanet ML Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
StarcoderdataPython
6514823
from django.contrib import admin from .models import Qusetion, Choice # Register your models here. class QusetionAdmin(admin.ModelAdmin): list_display = ('number', 'content') class ChoiceAdmin(admin.ModelAdmin): list_display = ('question', 'content', 'score') admin.site.register(Qusetion, QusetionAdmin) adm...
StarcoderdataPython
1947196
<filename>tests/test_radionet.py import unittest from mopidy_radionet.radionet import RadioNetClient class RadioNetClientTest(unittest.TestCase): def test_get_api_key(self): radionet = RadioNetClient() radionet.get_api_key() self.assertIsNotNone(radionet.api_key) def test_get_top_s...
StarcoderdataPython
1846312
from sandbox_42 import app app.run(host='127.0.0.1', debug=True)
StarcoderdataPython
3433325
class OutOfCoreArray(object): def __init__(self, array_opener): self.array_opener = array_opener def __getitem__(self, item): with self.array_opener.open_array(mode="r") as a: return a[item] def __setitem__(self, item, value): with self.array_opener.open_array(mode="a")...
StarcoderdataPython
184637
# Generated from STIXPattern.g4 by ANTLR 4.9.2 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u596...
StarcoderdataPython
8159967
import theading class stats(): """ """ def __init__(self, github): self.github = github self.process() self.kick_off = 1 self.last_limit = 5000 def process(self): self.calculate_kickoff() threading.Timer(self.kick_off, self.process).start() def calculate_kickoff(self): pass
StarcoderdataPython
376259
<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-09 13:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('omniforms', '0002_omniformsaveinstancehandler...
StarcoderdataPython
1901811
<filename>tasker/encoder/compressor/dummy.py<gh_stars>0 from . import _compressor class Compressor( _compressor.Compressor, ): name = 'dummy' @staticmethod def compress( data, ): compressed_object = data return compressed_object @staticmethod def decompress( ...
StarcoderdataPython
6557512
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from .models import UserFav from apps.users.serializers import UserSerializer class UserFavSerializer(serializers.ModelSerializer): """用户收藏的序列化函数""" user = serializers.HiddenField( default=serializer...
StarcoderdataPython
3502798
<reponame>mndarren/Speedup-Work-Lib<gh_stars>0 #!/usr/bin/env python """ .. current_module:: simple_log.py .. created_by:: <NAME> .. created_on:: 04/25/2021 This python script is a simple log. """ import sys from datetime import datetime from inspect import getframeinfo, stack TIME_FORMAT = '%m/%d/%Y %H:%M:%S' clas...
StarcoderdataPython
6612909
"""Flight category by hour""" import datetime import numpy as np import pytz from pandas.io.sql import read_sql import matplotlib.colors as mpcolors from matplotlib.patches import Rectangle from pyiem.plot.use_agg import plt from pyiem.util import get_autoplot_context, get_dbconn, utc from pyiem.exceptions import NoDa...
StarcoderdataPython
1820353
<reponame>nukemberg/git2elastic<filename>git2elastic/__init__.py # MIT license, see LICENSE.txt import click import git import elasticsearch, elasticsearch.helpers import pkg_resources import json import os.path import itertools import hashlib from collections import defaultdict def default_es_mappings(): resourc...
StarcoderdataPython
1657761
import pytest import numpy as np from fri.model.ordinal_regression import ordinal_scores as score @pytest.fixture() def data(): y = np.array([0, 1, 2, 3]) return y @pytest.fixture() def imb_data(): y = np.array([0, 1, 2, 2, 2, 2]) return y def reverse_label(y): y = np.copy(y) return np.fl...
StarcoderdataPython
150891
""" Defines types and operations related to MINC files. """ from dataclasses import dataclass from os import PathLike from typing import Literal, TypeVar, Generic, Optional from civet.bases import DataFile from civet.extraction.kernels import ngh_count_kernel _M = TypeVar('_M', bound='GenericMinc') _V = TypeVar('_V',...
StarcoderdataPython
3433680
#-*- coding: utf-8 -*- from __future__ import print_function, division """ Pytorch useful tools. """ import torch import os import errno import numpy as np def save_checkpoint(net, best_perf, directory, file_name): print('---------- SAVING MODEL ----------') if not os.path.isdir(directory): os.maked...
StarcoderdataPython
6614550
#import necessary packages from mrcnn.config import Config from mrcnn import model as modellib from mrcnn import visualize import numpy as np import colorsys import argparse import imutils import random import cv2 import os #construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_arg...
StarcoderdataPython
1997056
<filename>udemy-data-structures-and-algorithms/14-linked-lists/14.5_linked_list_nth_to_last_node.py ''' Write a function that takes a head node and an integer value n and then returns the nth to last node in the linked list. ''' from nose.tools import assert_equal class Node(object): def __init__(self, value): ...
StarcoderdataPython
3254312
<filename>Telstra_Messaging/api/authentication_api.py<gh_stars>10-100 # coding: utf-8 """ Telstra Messaging API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 2.2.10 Generated by: https://op...
StarcoderdataPython
1633757
class Solution: def XXX(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) i = 0 j = 0 while (i < (n-1)/2 ): j = 0 while (j < n/2 ): tmp = matrix[i][j]...
StarcoderdataPython
224337
<filename>manage.py from flask_script import Manager, Server from app import create_app, db from app.models import User, Pitch, Comment from flask_migrate import Migrate, MigrateCommand # Creating app instance app = create_app('production') manager = Manager(app) migrate = Migrate(app,db) manager.add_command('serv...
StarcoderdataPython
3458419
# Generated by Django 2.1.2 on 2019-10-03 18:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0089_merge_20190930_1519'), ('core', '0089_auto_20191003_1836'), ] operations = [ ]
StarcoderdataPython
12866441
<gh_stars>10-100 #!/usr/bin/env python """ CLI tool to runs various tasks related to QA. """ import os import time from pathlib import Path import sys import traceback import json import yaml import uuid import datetime import click from .run import RunContext from .runners import runners, Job, JobGroup from .runners...
StarcoderdataPython
6478517
#!/usr/bin/env python # coding=utf-8 import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import csv import os import re import xlsxwriter import datetime # from lib.data_change_Time import data_change_Time # from lib.txt_To_xlsx import txt_To_xlsx import glob import sys # def Merg...
StarcoderdataPython
4938824
<gh_stars>0 import shutil import os import stat import pathlib """ Additional Help stat.S_IRWXU -- mask for file owner permissions stat.S_IRWXG -- mask for file group permissions stat.S_IROTH -- others have read permissions stat.S_IXOTH -- others have exicute permissions """ def ensure_dir_permissions(path): p...
StarcoderdataPython
1784493
<filename>regalloc/testmain.py from regalloc import regalloc from codegen import codegen import json import argparse import sys REG_PREFIX = "r_" if __name__ == '__main__': parser = argparse.ArgumentParser(description='register allocation for bril json format') parser.add_argument("--stats", action="store_tru...
StarcoderdataPython
11339006
<filename>chippy/instructions.py import random class Opcode(object): """CHIP8 / SCHIP opcode datatype. Opcodes are 16-bit ints and are generally of the form: 'GXYN', 'GXNN' or 'GNNN'; where G : 4-bit opcode group id, X, Y : 4-bit register ids, NN : 8-bit constant, NNN: 12-bit address. ...
StarcoderdataPython
4920727
import numpy as np import pandas as pd from matplotlib import pyplot as plt from enduse.stockobjects import Equipment, RampEfficiency, EndUse, Building from enduse.stockturnover import BuildingModel from enduse.oedi_tools import LoadProfiles res_oedi_puma = { "segment": "resstock", "weather_type": "tmy3", ...
StarcoderdataPython
9683155
"""A collection of policy networks.""" import numpy as np import tensorflow as tf import sonnet as snt class Policy(object): """The base class for policy networks. Policy parameters are allowed to be functions of other policies. To keep track of such dependencies, each policy stores a list of parent poli...
StarcoderdataPython
5021915
<filename>Model Development/parameters.py<gh_stars>0 ################################################# # parameter file for St. Anna project ################################################ import numpy as np from sklearn.model_selection import ParameterGrid from ml_classes import ModelDevelopment from dataclasses im...
StarcoderdataPython
1825680
<reponame>michellemark/html2ans import pytest from html2ans.parsers.text import ListParser parser = ListParser() @pytest.fixture(params=[ '<ol></ol>', '<ul></ul>', ]) def valid_list_tag(request): return request.param def test_empty(make_tag): tag = make_tag('<ol></ol>', 'ol') assert not parser...
StarcoderdataPython
3390145
# Generated by Django 3.0.1 on 2019-12-29 14:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WebAXEL', '0009_auto_20191229_1505'), ] operations = [ migrations.AddField( model_name='document', name='description...
StarcoderdataPython
281809
from bs4 import BeautifulSoup import time import requests from django.shortcuts import render, redirect from django.urls import reverse from django.http import HttpResponse from django.views import View from django.views.generic.edit import CreateView, DeleteView from scraper.models import Serie BASE_URL = "http://fmo...
StarcoderdataPython
6514854
def index_power(array: list, n: int) -> int: try: return pow(array[n], n); except IndexError: return -1;
StarcoderdataPython
221240
<filename>gertrude/cogs/games/game_cog.py import discord import logging from .tictactoe import Tictactoe from .rps import Rockpaperscissors from .dice import Dice from discord.ext.commands import Bot, Cog from discord.ext import commands log = logging.getLogger(__name__) class Game(Cog): def __init__(self, bot: Bo...
StarcoderdataPython
3233391
<filename>awsSchema/dynamodb.py # AUTOGENERATED! DO NOT EDIT! File to edit: dynamodb.ipynb (unless otherwise specified). __all__ = [] # Cell #export from dataclasses import field from dataclasses import dataclass, field from dataclasses_json import dataclass_json, Undefined
StarcoderdataPython