id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
30834
import numpy as np from pytope import Polytope import matplotlib.pyplot as plt np.random.seed(1) # Create a polytope in R^2 with -1 <= x1 <= 4, -2 <= x2 <= 3 lower_bound1 = (-1, -2) # [-1, -2]' <= x upper_bound1 = (4, 3) # x <= [4, 3]' P1 = Polytope(lb=lower_bound1, ub=upper_bound1) # Print the halfspace represen...
StarcoderdataPython
3290944
<gh_stars>0 # coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import o...
StarcoderdataPython
3343060
<filename>tests/test_mock_firefly.py import unittest from unittest.mock import patch, PropertyMock, Mock from Firefly import Scheduler from Firefly.helpers.location import Location from Firefly.helpers.events import Event from Firefly.const import EVENT_TYPE_BROADCAST, SOURCE_LOCATION # Change this to false if you are...
StarcoderdataPython
1643810
<filename>WebMirror/OutputFilters/rss/FeedDataParser.py #!/usr/bin/python # from profilehooks import profile import urllib.parse import json import traceback import datetime import WebMirror.OutputFilters.util.feedNameLut as feedNameLut from WebMirror.OutputFilters.util.TitleParsers import extractVolChapterFragmentP...
StarcoderdataPython
1634978
<reponame>recursivelycurious/wordnik-repl<filename>practice/advanced_topics/ex9.py my_list = range(16) print filter(lambda x: x % 3 == 0, my_list) # or... languages = ["HTML", "JavaScript", "Python", "Ruby"] print filter(lambda x: x == "Python", languages) # or... squares = [x ** 2 for x in range(1, 11)] print filt...
StarcoderdataPython
187597
<reponame>mahi97/pycm # -*- coding: utf-8 -*- ''' >>> from pycm import * >>> import os >>> import json >>> y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2] >>> y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2] >>> cm = ConfusionMatrix(y_actu, y_pred) >>> cm pycm.ConfusionMatrix(classes: [0, 1, 2]) >>> len(cm) 3 >>> print(cm) ...
StarcoderdataPython
3397859
from enum import Enum class OptimizationKind(Enum): FINAL_VALUE = 'FINAL_VALUE', AREA_UNDER_CURVE = 'AREA_UNDER_CURVE' class OptimizationGoal(Enum): MAX = 'MAX', MIN = 'MIN'
StarcoderdataPython
4834040
<filename>torchgeo/trainers/regression.py # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """Regression tasks.""" from typing import Any, Dict, cast import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor...
StarcoderdataPython
1728034
<gh_stars>0 def f(a, b, c): print(f"a = {a}") print(f"b = {b}") print(f"c = {c}") t = (1, 2, 3) f(*t)
StarcoderdataPython
77220
<reponame>gary-dalton/Twenty47 from flask import Flask, flash from flask.ext.mongoengine import MongoEngine from flask_wtf.csrf import CsrfProtect from flask_mail import Mail import blinker app = Flask(__name__) #app.config.from_object(__name__) # Load the config app.config.from_pyfile('local.config.py') #app.config....
StarcoderdataPython
1649123
#!/usr/bin/env python # -*- coding: utf-8 -*- # # <NAME> # import sys import os import pandas as pd def main(): # Args in_ot = '../../output/nearest_gene/180830/nearest_gene.tsv.gz' in_vep = 'output/vcf_nearest_gene.txt' # Load ot = pd.read_csv(in_ot, sep='\t', header=0, nrows=1000000) vep =...
StarcoderdataPython
3230713
<reponame>callzhang/qdtrack<filename>qdtrack/models/trackers/tao_tracker.py<gh_stars>0 import os import random from collections import defaultdict import cv2 import mmcv import numpy as np import seaborn as sns import torch from mmcv.image import imread, imwrite from mmcv.visualization import color_val, imshow from mm...
StarcoderdataPython
168913
"""Asynchronous Python client for the Quby ToonAPI."""
StarcoderdataPython
72052
<reponame>finn-dodgson/DeepHalos<filename>scratch/losses/mse_loss.py import sys sys.path.append("/home/luisals/DeepHalos") from dlhalos_code import CNN import tensorflow.keras.callbacks as callbacks from tensorflow.keras.callbacks import CSVLogger import tensorflow from tensorflow.keras import regularizers import dlhal...
StarcoderdataPython
1641279
<reponame>momantang/cobrass from django.db import models # Create your models here. class Stock(models.Model): code = models.CharField(u'股票代码', max_length=10, unique=True) name = models.CharField(u'股票名称', max_length=30, null=True) mark = models.CharField(u'股票备注', max_length=200, null=True) is_interes...
StarcoderdataPython
1610866
import tensorflow as tf import numpy as np import random import matplotlib.pyplot as plt from zipfile import ZipFile random.seed(1337) np.random.seed(1337) tf.random.set_seed(1337) with ZipFile("archive.zip","r") as zip: zip.extractall() BATCH_SIZE = 32 IMG_SIZE = (160,160) train_ds = tf.keras.preprocessing.image...
StarcoderdataPython
1741161
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ AppletDialog.py MIT License (c) Faure Systems <dev at faure dot systems> Main dialog of an applet. """ from constants import * try: LAYOUT_FILE except NameError: LAYOUT_FILE = ".layout.yml" from PyQt5.QtCore import pyqtSlot, QPoint, QSize, QTimer from PyQt5....
StarcoderdataPython
1634754
# Copyright (c) 2018, DjaoDjin inc. # 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 conditions and...
StarcoderdataPython
139042
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 21 03:15:05 2020 @author: zqwu """ import numpy as np import pandas as pd import csv import torch as t import os import pickle import copy import torch_geometric as tg import tempfile class MolDataset(tg.data.Dataset): def __init__(self, ...
StarcoderdataPython
1622053
# Copyright 2019 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
StarcoderdataPython
3370154
<filename>serve.py import sys from http.server import HTTPServer, SimpleHTTPRequestHandler def main(addr: str='', port: int=0) -> int: http_server = HTTPServer((addr, port), SimpleHTTPRequestHandler) target_url = 'http://%s:%s' % http_server.server_address print(target_url) http_server.serve_forever(...
StarcoderdataPython
1697723
<filename>nldslfuncs/sqltoobjparser/sqltoobjparser.py from moz_sql_parser import parse import json sql = 'select cola, colb, colc from "someschema"."mytable" where id = 1' x = json.dumps(parse(sql)) def sqltojson(sqlstring: str): pass
StarcoderdataPython
3232556
<reponame>IgorBolotnikov/catsby<filename>lexer/char_helpers.py from typing import Optional from .char_constants import ( AND, DECIMAL_POINT, DIGITS, DIVIDE, EQ, GT, LEFT_PAREN, LETTERS, LT, MINUS, MODULO, MULTIPLY, NOT, OR, PLUS, POWER, RIGHT_PAREN, ...
StarcoderdataPython
1736181
<reponame>Invarato/Jarroba #!/usr/bin/env python # -*- coding: utf-8 -*- from collections import abc class MiColeccionConVistas(abc.Mapping): def __init__(self, *args, **kwargs): self.lista_interna_claves = [100, 200, 300] self.lista_interna_valores = ["CIEN", "DOSCIENTOS", "TRESCIENTOS"] de...
StarcoderdataPython
3210763
from django.db import models from datetime import datetime class Django_ES(models.Model): es_id = models.IntegerField(primary_key=True) es_name = models.CharField(max_length=1000) es_url = models.CharField(max_length=2000) kibana_url = models.CharField(max_length=4500) kibana_filter = models.CharF...
StarcoderdataPython
3346147
<reponame>maxlcummins/Chooklord<gh_stars>1-10 from scipy.spatial.distance import pdist from scipy.cluster.hierarchy import linkage, dendrogram import numpy as np import pandas as pd import glob import matplotlib matplotlib.use('Agg') #avoid problems with headless environments import matplotlib.pyplot as plt import...
StarcoderdataPython
1761890
<filename>eclcli/storage/storageclient/v2/volumes.py<gh_stars>0 # -*- coding: utf-8 -*- import six try: from urllib import urlencode except ImportError: from urllib.parse import urlencode from .. import base # Valid sort directions and client sort keys SORT_DIR_VALUES = ('asc', 'desc') SORT_KEY_VALUES = ('i...
StarcoderdataPython
1738939
''' List basics List Basics Part two: line 60 List Basics Part three: line 140 Agenda Purpose of lists Creating lists Empty lists Adding things to a list Getting things from a list >>> mylist = [10, 20, 30, 40] >>> mylist [10, 20, 30, 40] >>> names = ["Tahir", "Rich", "Sis", "Roger"] >>> names ...
StarcoderdataPython
111537
<reponame>texib/bitcoin-zoo from django.shortcuts import render from bitcoin_api.serializers import WalletSerializer ,WalletCreateSerializer from django_bitcoin.models import Wallet from django.http import Http404 from rest_framework.views import APIView from rest_framework import generics, permissions from rest_frame...
StarcoderdataPython
1702273
<filename>MultiSSHConnectionProxy.py<gh_stars>0 import paramiko class MultiSSHConnectionProxy: ''' This class is used to make a tunnel connection using paramiko. Use the first connection to instatiate the object. The second connection is done by using the method connect. This works like a proxy object b...
StarcoderdataPython
3275302
"""User editable top-level commands""" from invoke import task from .config import *
StarcoderdataPython
4829396
<gh_stars>1000+ """! @brief Test templates for MBSAS algorithm. @authors <NAME> (<EMAIL>) @date 2014-2020 @copyright BSD-3-Clause """ import matplotlib; matplotlib.use('Agg'); from pyclustering.tests.assertion import assertion; from pyclustering.cluster.mbsas import mbsas; from pyclustering....
StarcoderdataPython
3217954
<reponame>bnchdrff/jussi<filename>jussi/middlewares/update_block_num.py # -*- coding: utf-8 -*- import asyncio import structlog import ujson from ..request import JussiJSONRPCRequest from ..typedefs import HTTPRequest from ..typedefs import HTTPResponse from ..utils import async_nowait_middleware from ..validators i...
StarcoderdataPython
1798051
<filename>blueprints.py from flask import jsonify, request, Blueprint import kitchen_detection from kitchen_detection import people_counting from config import cfg from kitchen_database import kitchens_at from utils import avg kitchen_blueprint = Blueprint('kitchen', __name__) @kitchen_blueprint.route('/kitchen') d...
StarcoderdataPython
78609
# coding=utf-8 import os from flask import Flask app = Flask(__name__) conf = type('Config', (), {})() conf.DEBUG = True conf.SQLALCHEMY_DATABASE_URI = \ os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(app.root_path, 'project.db'))) conf.SQLALCHEMY_TRACK_MODIFICAT...
StarcoderdataPython
1773260
<reponame>ctoth/sound_lib<filename>sound_lib/effects/effect.py from sound_lib.main import bass_call import ctypes from sound_lib.external import pybass import string # for the alphabet! class SoundEffect(object): """ """ def __init__(self, channel, type=None, priority=0): self.original_chann...
StarcoderdataPython
99826
<reponame>4RCAN3/PyAlgo ''' module for implementation of cycle sort ''' def cycle_sort(arr: list): writes = 0 for cycleStart in range(0, len(arr) - 1): item = arr[cycleStart] pos = cycleStart for i in range(cycleStart + 1, len(arr)): if (arr[i] < item): ...
StarcoderdataPython
4804317
from solver import solve_level levels = ( ('T', '0'), # 1 ('TTT∀', '0000'), # 4 ('∀TT∀', '0110'), # 123 ('T∀TT', '1011'), # 1234 ## INTRODUCE ↕ ('T↕TT↕T', '000000'), # 25 ('T↕TT∀T', '111001'), # 256 ('∀↕↕T', '1001'), #34 ('T↕↕↕T', '10001'), # 3 ('↕∀↕T∀', '10100'), # 1234 ('T↕TT∀T', '010101'), # 1...
StarcoderdataPython
1629328
import os from flame import FLAME from flame_config import get_config import numpy as np import torch import torch.nn as nn import trimesh def batch_orth_proj_idrot(X, camera, name=None): """ X is N x num_points x 3 camera is N x 3 same as applying orth_proj_idrot to each N """ with tf.name_...
StarcoderdataPython
1696526
<reponame>nickdrozd/experimental ''' from __experimental__ import pep542 Trying to implement https://www.python.org/dev/peps/pep-0542/ ''' from io import StringIO import tokenize def transform_source(text): toks = tokenize.generate_tokens(StringIO(text).readline) result = [] special_def_clause = False...
StarcoderdataPython
1695166
<reponame>geocam/geocamUtilWeb # __BEGIN_LICENSE__ #Copyright (c) 2015, United States Government, as represented by the #Administrator of the National Aeronautics and Space Administration. #All rights reserved. # __END_LICENSE__ import os import logging # This is basically obsolete; django pipeline handles javascri...
StarcoderdataPython
91014
import ast import re from setuptools import setup, find_packages from pip.req import parse_requirements # get __version__ in __init__.py _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('jsonlookup/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('ut...
StarcoderdataPython
1798093
<reponame>Rollmops/restit import logging import signal from contextlib import contextmanager from threading import Thread from time import sleep from typing import Union, Callable, Generator, List from wsgiref.simple_server import make_server, WSGIServer LOGGER = logging.getLogger(__name__) class DevelopmentServer: ...
StarcoderdataPython
3249013
<filename>assignment1/sorted_customer_consumption.py<gh_stars>0 from pyspark import SparkConf, SparkContext def get_spark_context(): conf = SparkConf().setMaster('local').setAppName('TotalConsumption') sc = SparkContext(conf=conf) return sc def get_total_consumption(sc, file_path): lines = sc.textFi...
StarcoderdataPython
3392098
<gh_stars>1-10 """dynaconf recommended way to setup setup""" from dynaconf.base import LazySettings from dynaconf.constants import DEFAULT_SETTINGS_FILES # this was copied from dynaconf/__init__.py before it became deprecated # pylint: disable=invalid-name settings = LazySettings( environments=True, lowercas...
StarcoderdataPython
1719642
# Importing standard libraries import sys ''' Reads in an integer from stream passed in as the parameter. Simple parsing function that can read from files as well as standard input ''' def parseInt(stream): return int(stream.readline().rstrip()) ''' Utility method that does a binarySearch on the sor...
StarcoderdataPython
9005
from io import TextIOWrapper import math from typing import TypeVar import random import os from Settings import Settings class Dataset: DataT = TypeVar('DataT') WIN_NL = "\r\n" LINUX_NL = "\n" def __init__(self, path:str, filename:str, newline:str = WIN_NL) -> None: self.path_ = path self.f...
StarcoderdataPython
1745146
""" """ from six import add_metaclass try: from functools import total_ordering except ImportError: # pragma: no cover from .backports.total_ordering import total_ordering # pragma: no cover def safe_string(value): """ consistently converts a value to a string :param value: :return: str ...
StarcoderdataPython
99075
<gh_stars>1-10 # Script to preprocess the ADNI1 baseline (screening) data # Requires a directory with the image data # and the following ADNI tables # - ADNIMERGE.csv : Most information is here # - VITALS.csv : Some extra infos about congnitive scores # - DXSUM_PDXCONV_ADNIALL.csv : Patient weight # - MRI3META.csv ...
StarcoderdataPython
3338866
<filename>3b_main_hyperopt.py from functions.sub_hyperopt import hpsearch_model import numpy as np import pickle import os, time, joblib import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.models import load_model, save_model from tensorflow.keras.callbacks import LearningRateScheduler, Early...
StarcoderdataPython
1618463
<filename>evaluation/eval_metric_learning.py # Copyright (c) ByteDance, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Copy-paste from DINO library. https://github.com/facebookresearch/dino ""...
StarcoderdataPython
3323567
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 16 11:57:09 2019 @author: smrak """ from pyGnss import pyGnss from pyGnss import gnssUtils as gu from datetime import datetime, timedelta import georinex as gr import numpy as np from glob import glob from dateutil import parser import yaml import o...
StarcoderdataPython
103041
<reponame>Dundee/python-sqlpuzzle from sqlpuzzle.exceptions import ConfirmDeleteAllException from sqlpuzzle._queries.options import Options from sqlpuzzle._queryparts import Tables, Where from .query import Query __all__ = ('Delete',) class DeleteOptions(Options): _definition_of_options = { 'ignore': { ...
StarcoderdataPython
86655
#!/usr/bin/python3 # coding=utf8 # Date:2021/05/04 # Author:Aiden import sys import cv2 import math import time import rospy import threading import numpy as np from threading import Timer from std_msgs.msg import * from std_srvs.srv import * from sensor_msgs.msg import Image from sensor.msg import Led from warehouse...
StarcoderdataPython
1690989
<filename>src/core/src/tortuga/objects/validators.py # Copyright 2008-2018 Univa 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 # # http://www.apache.org/licenses/LICENSE-2.0 ...
StarcoderdataPython
3398147
#!/usr/bin/env python3 import re from os.path import dirname, realpath dir_path = dirname(realpath(__file__)) with open(f'{dir_path}/input') as f: puzzle_input = f.read().split('\n')[:-1] def parse_input(): return puzzle_input[:] def format_entry(entry): p = re.compile('(^\d+)-(\d+) (\w): (\w+$)') return p....
StarcoderdataPython
1713289
notas = [] bolet = [] while True: notas.append(str(input('Nome: ')).title()) notas.append(float(input('Nota 1: '))) notas.append(float(input('Nota 2: '))) bolet.append(notas[:]) notas.clear() sn = ' ' while sn not in 'SN': sn = str(input('Quer continuar? [S/N]: ')).upper().strip()[0]...
StarcoderdataPython
91726
<gh_stars>1-10 # -*- coding: utf-8 -*- # Python QR Code Generator # Author - HoneyMoose(<EMAIL>) # Link Article - https://www.ossez.com/t/python-qr/13396 import qrcode.image.svg image_path = "resources/token_qr.png" qr_string = "https://www.ossez.com/c/open-source/python/14" print(qr_string) img = qrcode.make(qr_s...
StarcoderdataPython
3389307
# Generated by Django 3.0 on 2019-12-10 21:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hackerspace', '0003_auto_20191210_2053'), ] operations = [ migrations.AlterField( model_name='event', name='image_feat...
StarcoderdataPython
4830611
import pickle import numpy as np import os import random class Memory: def __init__(self,replay_size=None,action_size=None,state_size=None,batch_size=None): self.buffer = 4 self.batch_size=batch_size self.replay_size = replay_size self.state_size = state_size self.action_size = action_size self.states ...
StarcoderdataPython
3364420
<reponame>andrey-tpt/datawig<gh_stars>0 # Copyright 2018 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/apa...
StarcoderdataPython
3325320
# %% # import packages from bs4 import BeautifulSoup import requests import pandas as pd #%% # create urls list_of_parts = list(range(1,9)) def build_url(part): return 'https://greengables-1.tripod.com/script/1part' + str(part) + '.html' list_of_urls = [build_url(part) for part in list_of_parts] print(list_of_ur...
StarcoderdataPython
33948
from django.urls import reverse_lazy, reverse from django.views.generic import TemplateView from exporter.applications.services import post_applications, post_open_general_licences_applications from exporter.apply_for_a_licence.forms.open_general_licences import ( open_general_licence_forms, open_general_licen...
StarcoderdataPython
166212
<reponame>hep-gc/cloud-scheduler-2 from unit_test_common import execute_csv2_request, initialize_csv2_request, ut_id from sys import argv def main(gvar): if not gvar: gvar = {} if len(argv) > 1: initialize_csv2_request(gvar, selections=argv[1]) else: initialize_csv2_...
StarcoderdataPython
3328993
def sumOfTwo(a, b, v): # examples are sorted, but are we going to actually get sorted input? # no, input arrays may not be sorted ​ # sort the two arrays # could we use a similar two pointer strategy? ​ # if we're hash tables, what is going in the hash tables? # store the elements of one of...
StarcoderdataPython
71119
from datawasher import get_friends_data,get_user_item_matrix, \ get_reputation,get_user_item_matrix_sub, get_reputation, \ get_original_user_item_matrix,get_original_UI, \ get_friends_data_index,get_moive100k, \ get_twittermovie...
StarcoderdataPython
1749855
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/16 15:23 # @Author : Tao.Xu # @Email : <EMAIL> """Kubernetes Python Client Usage of Official Python client library for kubernetes FYI: https://github.com/kubernetes-client/python """ import json import urllib3 from kubernetes import config, client...
StarcoderdataPython
1778423
from .protocols.http import request as http_request, request_handler as http_request_handler from .protocols.ws import request_handler as ws_request_handler, request as ws_request from .protocols.grpc import request as grpc_request from .dbapi import request as dbo_request from .protocols.proxy import tunnel_handler fr...
StarcoderdataPython
36001
<reponame>mdameenh/elysia<filename>moviecritic/models.py from django.db import models from django.contrib.postgres.fields import ArrayField # Create your models here. class Movie_Details(models.Model): name = models.CharField(max_length=100) year = models.IntegerField(default=0) boxoffice = models.BigInteg...
StarcoderdataPython
115703
<gh_stars>1-10 import numpy as np import pandas as pd import random import pickle import os from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from pipelitools.models import metrics as m def test_models(): """ """ print('test_models: ok') class Model: """Runs a model, plots confusion...
StarcoderdataPython
1792350
<reponame>SauceTheBoss/SketchAAE class HParams(): def __init__(self): self.sketches_folder = 'sketches' self.models_folder = 'models' self.max_epochs = 50000 self.M = 20 self.batch_size = 100 self.lr = 0.001 self.inner_lr = 0.001 self.lr_d...
StarcoderdataPython
3263858
<filename>main.py # Here is where I import all of the modules I require import zipfile import os import requests # Beginning Introduction of the program print("Welcome to TaptonPIX Automated Data Packaging Program") # The location of the question, this will decide what the user wants to do # either run with defaults, e...
StarcoderdataPython
1774034
import matplotlib.pyplot as plt import numpy as np size = np.genfromtxt('positions.csv', delimiter='\t', skip_header=1, max_rows=1) data = np.genfromtxt('positions.csv', delimiter='\t', skip_header=3) x = data[:,0] y = data[:,1] #heatmap, xedges, yedges = np.histogram2d(x, y, bins=(size[0],size[1])) #extent = [xedge...
StarcoderdataPython
141870
<reponame>mistio/mist.api<filename>src/mist/api/views.py<gh_stars>1-10 """mist.api.views Here we define the HTTP API of the app. The view functions here are responsible for taking parameters from the web requests, passing them on to functions defined in methods and properly formatting the output. This is the only sour...
StarcoderdataPython
56183
def splitscore(file_dir): score = [] Prefix_str = [] f = open(file_dir) for line in f: s =line.split() score.append(float(s[-1])) s = s[0] + ' ' + s[1] + ' ' + s[2] + ' ' Prefix_str.append(s) return score,Prefix_str file_dir1='submission/2019-01-28_15:45:05_fishnet15...
StarcoderdataPython
3361614
<filename>test/analysis/tables/test_table_builder.py from unittest import TestCase, mock from unittest.mock import call import numpy as np from sklearn.linear_model import LogisticRegression from source.analysis.classification.classifier_summary import ClassifierSummary from source.analysis.performance.performance_su...
StarcoderdataPython
23197
from torch.utils.data import Dataset from skimage import io import os import torch class MnistData(Dataset): def __init__(self, root_dir): self.root_dir = root_dir img_list = [] label_list = os.listdir(self.root_dir) for label in label_list: file_names = os.li...
StarcoderdataPython
168643
__version__ = "0.9.4" version_info = [0, 9, 4]
StarcoderdataPython
3249227
<reponame>MrFelixU/ks5-edexcel<filename>oink/simpletal/simpleTAL.py """ simpleTAL Interpreter Copyright (c) 2009 <NAME> (http://www.owlfish.com/) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are m...
StarcoderdataPython
3211689
<reponame>Pandinosaurus/mlstatpy # -*- coding: utf-8 -*- """ @file @brief About Machine Learning Benchmark """ import os import numpy from sklearn.model_selection import train_test_split from sklearn.base import ClusterMixin from sklearn.metrics import silhouette_score from pyquickhelper.loghelper import noLOG from pyq...
StarcoderdataPython
1656661
from project import variables def text_size(size): """This sets the text size to the input value specified.""" variables['Seg1'] = size variables['Seg2'] = variables['Seg1'] * 2 variables['Seg3'] = variables['Seg1'] * 3 variables['Seg4'] = variables['Seg1'] * 4
StarcoderdataPython
112231
# Here goes all the walls in the scenario import pygame from config import * def walls(): from main import screen pygame.draw.rect( screen, colors["Blue_ball"], (0, 0, (SCREEN_WIDTH // 2), WALL_WIDTH) ) pygame.draw.rect( screen, colors["Red_ball"], ((SCREEN_WIDTH // 2)...
StarcoderdataPython
189014
<filename>0x15-api/1-export_to_CSV.py #!/usr/bin/python3 """ Python CVS """ import csv import requests from sys import argv if __name__ == '__main__': user_id = argv[1] url_todos = "https://jsonplaceholder.typicode.com/todos?userId={}" api_todos = requests.get(url_todos.format(user_id), verify=False).json...
StarcoderdataPython
3315067
# Tencent is pleased to support the open source community by making GNES available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. 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...
StarcoderdataPython
39531
<filename>backend/api/migrations/0001_initial.py # Generated by Django 3.1.2 on 2020-10-05 10:33 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.s...
StarcoderdataPython
139786
import torch import torch.nn as nn import torch.nn.functional as F from misc.utils import initialize_weights class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, use_bn=False, **kwargs): super(BasicConv, self).__init__() self.use_bn = use_bn self.conv = nn.Conv2d(in_ch...
StarcoderdataPython
3381099
# coding: utf-8 # flake8: noqa """ vautoscaling Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import # import models into model package from ncloud_vautoscaling.model.activity_log import ActivityLog from ncloud_vautoscaling.model.adjustment_type i...
StarcoderdataPython
3321242
# Generated by Django 3.1.3 on 2020-11-17 19:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapi', '0001_initial'), ] operations = [ migrations.CreateModel( name='Incidents', fields=[ ('id', ...
StarcoderdataPython
3262495
<reponame>germank/CommAI-env<gh_stars>0 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import term def all_reductions(t): for tr,_,_ in term.all_reductions(t): ...
StarcoderdataPython
122496
<gh_stars>1-10 from fastapi import APIRouter from .endpoints.languages import router as languages_router from .endpoints.recipes import router as recipes_router from .endpoints.topogen import router as topogen_router router = APIRouter() router.include_router(topogen_router) router.include_router(recipes_router) rout...
StarcoderdataPython
146130
from fastapi import APIRouter, Depends from fastapi.exceptions import HTTPException from fastapi.responses import RedirectResponse from odp.lib.media import MediaRepoClient from odp.lib.exceptions import MediaRepositoryError from odp.api_old.dependencies.media import get_media_repo_client router = APIRouter() @rout...
StarcoderdataPython
1680864
# -*- coding: utf-8 -*- """Test error handling.""" import frost.error import flask import werkzeug.exceptions def test_custom_handler(): app = flask.Flask(__name__) def handler(e): return e.name + '\n', e.code frost.error.register_error_handler(app, handler) @app.route('/good') def goo...
StarcoderdataPython
169008
import io import logging import sqlite3 from os.path import abspath, dirname, join, exists import numpy as np from speaker_verification.utils.logger import SpeakerVerificationLogger DATABASE_PATH = join(abspath(dirname(__file__)), "SQL", "sqlite.db") logger = SpeakerVerificationLogger(name=__file__) logger.setLevel(...
StarcoderdataPython
71707
import torch from .shape import Shape class Cube(Shape): def __init__(self,cube_size,position:tuple=(0.,0.,0.), orientation:tuple=(0.,0.,0.)): super().__init__(position,orientation) self.cube_size = cube_size def signed_distance_function(self,point_tensor): signed_distance_in_each_axi...
StarcoderdataPython
3241814
import ysports Y = ysports.YAuth() L = ysports.YLeague(Y) print L.name r, c = L.scoreboard(2) print r['status']
StarcoderdataPython
41423
""" Implements MissSVM """ from __future__ import print_function, division import numpy as np import scipy.sparse as sp from random import uniform import inspect from misvm.quadprog import IterativeQP, Objective from misvm.util import BagSplitter, spdiag, slices from misvm.kernel import by_name as kernel_by_name from m...
StarcoderdataPython
148813
<filename>src/pvc/widget/inventory.py # Copyright (c) 2015 <NAME> <<EMAIL>> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # ...
StarcoderdataPython
134007
<gh_stars>1-10 from nlstruct.models.bitag import BiTagSpanScorer from nlstruct.models.ner import SpanScorer, ContiguousEntityDecoder, NERPreprocessor
StarcoderdataPython
13242
"""state consumed Revision ID: 0be658f07ac6 Revises: bd1e892d0609 Create Date: 2021-07-18 21:26:04.588007 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import table, column from sqlalchemy import String # revision identifiers, used by Alembic. revision = '0be658f07ac6' down_revision = 'bd1e...
StarcoderdataPython
3302757
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from urllib.parse import urlparse from unittest.mock import Mock, patch from azure.core.pipeline.policies import ContentDecodePolicy, SansIOHTTPPolicy from azure.identi...
StarcoderdataPython