id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1617629
<filename>checkov/cloudformation/checks/resource/aws/RDSPubliclyAccessible.py from checkov.cloudformation.checks.resource.base_resource_value_check import BaseResourceValueCheck from checkov.common.models.enums import CheckResult, CheckCategories class RDSPubliclyAccessible(BaseResourceValueCheck): def __init__(...
StarcoderdataPython
54690
<reponame>kzl/lifelong_rl from collections import deque, OrderedDict import numpy as np from lifelong_rl.util import eval_util from lifelong_rl.util.eval_util import create_stats_ordered_dict from lifelong_rl.data_management.utils.path_builder import PathBuilder from lifelong_rl.samplers import StepCollector class ...
StarcoderdataPython
1757028
from django.template import Library from django.utils.safestring import mark_safe from HTMLParser import HTMLParser register = Library() @register.filter def custom_safe(value): html_parser = HTMLParser() unescaped = html_parser.unescape(value) return mark_safe(unescaped)
StarcoderdataPython
11862
<gh_stars>1-10 """A small sphinx extension to let you configure a site with YAML metadata.""" from pathlib import Path # Transform a "Jupyter Book" YAML configuration file into a Sphinx configuration file. # This is so that we can choose more user-friendly words for things than Sphinx uses. # e.g., 'logo' instead of ...
StarcoderdataPython
1726281
<filename>MAGE/urls.py # coding: utf-8 ''' @license: Apache License, Version 2.0 @copyright: 2007-2013 <NAME> @author: <NAME> ''' from django.urls import include, path from django.conf.urls import url from django.contrib.admin import autodiscover from django.contrib.auth import views as auth_views from ref...
StarcoderdataPython
129795
from .lattice import Lattice class LiebLattice(Lattice): def initialize(self): self.addLatticevector([2, 0]) self.addLatticevector([0, 2]) self.addBasisvector([0, 0]) self.addBasisvector([1, 0]) self.addBasisvector([0, 1])
StarcoderdataPython
1636395
<gh_stars>1-10 import ADM_image # Recompute dest image source/dest # Taking aspect ratio into account # Ported from js mean (c) 2011 # aspectRatio=[ (1.,0.888888,1.185185), # NTSC 1:1 4:3 16:9 (1.,1.066667,1.422222), # PAL 1:1 4:3 16:9 (1.,0.888888,1.185185), # FILM 1:1 4:3 16:9 ] fps_predef=[ 29970, 2500...
StarcoderdataPython
1772149
import sys import math # Auto-generated code below aims at helping you parse # the standard input according to the problem statement. r_1 = int(input()) r_2 = int(input()) def sum_digit(number): """ Calculate the sum of a number's digits """ assert type(number) == int number_str = str(number) ...
StarcoderdataPython
3377202
<reponame>d3no/mocean-sdk-python class AbstractAuth: def get_auth_method(self): raise NotImplementedError("AbstractAuth is a abstract class") def get_params(self): raise NotImplementedError("AbstractAuth is a abstract class")
StarcoderdataPython
3374790
<reponame>JMAlego/NAVTool<gh_stars>0 """Supported protocol implementations.""" from os import path, listdir, getcwd, chdir from importlib import import_module PROTOCOLS = set( map( lambda x: path.splitext(x)[0], filter(lambda x: not x.startswith("_") and path.splitext(x)[-1] == ".py", ...
StarcoderdataPython
1648901
<gh_stars>10-100 import os, datetime, socket, logging, time, pickle import pyev from ..config import config from ..sendmail import send_mail # L = logging.getLogger('notify') # class stash(object): # Example structure of self.data dict is: # { # "<EMAIL>": [] # List of lines to be included in the mail # "<E...
StarcoderdataPython
79420
<gh_stars>0 # OpenWeatherMap API Key weather_api_key = "<KEY>" # Google API Key g_key = "<KEY>"
StarcoderdataPython
1645832
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=400) address = models.CharField(max_length=500) class Cook(models.Model): name = models.CharField(max_length=300) restaurant = models.Forei...
StarcoderdataPython
3395779
import sys import os import datetime import platform import random import taichi def get_os_name(): name = platform.platform() if name.lower().startswith('darwin'): return 'osx' elif name.lower().startswith('windows'): return 'win' elif name.lower().startswith('linux'): return ...
StarcoderdataPython
33108
<reponame>BlazesRus/Bforartists # Blender directX importer # version baby # litterature explaining the parser directions : # I don't want to load the whole file as it can be huge : go chunks # also I want random access to 3d datas to import pieces, not always everything # so step1 is a whole file fast parsing, retrie...
StarcoderdataPython
1774553
<filename>pywincffi/dev/testutil.py """ Test Utility ------------ This module is used by the unittests. """ import os import socket import subprocess import sys from random import choice from string import ascii_lowercase, ascii_uppercase from textwrap import dedent from cffi import FFI from mock import patch try: ...
StarcoderdataPython
1743997
<gh_stars>1-10 # Python Version: 3.x name = 'online-judge-tools' __author__ = '<NAME>' __email__ = '<EMAIL>' __license__ = 'MIT License' __url__ = 'https://github.com/kmyk/online-judge-tools' __version_info__ = ( 0, 1, 41, 'final', 0 ) __version__ = '.'.join(map(str, __version_info__[: 3]))
StarcoderdataPython
74698
<filename>django/engagementmanager/tests/test_add_feedback.py # # ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. # =================...
StarcoderdataPython
124579
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from tqdm import tqdm, tqdm_notebook import pandas as pd def create_bars(df, col, m, bartype="tick"): ''' Function to compute various types of bars, depending on column passed # args df: dataframe of tick price data p: name of column in df t...
StarcoderdataPython
112605
import vim import json class config_manager: def __init__(self, root_path): try: self.root_path = root_path self.marked = [] self.load_array = None self.err = None with open(root_path + '/.vim-sync', 'r') as f: self.load_array = js...
StarcoderdataPython
1649815
from pydoc2md import main main( "/Users/federicoclaudi/Documents/Github/bg-atlasapi/bg_atlasapi", "/Users/federicoclaudi/Documents/Github/bg-atlasapi/docs/md", githuburl="https://github.com/brainglobe/bg-atlasapi", ) # main("pydoc2md", "Docs", githuburl="https://github.com/FedeClaudi/pydoc2md")
StarcoderdataPython
3294127
import scrape.api import scrape.auth def main(): session = scrape.auth.get_session() investment_summary = scrape.api.get_investment_summary(session) investment_history = scrape.api.get_investment_history(session) unit_prices = scrape.api.get_unit_prices(session)["unit_prices"] aud_balance = flo...
StarcoderdataPython
3257312
# -*- coding: utf-8 -*- from __future__ import unicode_literals from cms.toolbar_base import CMSToolbar from cms.toolbar_pool import toolbar_pool from cms.constants import RIGHT @toolbar_pool.register class LayouterModifier(CMSToolbar): def populate(self): # classes for scripting and styling extr...
StarcoderdataPython
1628620
<reponame>PythonForChange/Egg from egg.resources.utils import colour BLACK=30 RED=31 GREEN=32 YELLOW=33 BLUE=34 PURPLE=35 CYAN=36 WHITE=37 black=colour(BLACK) red=colour(RED) green=colour(GREEN) yellow=colour(YELLOW) blue=colour(BLUE) purple=colour(PURPLE) cyan=colour(CYAN) white=colour(WHITE)
StarcoderdataPython
64727
<reponame>danielfsousa/algorithms-solutions<gh_stars>1-10 from collections import deque graph = {'you': ['alice', 'bob', 'claire'], 'bob': ['anuj', 'peggy', 'you', 'anuj'], 'alice': ['peggy'], 'anuj': [], 'peggy': ['bob', 'you'], 'thom': [], 'claire': ...
StarcoderdataPython
3215209
<filename>jp.atcoder/practice2/practice2_g/26020641.py import sys import typing import numba as nb import numpy as np @nb.njit def sort_csgraph( n: int, g: np.ndarray, ) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray]: sort_idx = np.argsort(g[:, 0], kind='mergesort') g = g[sort_idx] edge_...
StarcoderdataPython
1656713
#!/usr/bin/env python3 """ Refactored version of Part 1a. It turned out to be slow for Part 2. """ from collections import deque from typing import Deque, List class Rotator: def __init__(self, digits: str) -> None: self.d: Deque[int] = deque([int(x) for x in digits]) self.MIN = min(self.d) ...
StarcoderdataPython
7716
<reponame>davisidarta/dynamo-release<gh_stars>0 import numpy as np from ..tools.utils import update_dict from .utils import save_fig def plot_direct_graph(adata, layout=None, figsize=[6, 4], save_show_or_return='show', save_kwargs...
StarcoderdataPython
39494
<reponame>Kgoetsch/sklearn_pipeline_enhancements import numpy as np import pandas as pd from patsy.highlevel import dmatrix from sklearn.base import TransformerMixin, BaseEstimator from sklearn.pipeline import _name_estimators, Pipeline __author__ = 'kgoetsch' def make_dataframeunion(steps): return DataFrameUnio...
StarcoderdataPython
3378921
from boa3.builtin.type import UInt160 class Policy: @classmethod def get_fee_per_byte(cls) -> int: """ Gets the network fee per transaction byte. :return: the network fee per transaction byte :rtype: int """ pass @classmethod def get_exec_fee_factor(cl...
StarcoderdataPython
1678439
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # -*- coding: utf-8 -*- import tensorflow as tf from .. import builder from ..registry import DETECTORS from .base import BaseDetector from .test_mixins import BBoxTestMixin, RPNTestMixin @DETECTORS.regist...
StarcoderdataPython
1709967
<gh_stars>0 """Subclass of testFrame2, which is generated by wxFormBuilder.""" import wx import opg #from astropy.coordinates import Angle import obsPlanGraphs # Implementing testFrame2 class opg_testFrame2( opg.testFrame2 ): def __init__( self, parent ): opg.testFrame2.__init__( self, parent ) # Handl...
StarcoderdataPython
1794698
<reponame>demitri/cornish #!/usr/bin/env python from typing import Iterable import numpy as np from ..ast_object import ASTObject class ASTMapping(ASTObject): ''' :param ast_object: an existing :class:`starlink.Ast.Mapping` object ''' def __init__(self, ast_object=None): super().__init__(ast_object=ast_obje...
StarcoderdataPython
1767186
<reponame>gitrymt/qgm import copy import numpy as np import scipy as sp from scipy.signal import find_peaks import pandas as pd import cv2 from PIL import Image from . import image, function, fitting from . import filter def select_interporation(interporation, library): if library == 'OpenCV': if inter...
StarcoderdataPython
3372106
<reponame>YelloFam/python-dependency-injector """Configuration(yaml_files=[...]) tests.""" from dependency_injector import providers from pytest import fixture, mark, raises @fixture def config(config_type, yaml_config_file_1, yaml_config_file_2): if config_type == "strict": return providers.Configuratio...
StarcoderdataPython
3362297
<gh_stars>1-10 from grafo import Grafo from vertice import Vertice g = Grafo() # Fase 2 INE5405 = Vertice("Probabilidade e Estatística", 5) MTM7174 = Vertice("Cálculo B para Computação", 4) # Fase 3 INE5409 = Vertice("Cálculo Numérico para Computação", 4) # Fase 4 INE5412 = Vertice("Sistemas Operacionais I", 4) INE...
StarcoderdataPython
1711413
<filename>day20/part1/donut.py import sys import numpy as np directions = { 'UP': (-1, 0), 'DOWN': (1, 0), 'RIGHT': (0, 1), 'LEFT': (0, -1), } portals = {} # Build dictionary of portals def find_portals(maze): for i in range(maze.shape[0]): for j in range(maze.shape[1]): pos,...
StarcoderdataPython
3305174
import logging import json from textwrap import dedent from airflow.hooks.postgres_hook import PostgresHook from util.loader import column_names as col from util.loader import provider_details as prov from psycopg2.errors import InvalidTextRepresentation logger = logging.getLogger(__name__) LOAD_TABLE_NAME_STUB = 'pr...
StarcoderdataPython
3329288
<reponame>ColdFrenzy/Adaptive_Learning<filename>utils/pre_compute_elo.py import sys import os import random import numpy as np import math import logging sys.path.insert(1, os.path.abspath(os.pardir)) from tqdm import tqdm from config.custom_config import Config from config.connect4_config import Connect4Config,Conne...
StarcoderdataPython
3301291
<reponame>tuyendq/lthwmongodb<gh_stars>0 #!/usr/bin/env python import json # import urllib2 import urllib3 import pymongo # connect to mongo connection = pymongo.MongoClient("mongodb://localhost") # get a handle to the reddit database db = connection.reddit stories = db.stories # drop existing collection stories.dr...
StarcoderdataPython
127512
<filename>tests/views.py from django.http import HttpResponse, HttpResponseForbidden from bukdjango_multiform.views import MultiFormTemplateView from .forms import Form1, Form2 class MyMultiFormTemplateView1(MultiFormTemplateView): template_name = 'index.html' multiform_field_name = 'zxc' multiforms = { ...
StarcoderdataPython
3385222
<reponame>yoshson/workbench # Generated by Django 3.0.3 on 2020-02-19 11:34 from django.conf import settings from django.db import migrations from workbench.tools import search class Migration(migrations.Migration): dependencies = [ ("deals", "0001_initial"), ] operations = [ migration...
StarcoderdataPython
110967
from django.shortcuts import render, redirect from django.http import HttpResponse from reveal.models import Reveal, get_content_object from reveal import app_settings from reveal import cipher def reveal_info(request, info_attr, app_label=None, model=None, object_id=None, no_js=None):...
StarcoderdataPython
6498
import numpy as np from pyad.nn import NeuralNet from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split np.random.seed(0) data = load_breast_cancer() X_train, X_test, y_train, y_test = train_test_split( data.data, data.target, train_size=0.8, random_state=0 ) nn = Ne...
StarcoderdataPython
3390244
from unittest.mock import patch import pytest from sagemaker_mlflow_container import const from sagemaker_mlflow_container._utils import _conda_info, _copy_environ_and_prepend_path, \ _extract_conda_file_name, _find_mlproject_file_path, _get_conda_env_bin_path, _mapping_to_mlflow_hyper_params, \ _mapping_to_ml...
StarcoderdataPython
6455
import setuptools # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setuptools.setup( name="atm76", version="0.1.0", author="<NAME>", a...
StarcoderdataPython
164236
import imageio # imageio.plugins.ffmpeg.download() import numpy as np import os import argparse import process_anno from tqdm import tqdm import torch import torchvision.transforms as trn from spatial_transforms import ( Compose,ToTensor) import json def extract_frames(output, dirname, filenames, frame_num, anno): tr...
StarcoderdataPython
1615149
import threading from contextlib import contextmanager import attr @attr.s(slots=True) class Settings(object): """ :param strict: boolean to indicate if the lxml should be parsed a 'strict'. If false then the recover mode is enabled which tries to parse invalid XML as best as it can. :type s...
StarcoderdataPython
3275301
# -*- coding: utf-8 -*- # @Author: Administrator # @Date: 2019-05-23 18:19:15 # @Last Modified by: Administrator # @Last Modified time: 2019-05-23 18:23:05 __all__ = [ "task_download_favorite_matches", ] import os from ...client.botzone import BotzoneClient from ...client.bean import FavoriteMatchBean f...
StarcoderdataPython
1778910
<gh_stars>0 # -*- coding:utf-8 -*- from codelieche.views.viewset import ModelViewSet from workflow.models.process import Process from workflow.serializers.process import ProcessModelSerializer, ProcessInfoModelSerializer class ProcessApiModelViewSet(ModelViewSet): """ Process Api Model View Set """ qu...
StarcoderdataPython
98555
<reponame>bopopescu/NovalIDE # -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # Name: DebuggerService.py # Purpose: Debugger Service for Python and PHP # # Author: <NAME> # # Created: 12/9/04 # CVS-ID: $Id$ # Copyright: (c) 2...
StarcoderdataPython
56126
"""Root package for anstoss tools."""
StarcoderdataPython
1634149
import random name = input("Please enter your username: ") print("Hello {}".format(name)) game = (input("Would you like to play a game? yes or no ")).casefold() play = "yes" highest = 10 answer = random.randint(1, highest) guesses = 3 while game != play: print("Wrong Choice") game = (input("Would you like to ...
StarcoderdataPython
116586
<filename>taxi_simulator/secretary.py import logging import json from spade.agent import Agent from spade.template import Template from spade.message import Message from .utils import StrategyBehaviour, CyclicBehaviour from .protocol import REQUEST_PROTOCOL, REGISTER_PROTOCOL, INFORM_PERFORMATIVE, ACCEPT_PERFORMATIVE...
StarcoderdataPython
3346497
#!/usr/bin/env python # encoding: utf-8 import os try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup from tbone import __version__ def read(f): return open(os.path.join(os.path.dirname(__file__), ...
StarcoderdataPython
163503
from typing import Callable, Dict ResourceToMockFn = Dict[str, Callable]
StarcoderdataPython
196528
<reponame>smokeytheblair/adventcode2018 import sys import argparse import math from collections import Counter from operator import xor reset_report = None valid_colors = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] def print_usage(name, input_file): print(f"Usage: python3 {name} {input_file}") def load_in...
StarcoderdataPython
1722266
set1 = {1} print(set1.__sizeof__()) for i in range(2, 100): set1.add(i) print(i, end="-") print(set1.__sizeof__())
StarcoderdataPython
3383658
def get_scorer(task_type='regression'): if task_type == 'regression': return RegressionScorer() else: return ClassificationScorer() class Scorer: def __init__(self): pass @staticmethod def check_significance(this_results: list, baseline_results: list, P_VALUE_THRES=0.05): ...
StarcoderdataPython
1727842
<reponame>R6500/SLab ''' SLab Example Example_06.py Measure a voltage drop circuit Connection diagram: <DAC1>----[A 1N4148 Diode K]----<ADC1>----<1k Resistor>----<GND> ''' # Locate slab in the parent folder import sys sys.path.append('..') sys.path.append('.') import slab import slab_dc as dc ...
StarcoderdataPython
1685884
from __future__ import unicode_literals import frappe from frappe.utils import now from frappe import _ sitemap = 1 def get_context(context): out = { "parents": [ { "name": _("Home"), "route": "/" } ] } return out
StarcoderdataPython
3255881
<gh_stars>0 #!/usr/bin/env python3 # coding: utf-8 import os import tar import uuid import argparse import celery_worker parser = argparse.ArgumentParser() parser.add_argument('folder') parser.add_argument('entrypoint') args = parser.parse_args() f = tar.make_tar_file(args.folder, mode='rb') tar_base64 = tar.bin_to_...
StarcoderdataPython
1687192
<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from pcodes import all_formats, all_lexers, codes # Create your views here. def mainindex(request): return render(request, 'index.html') def dcode(requests): ...
StarcoderdataPython
3204403
import collections import errno import functools import select import socket '''Asynchronous socket service inspired by the basic design of Boost ASIO. This service currently supports TCP sockets only, and supports asynchronous versions of common client operations (connect, read, write) and server operations (accept...
StarcoderdataPython
160757
<reponame>PerformLine/webfriend from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict from webfriend.scripting.parser import MetaModel import re class Array(MetaModel): pass class String(unicode): def __new__(cls, value, *args, **kwargs): ...
StarcoderdataPython
1685806
<reponame>mlioo/dispatch import logging from typing import List, Optional from fastapi.encoders import jsonable_encoder from dispatch.exceptions import InvalidConfiguration from .models import Plugin, PluginCreate, PluginUpdate log = logging.getLogger(__name__) def get(*, db_session, plugin_id: int) -> Optional[Pl...
StarcoderdataPython
1633658
import yfinance as yf import pandas as pd import requests def outputZipandLongName(): tickers = pd.read_csv('sp500.csv')['Symbol'].tolist() zipList = [] yf_out = yf.Tickers(' '.join(tickers)) i = 0 for ticker in tickers: info = yf_out.tickers[ticker].info if "zip" in info and "lon...
StarcoderdataPython
3285555
<reponame>i10416/Skija #! /usr/bin/env python3 import argparse, glob, os, subprocess, sys sys.path.append(os.path.normpath(os.path.dirname(__file__) + '/../../../script')) import common, build, build_utils def main(): parser = argparse.ArgumentParser() parser.add_argument('--skija-version') parser.add_argument('...
StarcoderdataPython
4819964
""" Game of Life imp by O.Gindia 30-09-2020 """ from typing import Tuple, List from time import sleep from random import randint from asciimatics.screen import Screen class Board: """ Game of Life Board """ __board: List[bool] = [] __width: int = 0 __height: int = 0 def __init__(self, w: ...
StarcoderdataPython
57882
<filename>packages/submodopt/submodopt/__init__.py<gh_stars>10-100 """submodopt - A package for maximizing submodular functions""" __version__ = '0.1.0' __author__ = '<NAME> <<EMAIL>>' __all__ = []
StarcoderdataPython
3392508
"""Exceptions for libvcs. If you see this, we're publishing to S3 automatically """ class LibVCSException(Exception): """Standard exception raised by libvcs.""" pass class CommandError(LibVCSException): """This exception is raised on non-zero return codes.""" def __init__(self, output, returncod...
StarcoderdataPython
1616957
<filename>Leetcode-cn/633.平方数之和.py<gh_stars>0 # # @lc app=leetcode.cn id=633 lang=python3 # # [633] 平方数之和 # # https://leetcode-cn.com/problems/sum-of-square-numbers/description/ # # algorithms # Medium (35.38%) # Likes: 195 # Dislikes: 0 # Total Accepted: 49K # Total Submissions: 134.2K # Testcase Example: '5' #...
StarcoderdataPython
3232476
<filename>athenet/utils/run_algorithm.py """Function for running algorithm on network for multiple cases. """ import datetime from athenet.utils import count_zeros from athenet.utils.results import Results def get_error_rate(network): """ Returns error rate in given network :param Network network:netwo...
StarcoderdataPython
1600971
# coding=utf-8 # This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders. import scrapy import logging from scrapy.http import FormRequest import datetime from ptt.items import PostItem import re class PTTSpider(s...
StarcoderdataPython
56027
"""Enforce adding a pip install statement in the notebook. In the `compwa-org repo <https://github.com/ComPWA/compwa-org>_`, notebooks should specify which package versions should be used to run the notebook. This hook checks whether a notebook has such install statements and whether they comply with the expected form...
StarcoderdataPython
4811426
class Solution(object): def recurse(self, root): if not root: return 0 if root in self.cache: return self.cache[root] val = 0 if root.left is not None: val += self.recurse(root.left.left) + self.recurse(root.left.right) if root.right is not None: val...
StarcoderdataPython
13714
import sys import os import os.path import random from pathlib import Path import torch import torchaudio from .audiodataset import AUDIO_EXTENSIONS, default_loader from ..dataset import PureDatasetFolder, has_file_allowed_extension class TAU2019(PureDatasetFolder): """TAU urban acoustic scene 2019 dataset. ...
StarcoderdataPython
182689
<filename>messages.py __author__ = 'kehao' from thu_learn import * def main(): login() semester = Semester() messages = [] for course in semester.courses: print(course.name) for message in course.messages: messages.append(message) messages.sort(key=lambda x: x.date, rev...
StarcoderdataPython
3243490
<gh_stars>1-10 # -*- coding: utf-8 -*- """ Created on Tue Sep 23 2019 main eval mfnet multitask Notes for evaluation on multidataset models. Evaluation is not to be done on multiple datasets together as it will most probably complicate everything when calculating metrics. Instead I intend to run the evaluation script ...
StarcoderdataPython
1690485
import pytest import responses from django.core.files.uploadedfile import SimpleUploadedFile from docutils.nodes import document from inmemorystorage.storage import InMemoryFile from django_docutils.favicon.prefetch import ( is_favicon_stored, prefetch_favicon, yield_page_doctrees, yield_references, )...
StarcoderdataPython
3323400
<gh_stars>0 from flask import Flask, render_template import os import sys from flask import request from random import randint import tact_util as t_util app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/result', methods=['POST']) def result(): name = r...
StarcoderdataPython
4825627
<gh_stars>0 def solution(text): c_row = 0 c_col = 0 tree_count = 0 while c_row < len(text) - 1 and c_col < len(text[c_row]) - 3: c_row = c_row + 1 c_col = c_col + 3 if text[c_row][c_col] == '#': tree_count = tree_count + 1 print(f'Final tree count: ...
StarcoderdataPython
3351143
import csv, numpy as np test_data = np.loadtxt('../data/test/reduced_test_data.csv',delimiter=','); test_size = test_data.shape[0]; N = 3; accr = np.array([0.80439, 0.77545, 0.79741]); data = np.array([[0 for i in xrange(N+1)] for j in xrange(test_size)]); for i in xrange(N): name = '../data/submission_' + str(i+...
StarcoderdataPython
1687964
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class BaseModel(Base): __abstract__ = True def __repr__(self): return "<{0.__class__.__name__}(id={0.id!r})>".format(self)
StarcoderdataPython
37238
def test_see_for_top_level(result): assert ( "usage: vantage [-a PATH] [-e NAME ...] [-v KEY=[VALUE] ...] [--verbose] [-h] COMMAND..." in result.stdout_ )
StarcoderdataPython
1771845
#!/usr/bin/env python # -*- encoding: utf-8 -*- '''AMEN Exception classes''' class AmenError(Exception): """ The root amen exception class """ pass class SynthesizeError(AmenError): """ Exception class for errors in synthesize.py """ pass class FeatureError(AmenError): """ ...
StarcoderdataPython
3276822
<reponame>cgbits/pybits import unittest from typing import Dict, List, Any from pybits.subset import ( dict_assert_is_subset, dict_is_subset, list_is_subset, ) from pybits.exceptions import ( ComparisonBaseError, ComparisonErrorInfo, ) class TestSubsetModule(unittest.TestCase): def test_dict...
StarcoderdataPython
179352
#!/usr/bin/env python # _#_ coding:utf-8 _*_ import os from django.http import HttpResponseRedirect,JsonResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from OpsManage.models import Cron_Config,Server_Assets from OpsManage.utils.ssh_tools import SSHManage from O...
StarcoderdataPython
3253605
<filename>Corpora/annotation_manager.py __author__ = "<NAME>" __email__ = "<EMAIL>" import corpus, re, shutil from warnings import warn home = os.environ['HOME'] base_path = os.path.join(home, 'Dropbox', 'ISO-Space', 'Annotation') os.chdir(base_path) corpora_path, corpora, other_files = os.walk(os.getcwd()).next() wi...
StarcoderdataPython
181130
<filename>python/csv_value_copy.py<gh_stars>10-100 #!/usr/bin/env python3 # -*- coding: UTF-8 -*- import argparse import codecs import csv import sys import openapc_toolkit as oat ARG_HELP_STRINGS = { "source_file": "The source csv file", "source_file_key_column": "The numerical index of the key column " + ...
StarcoderdataPython
4813216
from .service import RedditAuth, ScraperService from .models import Subreddit, Submission, AuthorRedditor, Comments from django_q.tasks import async_task from django_q.models import Schedule def crawl_subreddits(): # Creates 27 tasks at once subreddits = [ 'all', 'COVID', 'COVID19', ...
StarcoderdataPython
46388
<reponame>majestylink/majestyAccencis<filename>shop/migrations/0004_auto_20191223_1511.py # Generated by Django 2.2.7 on 2019-12-23 14:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0003_auto_20191223_1507'), ] operations = [ ...
StarcoderdataPython
3240908
import subprocess import sys import os if __name__ == '__main__': print "call arguments: " for arg in sys.argv: print arg, " " script_dir = "~/copies_scripts/" # script_dir = "~/mitral_fully_discrete/scripts/" # get some output names cwd = os.getcwd() cwd_split = cwd.split('/...
StarcoderdataPython
3217553
<filename>tempest/api/compute/admin/test_servers_negative.py # Copyright 2013 Huawei Technologies Co.,LTD. # # 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.apac...
StarcoderdataPython
4824643
<reponame>frknnlzts/howto<filename>venv-howto/bin/explode.py #!/home/cracker/Desktop/howto/venv-howto/bin/python3.5 # # The Python Imaging Library # $Id$ # # split an animation into a number of frame files # from __future__ import print_function from PIL import Image import os import sys class Interval(object): ...
StarcoderdataPython
32435
#!/usr/bin/env python3 import functools #https://stackoverflow.com/questions/3888158 def optional_arg_decorator(fn): @functools.wraps(fn) def wrapped_decorator(*args, **kwargs): # is_bound_method = hasattr(args[0], fn.__name__) if args else False # if is_bound_method: # klass = args[...
StarcoderdataPython
1732566
from math import trunc from re import L import lightbulb import random import hikari import wikipedia import requests import asyncio from hikari.colors import Color import datetime as dt from datetime import datetime, time, timedelta from wikipedia import exceptions from wikipedia.wikipedia import languages plugin ...
StarcoderdataPython
152885
<reponame>sattwik21/Hacktoberfest2021-1<gh_stars>100-1000 >> def fibo(n): a,b = 0, 1 for _ in range(2,n+1): c = a+b c = c%10 b,a = c,b if (c!=0): print(c-1) else: print(9) n = int(input()) if (n<=1): print(n) else: q = (n+2)%60 if q==1: print(0) elif q==0:...
StarcoderdataPython
1668051
<gh_stars>1-10 from django.shortcuts import render from django.http import HttpResponse from .models import temp_Client # Create your views here. def home(request): client1 = temp_Client() client2 = temp_Client() client1.First_name = "Faizan" client1.Last_name = "Ahmed" client2.First_name = "Ahmed" client2.Last_...
StarcoderdataPython
3381631
## Decode stimulus and choice from neural activity import json import os import pandas import numpy as np import my, my.decoders import tqdm import extras ## Parameters with open('../parameters') as fi: params = json.load(fi) ## Where to store results neural_decoding_dir = os.path.join(params['neural_dir'], 'd...
StarcoderdataPython