id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1792255
from rest_framework import serializers from league.models import Match, Team, League, MatchImage from account.models import User # Serializer for League # Account serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" # League serializers class...
StarcoderdataPython
3348298
<gh_stars>10-100 from __future__ import absolute_import from __future__ import division from __future__ import print_function from caffe2.python import core import caffe2.python.hypothesis_test_util as hu import caffe2.python.serialized_test.serialized_test_util as serial from hypothesis import given import hypothesis...
StarcoderdataPython
1798623
<filename>GA/draw_graph.py<gh_stars>0 import numpy as np import matplotlib.pyplot as plt def draw_sin(x: np.ndarray, y: np.ndarray, epoch): x_sin = np.arange(0, 128, 0.1) y_sin = np.sin(x_sin) plt.plot(x_sin, y_sin) plt.scatter(x, y, color='orange') plt.title(f'Epoch {epoch}') plt.show() def draw(*args):...
StarcoderdataPython
3380724
<filename>scenes/menu_main.py # -*- coding: utf-8 -*- from engine import scene class MenuMain(scene.Scene): """ The main menu scene. """ def __init__(self, *args, **kwargs): super(MenuMain, self).__init__(*args, **kwargs)
StarcoderdataPython
3391796
from string import ascii_lowercase from python.src.util.hashset import HashSet class SpellChecker: def __init__(self, words): self.words = words def is_correctly_spelled(self, word): # TODO: complete this function return False def get_suggestions(self, word): # TODO: co...
StarcoderdataPython
1682144
<gh_stars>1-10 from django.shortcuts import render def index(request): return render(request, 'cardgame/index.html') def play(request): type = request.GET.get('type') if type == 'default': context = {} else: context = {'extrascript': 'js/cardgame/' + type + '.js'} return render(re...
StarcoderdataPython
1660806
import unittest from webapp import create_app from webapp.models import db, User, Role from webapp.extensions import admin, rest_api class TestURLs(unittest.TestCase): def setUp(self): # Bug workarounds admin._views = [] rest_api.resources = [] app = create_app('webapp.config.Tes...
StarcoderdataPython
102629
from enum import Enum from deprecation import deprecated @deprecated(details="""Enum-value statuses are deprecated since SLIMS 6.4. Unless your SLIMS system still uses them (see Lab Settings), you should use the Status table and cntn_fk_status for status queries.""") class Status(Enum): "...
StarcoderdataPython
3226960
import cv2 import matplotlib.pyplot as plt import numpy as np from matplotlib.pyplot import figure import statistics as sts def get_bounding_box(img): # https://stackoverflow.com/questions/35854197/how-to-use-opencvs-connected-components-with-stats-in-python?fbclid=IwAR2oFmjaP_z7RTwvxh2hX86ChlZEvtY-MM8Qs2...
StarcoderdataPython
1670681
import os import sys import time glob = 'hello, i am global' childpid = 0 gdata0 = 'notinit' gdata1 = -1 def me(): pid = os.fork() if pid == 0: print('child here') loc = 'and this is childs play' print('c', glob) print(loc) time.sleep(5) print('goodbye') else: print('parent he...
StarcoderdataPython
4837373
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime def test_create_fulfillment_order(mws_client, mock_adapter, example_response): mock_adapter.register_uri( 'POST', ( mws_client.marketplace.endpoint + '/FulfillmentOutboundShipment/2010-10-...
StarcoderdataPython
168819
<reponame>fiifikrampah/family_device_inventory<gh_stars>0 """ This file contains the functional tests for the `devices` blueprint. These tests use GETs and POSTs to different URLs to check for the proper behavior of the `devices` blueprint. """ def test_inventory(client): """ GIVEN a Flask application config...
StarcoderdataPython
127712
<gh_stars>1-10 import random class ValueRange(object): """ Used to represent a range of possible values for a variable, parameter, or setting. """ def sample(self): """ Uses uniform selection to sample a single value from this range. """ raise NotImplementedError ...
StarcoderdataPython
51283
<gh_stars>1-10 class Trie(): def __init__(self): self.val = 0 self.next = dict() def __repr__(self): return f'{self.val} {self.next}' def makeTrie(words): trie, r_trie = dict(), dict() for word in words: l = len(word) trie[l], r_trie[l] = trie.get(l, dict(...
StarcoderdataPython
1666328
import configparser conf = configparser.ConfigParser() conf.read('config.cfg', encoding='utf-8') conf.get('ocr', 'lable_map_dict') print(conf.get('ocr', 'lable_map_dict'))
StarcoderdataPython
3345799
import streamlit as st import pandas as pd import pickle import numpy as np import sklearn st.write(""" ## Forest Fires """) st.sidebar.header('User Input') st.sidebar.subheader('Please enter your data:') # -- Define function to display widgets and store data def get_input(): # Display widg...
StarcoderdataPython
1669272
<reponame>Nhan121/plugins-DSS-platform- # -------------------------------------------------------------------------------- NOTEBOOK-CELL: CODE # If exist, drop all the comment above from dataiku.customrecipe import ( get_recipe_config, get_input_names_for_role, get_output_names_for_role, ) # --------------...
StarcoderdataPython
3319928
<reponame>RaspberryProgramming/ChatRoom #!/usr/bin/env python # -.- coding: utf-8 -.-y import socket import math import os import time import base64 from Crypto.Cipher import AES from Crypto import Random import threading import random import Queue import sys import argparse import datetime from multiprocessing import ...
StarcoderdataPython
3284595
# -*- coding: utf-8 -*- from plexapi.exceptions import NotFound from plexapi.utils import tag_singular import pytest from . import conftest as utils TEST_MIXIN_TAG = "Test Tag" CUTE_CAT_SHA1 = "9f7003fc401761d8e0b0364d428b2dab2f789dbb" def _test_mixins_tag(obj, attr, tag_method): add_tag_method = getattr(obj, "...
StarcoderdataPython
1734578
<reponame>rajitbanerjee/leetcode from collections import Counter class Solution: def longestPalindrome(self, s: str) -> int: longest = 0 for v in Counter(s).values(): # add all pairs of characters to palindrome length longest += (v // 2) * 2 # this is only execu...
StarcoderdataPython
3315584
<filename>lib/bot.py from game import Game from util import grouper, compose, transpose, flatten, display_board, dedupe from strategy import * class Bot: def __init__(self, verbose = 'quiet'): self.directions = ['up', 'down', 'left', 'right'] self.preferred_directions = ['up', 'left', 'right'] self.strat...
StarcoderdataPython
3241574
#!/usr/bin/python # -*- coding: utf-8 -*- """ ############### TF Version: 1.13.1/Python Version: 3.7 ############### """ import os import glob import random import shutil import tensorflow as tf from datetime import date, timedelta from tensorflow_estimator import estimator from model_local import lr, fm, deepcrossin...
StarcoderdataPython
3346017
<reponame>rnowling/aranyani """ Copyright 2019 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
StarcoderdataPython
4835267
from flask.app import Flask from unittest import TestCase from python_to_you import app class TestAppFactory(TestCase): def test_if_has_in_app_a_minimal_app(self): self.assertEqual( hasattr(app, 'minimal_app'), True, 'Do not has a minimal_app in app!' ) def...
StarcoderdataPython
101307
""" eep_functions.py (C) <NAME> Institute for Astronomy University of Hawaiʻi 2019 July 1 Python utilities to convert stellar evolution tracks to downsampled tracks based on Equivalent Evolutionary Phases (EEPs) according to the method of Dotter (2016). """ from multiprocessing import Pool import numpy as np from sc...
StarcoderdataPython
187899
from types import MappingProxyType GLOSSARY = MappingProxyType( { "Batch": "The batch system, e.g. PBS, LSF, SLURM, SGE, HTCondor, etc.", "CE": "Computing Element", "CLI": "Command Line Interface", "DICE": "Data Intensive Computing Environment", "FTS": "File Transfer Service...
StarcoderdataPython
133756
<filename>blog/models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class BlogPost(models.Model): title=models.CharField(max_length=255) author= models.ForeignKey(User, on_delete=models...
StarcoderdataPython
3354761
<reponame>thlux/fmodpy<filename>fmodpy/parsing/real.py from .argument import Argument class Real(Argument): type = "REAL" c_types = {"8":"ctypes.c_double", "4":"ctypes.c_float"} default_singleton = "1"
StarcoderdataPython
1720150
import os from collections import defaultdict import numbers import numpy as np import sys import os.path as osp import scipy.io as scio import random class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def re...
StarcoderdataPython
1694016
""" Copyright (c) 2015 SONATA-NFV ALL RIGHTS RESERVED. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
StarcoderdataPython
81410
from functools import partial from unittest.mock import ANY import pytest from bs4 import BeautifulSoup, element from flask import url_for from freezegun import freeze_time from app.main.views.feedback import ( PROBLEM_TICKET_TYPE, QUESTION_TICKET_TYPE, has_live_services, in_business_hours, ) from tes...
StarcoderdataPython
3329057
from __future__ import absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7 # Import applications import KratosMultiphysics as Kratos # Import base class file from KratosMultiphysics.kratos_utilities import CheckIfApplicationsAvailable if CheckIfApplicationsAvailable("Flui...
StarcoderdataPython
4834517
<gh_stars>10-100 #! /usr/bin/env python3.9 import atexit from queue import Queue from subprocess import CREATE_NO_WINDOW, Popen, PIPE import sys from threading import Thread from tkinter import BOTH, BooleanVar, Checkbutton, END, Frame, NONE, Text, Tk, ttk from tkinter.font import Font import psutil class HarmonbotG...
StarcoderdataPython
1755929
""" This file contains the Agent class. """ import itertools import datetime import pickle import os import logging import numpy as np from numpy.lib import recfunctions import pandas as pd from src.util import CONSTANT_NINF, get_dir_path from src.environment import Environment class Agent: """ Reinforcemen...
StarcoderdataPython
17835
# /*********************************************************************** # Copyright 2019 Google 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/LICE...
StarcoderdataPython
1691523
<filename>leetcode/weekly/84/find-and-replace-in-string.py class Solution: def findReplaceString(self, S, indexes, sources, targets): """ :type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str """ output_str...
StarcoderdataPython
38765
""" Configuration variables used in the application. These variables should be setup as environment variables in the docker-compose.yml file when launching all the services. If these environment variables are not present, default values are asigned to them. """ import os KAFKA_ENDPOINT = os.environ.get('KAFKA_ENDPOI...
StarcoderdataPython
1612578
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- # Created by Derek on 2021/10/26 """ ------------------------------------------------- File Name : main Description : data collection - batch process - data was collected from multiple sources and combined to become a single source of information Author : dere...
StarcoderdataPython
3309032
<gh_stars>1-10 import json import operator import tempfile import yaml from ansible.inventory import Inventory from ansible.parsing.dataloader import DataLoader from ansible.playbook import Playbook from ansible.vars import VariableManager from cloudmesh_client.shell.console import Console from cloudmesh_client.comm...
StarcoderdataPython
134928
import os import pygame class Heart(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() image_location = os.path.join("assets", "heart.png") self.image = pygame.image.load(image_location).convert_alpha() self.rect = self.image.get_rect() self.image = pygame....
StarcoderdataPython
3238142
<reponame>Digasi123percy/Beast-X<gh_stars>10-100 from beastx.events import register import base64 from . import * @register(pattern=".encode ?(.*)") async def encod(e): match = e.pattern_match.group(1) if not match and e.is_reply: gt = await e.get_reply_message() if gt.text: m...
StarcoderdataPython
3304472
history_types_dict = {}
StarcoderdataPython
196729
<gh_stars>0 """Initial Migration Revision ID: <PASSWORD> Revises: <PASSWORD> Create Date: 2021-06-19 22:50:18.089969 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<PASSWORD>' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade()...
StarcoderdataPython
3235845
<reponame>lcirrott/Kratos from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7 # Importing the Kratos Library import KratosMultiphysics # Importing the base class from KratosMultiphysics.from_json_check_result_process import FromJsonChec...
StarcoderdataPython
3357617
"""Evaluate ensemble""" import os import sys import argparse import numpy as np import torch import torch.nn.functional as F import data import models import utils parser = argparse.ArgumentParser(description="Ensemble evaluation") parser.add_argument("--dataset", type=str, de...
StarcoderdataPython
148378
<gh_stars>0 #!/usr/bin/env python import little_app import bson import sys from kaiju.arguments import ObjectId from kaiju.cli import KaijuCLI cli = KaijuCLI(little_app.trilotest.operations, description="Little test app") gargs, opargs = cli.parse_args(sys.argv[1:]) little_app.trilotest.h...
StarcoderdataPython
3349209
<gh_stars>0 from django.contrib import admin from .models import Adventure, Room, Choice # Register your models here. admin.site.register(Adventure) admin.site.register(Room) admin.site.register(Choice)
StarcoderdataPython
170727
import signal def install_shutdown_handlers(function, override_sigint=True): """Install the given function as a signal handler for all common shutdown signals (such as SIGINT, SIGTERM, etc). If override_sigint is ``False`` the SIGINT handler won't be install if there is already a handler in place (e.g...
StarcoderdataPython
4803970
#!/usr/bin/env python3 """ Tests the grand_trade_auto.apic.apic_meta functionality. Per [pytest](https://docs.pytest.org/en/reorganize-docs/new-docs/user/naming_conventions.html), all tiles, classes, and methods will be prefaced with `test_/Test` to comply with auto-discovery (others may exist, but will not be part of...
StarcoderdataPython
3312129
<reponame>JustIceQAQ/play_m3o_in_python # TODO Sentiment: https://m3o.com/sentiment/overview
StarcoderdataPython
1621054
<reponame>sujalgera01/Python3-by-practice #Print the string of number without using string function n = int(input("Enter the number: ")) r = range(1,n+1) print(*r,sep="")
StarcoderdataPython
3203400
<filename>seguranca_trabalho/submodels/empresa.py from django.db import models class Empresa(models.Model): class Meta: verbose_name="Empresa" verbose_name_plural="Empresas" __tablename__="sst_empresa" codigo = models.CharField(max_length=20, null=False) cnpj = models.CharField(max_leng...
StarcoderdataPython
3381479
<filename>demystifying_machine_learning_operations_(mlops)_prototype.py import pandas as pd import matplotlib.pyplot as plt import joblib from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error # Prepare data def prepare_dat...
StarcoderdataPython
1716697
# -*- coding: utf-8 -*- """ Read the Order details xlsx and extract data from it to the Order classes """ from openpyxl import load_workbook, Workbook from collections import OrderedDict ORDER_START_TOKEN = 'Line Item:' SIZE_BEGIN_TOKEN = 'Size' SIZE_END_TOKEN = 'Total Qty:' class StateError(Exception): def __i...
StarcoderdataPython
1679043
import logging import time import os import fabric.api import fabric.operations import cloudenvy.envy class Files(cloudenvy.envy.Command): def _build_subparser(self, subparsers): help_str = 'Upload arbitrary files from your local machine to an ' \ 'Envy. Uses the `files` hash in your...
StarcoderdataPython
1602707
import logging from app.event_server.service.persistence_service import PersistenceService from app.service.storage.elastic_storage import ElasticStorage rules_logger = logging.getLogger('Rules') class Rules(list): @staticmethod def storage() -> PersistenceService: return PersistenceService(Elastic...
StarcoderdataPython
16135
<reponame>migachevalexey/BigQuery-integrations<gh_stars>0 from google.cloud import bigquery from mysql.connector import connect import os # writeable part of the filesystem for Cloud Functions instance gc_write_dir = "/tmp" def get_file_mysql(mysql_configuration): """ Querying data using Connector/Python ...
StarcoderdataPython
64729
<reponame>minefarmer/Comprehensive-Python<gh_stars>0 ''' While Loops Used to execute a set of statements(code) continuously as long as a condition is True. The while loop needs to be setup in a way that as long as a condition is True, Then stop when the condition becomes False. While loop can have optional else...
StarcoderdataPython
24097
from datasets.hscic.hscic_datasets import scrape as datasets_scrape from datasets.hscic.hscic_indicators import scrape as indicators_scrape def main(workspace): datasets_scrape(workspace) indicators_scrape(workspace)
StarcoderdataPython
3340212
""" -*- coding: utf-8 -*- Time : 2019/7/18 17:14 Author : Hansybx """ import re from bs4 import BeautifulSoup from flask import jsonify from app.models.empty_classroom import ClassroomEmpty from app.models.error import PasswordFailed from app.utils.common_utils import sql_to_execute from app.utils.login.login_...
StarcoderdataPython
1682593
<reponame>Panthere/coinstream # -*- coding: utf8 -*- import os basedir = os.path.abspath(os.path.dirname(__file__)) CSRF_ENABLED = True SECRET_KEY = 'try-and-guess-you-chode' # Streamlabs Keys, These are only for the testapp, replace when in production STREAMLABS_CLIENT_ID = 'JD8Mwed8eJ1S1LgwqfCSCccbSKGtsr0FuVfk35Gw...
StarcoderdataPython
45336
#By @Joel_Noob from pyrogram import Client, filters from config import Config @Client.on_message( filters.private & filters.command("broadcast") & filters.user(Config.ADMINS) & filters.reply ) async def broadcast_(c, m): await c.start_broadcast( broadcast_message=m.reply_to_message, admin...
StarcoderdataPython
165441
#!/usr/bin/env python # -*- coding: utf-8 -*- ## @package ReadDataFIFO # test reading datafifo # from __future__ import print_function from __future__ import division import math,sys,time,os,shutil import socket import argparse import pprint from command import * def demux_fifodata(fData, adcVoffset=1.024, adcLSB=62...
StarcoderdataPython
1774305
<filename>Exercicios - py/ex015.py quantidade_days = int(input("Quantos dias você alugou o carro?: ")) quantidade_km = float(input("Quantos kms rodados com ele?: ")) calculo_empresa = (quantidade_days * 60) + (0.15 * quantidade_km) print("Você com {} km rodados em {} dias você necessita pagar {:.2f} R$.".format(quantid...
StarcoderdataPython
1699023
<filename>Medium/1079.LetterTilePossibilities.py ''' You have n tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles. Example: Input: tiles = "AAB" Output: 8 ...
StarcoderdataPython
191888
<filename>config/colorterms.py #colorterms = config.photoCal.colorterms from lsst.pipe.tasks.colorterms import ColortermDict, Colorterm config.data = { "ps1*": ColortermDict(data={ # Names used by Exposure.getFilter() in Gen2. # 'g': Colorterm(primary="g", secondary="r", c0=0.005728, c1=0.061749,...
StarcoderdataPython
3244397
from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework.schemas import get_schema_view from rest_framework_swagger.views import get_swagger_view router = DefaultRouter() router.register(r'hello', views.HelloViewSet) #schema view schema_view = get_swagger_view(ti...
StarcoderdataPython
55953
__version__ = 0.9 from .parser import * from .syntax import *
StarcoderdataPython
47057
<gh_stars>10-100 """ add_fc =============== Autogenerated DPF operator classes. """ from warnings import warn from ansys.dpf.core.dpf_operator import Operator from ansys.dpf.core.inputs import Input, _Inputs from ansys.dpf.core.outputs import Output, _Outputs from ansys.dpf.core.operators.specification import PinSpecif...
StarcoderdataPython
3312249
<reponame>ErikRoelofs/prototypical import pygame from drawer.complexObjectDrawer import ComplexObjectDrawer class DeckDrawer: def __init__(self, config): self.config = config def draw(self, deck): drawer = ComplexObjectDrawer(deck.cards[0].object, self.config) w, h = drawer.getCardSize...
StarcoderdataPython
3296007
def diff(a,b): return a - b def main(): print(f'Test Diff: {diff(10,20)}') if __name__ == '__main__': print(f'__name__:{__name__}') main()
StarcoderdataPython
1691939
# cfg file to test L1 RCT parameters import FWCore.ParameterSet.Config as cms # process process = cms.Process("L1RCTParametersTest") process.l1RCTParametersTest = cms.EDAnalyzer("L1RCTParametersTester") # number of events and source process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) ) proces...
StarcoderdataPython
3376037
#!/usr/bin/python3 import sys import os import pickle import pprint import pyfsdb from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, FileType def parse_args(): parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter, description=__doc__, ...
StarcoderdataPython
1701630
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 <NAME> 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 htt...
StarcoderdataPython
3387228
<filename>COMPONENTS/Propeller/PropellerData/Parser_UIUC_AeroData/airfoil_data_util.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 25 11:01:19 2020 @author: pfreitas97 Airfoil_data_util: Filter """ import os import shutil # ''.join([char for char in first_line if char not in SPECIAL_CHAR...
StarcoderdataPython
59513
<reponame>anukaal/dict_minimize from setuptools import find_packages, setup from dict_minimize import __version__ def read_requirements(name): with open("requirements/" + name + ".in") as f: requirements = f.read().strip() requirements = requirements.replace("==", ">=").splitlines() # Loosen strict ...
StarcoderdataPython
171763
<reponame>Christin95/mseg-semantic #!/usr/bin/python3 from typing import Tuple import numpy as np import torch from torch import nn """ Utilies to compute quantities required to compute IoU per class on a single image, using Numpy or Pytorch. """ def intersectionAndUnion( output: np.ndarray, target: np.ndarra...
StarcoderdataPython
183018
<reponame>etiennody/purbeurre-v2<gh_stars>0 """ Django settings for purbeurre_project project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.dj...
StarcoderdataPython
78785
import unittest import os from translator import utils class TestUtils(unittest.TestCase): def test_project_root_path(self): self.assertEqual(os.path.dirname(os.path.dirname(__file__)), utils.get_project_root_path()) def test_get_random_int(self): self.assertIn(utils.get_random_int(0, 1), [0,...
StarcoderdataPython
3366584
<reponame>CodeProcessor/sports-events-detection<filename>training_pipeline/step3_model_training/clasification/pretrained_models.py #!/usr/bin/env python3 """ @Filename: pretrained_models.py @Author: dulanj @Time: 30/01/2022 12:01 https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutori...
StarcoderdataPython
3258728
<reponame>yui-u/emerge-chord-function import pandas as pd import torch from torch.utils.data import DataLoader, RandomSampler from core.common.constants import * from core.preprocess.dataset import CustomCollate, CustomDataset from core.preprocess.instances import batch_to_device class Evaluator(object): @static...
StarcoderdataPython
74660
<filename>import.py # This module transforms records from a csv file into a sqlite database # using pure (as opposed to flask_sqlalchemy which will be used at # next step) SQLAlchemy orm to create the database import csv import os from sqlalchemy import create_engine, ForeignKey from sqlalchemy.ext.declarative import...
StarcoderdataPython
3306625
<filename>sudoku_puzzle_solver.py import math def column_names(puzzle_string): puzzle_size = int(math.sqrt(len(puzzle_string))) # 65 is the ASCII number for a capital A return ''.join(chr(ord('A') + col_number) for col_number in range(puzzle_size)) def row_names(puzzle_string): puzzle_size = int(mat...
StarcoderdataPython
3371615
# -*- coding: utf-8 -*- import os.path from core import GsxObject from lookups import Lookup STATUS_OPEN = 'O' STATUS_CLOSED = 'C' STATUS_ESCALATED = 'E' STATUSES = ( (STATUS_OPEN, 'Open'), (STATUS_CLOSED, 'Closed'), (STATUS_ESCALATED, 'Escalated'), ) CONTEXTS = ( ('1', 'Serial Number'), ('2', '...
StarcoderdataPython
3296425
from abaqusConstants import * from .LayerPropertiesArray import LayerPropertiesArray from .RebarLayers import RebarLayers from .ShellSection import ShellSection from .TransverseShearShell import TransverseShearShell class GeometryShellSection(ShellSection): """The GeometryShellSection object defines the propertie...
StarcoderdataPython
1660425
__version__ = 0, 0, 1 class MicroDjango(object): NAME = '__main__' def __init__(self, **settings): module = self.get_module(self.NAME) self._urlpatterns_module = \ Module('urlpatterns', module, urlpatterns=[]) self._urlpatterns_module.install() ...
StarcoderdataPython
4838417
import smtplib import xml.dom import unittest from nose.tools import eq_, raises from funfactory.manage import import_mod_by_name class TestImporter(unittest.TestCase): def test_single_mod(self): eq_(import_mod_by_name('smtplib'), smtplib) def test_mod_attr(self): eq_(import_mod_by_name('s...
StarcoderdataPython
118536
# -*- coding: utf-8 -*- # Copyright (c) 2021 Mantium, 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...
StarcoderdataPython
98716
import torch import torch.nn as nn import torch.nn.functional as F from Regressor import Regressor from utils import *; class Model(nn.Module): def __init__(self, input_dim, embed_dim, output_dim, data=None): super(Model, self).__init__() self.input_dim = input_dim; self.embed_dim = embed_d...
StarcoderdataPython
3311884
<gh_stars>0 import typing as T from dataclasses import dataclass, field from moonleap import Resource, Term from moonleap.resource.rel import Rel from moonleap.utils.inflect import plural from moonleap.verbs import uses from titan.api_pkg.item.resources import Item from titan.api_pkg.pkg.ml_name import ml_type_spec_fr...
StarcoderdataPython
3336080
from abc import abstractmethod import tensorflow as tf import tensorflow_probability as tfp from tensorflow import math as tfm from alfi.mcmc.results import GenericResults import numpy as np f64 = np.float64 class MetropolisKernel(tfp.mcmc.TransitionKernel): def __init__(self, step_size, tune_every=20): ...
StarcoderdataPython
1636450
<gh_stars>0 # Copyright 2022 New Vector 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
StarcoderdataPython
3396586
# run a test server from app import app app.run(host='0.0.0.0', port=5000, debug=True)
StarcoderdataPython
3385253
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: from easyai.base_name.model_name import ModelName from easyai.base_name.backbone_name import BackboneName from easyai.base_name.block_name import NormalizationType, ActivationType from easyai.base_name.block_name import LayerType, BlockType from easyai.base_name.l...
StarcoderdataPython
3216762
<filename>tron/Hub/KV/KVDict.py __all__ = ['KV', 'KVDict', 'kvAsASCII'] import time from collections import OrderedDict from tron import Misc from tron.Misc.cdict import cdict """ Rethought a bit. All keys are stored as strings (or reprs), but may need to be extracted as some given type. Keys only exist in ...
StarcoderdataPython
1684287
from flask import Blueprint, g, jsonify from rowboat.models.guild import Guild from rowboat.util.decos import authed users = Blueprint('users', __name__, url_prefix='/api/users') @users.route('/@me') @authed def users_me(): return jsonify(g.user.serialize(us=True)) @users.route('/@me/guilds') @authed def user...
StarcoderdataPython
1687509
<gh_stars>1-10 # -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name,missing-docstring """Quick program to test the quantum information states modu...
StarcoderdataPython
3225362
# -*- coding: utf-8 -*- import dao.PersonDAO as PersonDAO import manager.PermissionManager as PermissionManager def get_all(): get_first_name_last_name(None, None) def get_first_name(first_name): get_first_name_last_name(first_name, None) def get_last_name(last_name): get_first_name_last_name(None, ...
StarcoderdataPython
1710722
import RPi.GPIO as GPIO import slcypi.slcyGeneral as General # GPIO.HIGH = 1 # GPIO.LOW = 0 class OutPin(): """Sets up a pin for output pin <dict>, <list>, <int>, {'out':1} [name] <str>, identify this pin [verbose] <bool>, print every action """ def __init__(self,pins={},name='',verbose=False...
StarcoderdataPython
1673108
import os class Config(object): _ydb_endpoint = os.getenv("YDB_ENDPOINT") _ydb_database = os.getenv("YDB_DATABASE") _ydb_path = os.getenv("YDB_PATH", "") _reservation_period_minutes = int(os.getenv("RESERVATION_PERIOD_MINUTES", "60")) @classmethod def ydb_endpoint(cls): return cls._y...
StarcoderdataPython