id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1811670
<reponame>MatheusProla/Codestand # -*- coding: utf-8 -*- import os from django.db import models from django.db.models.signals import post_delete from django.conf import settings from django.contrib.auth.models import User from django.template.loader import render_to_string from django.template.defaultfilters import li...
StarcoderdataPython
1839194
<gh_stars>0 import os from terminaltables import SingleTable from repository.repo import Repo import ui.console_utils as console import ui.one_line_table as olt from ui.statistics_menu import StatisticsMenu from utils.input_checker import Parser from services import add, update, remove class Handler: """ ...
StarcoderdataPython
6418862
# Write a function that will reverse a integer number using a stack and return the reversed number as an integer. # For example, if your input number is 3479 the function will return 9743. def reverse_num(nums): stack = "" for num in str(nums): # stack.insert(len(stack),num) #if stack was an array ...
StarcoderdataPython
368807
import pickle import numpy as np from scipy import stats breath_type="strong" model_name="strong_multi_cnn-lstm_0" list_test_acc=[] list_test_eer_KNN=[] list_test_eer_GMM=[] with open('results/outputs/'+breath_type+'/list_test_acc_'+model_name, 'rb') as filehandle: list_test_acc = pickle.load(filehand...
StarcoderdataPython
3280218
from datetime import datetime, timedelta from unittest import TestCase from mock import Mock import elasticsearch import yaml from . import testvars as testvars import curator class TestEnsureList(TestCase): def test_ensure_list_returns_lists(self): l = ["a", "b", "c", "d"] e = ["a", "b", "c", "d"...
StarcoderdataPython
9692112
"""Test our DSM Parsing.""" import datetime try: from zoneinfo import ZoneInfo except ImportError: from backports.zoneinfo import ZoneInfo import pytest from pyiem.util import utc, get_test_file from pyiem.nws.products.dsm import process, parser, compute_time def create_entries(cursor): """Get a databas...
StarcoderdataPython
4812545
<reponame>pyequion/pyequion<gh_stars>0 # -*- coding: utf-8 -*- import pyequion2 from pyequion2 import gaseous_system, converters gsys = gaseous_system.InertGaseousSystem(["CO2(g)"], fugacity_model="PENGROBINSON") logacts = gsys.get_fugacity({"CO2(g)":1.0}, 300, 100) fugacity = 10**logacts['CO2(g)']
StarcoderdataPython
6484543
import argparse import torch def get_args(args): parser = argparse.ArgumentParser(description='RL') parser.add_argument( '--algo', default='a2c', help='algorithm to use: a2c | ppo | acktr') parser.add_argument( '--experiment-name', default='default', help='experiment name for save models'...
StarcoderdataPython
1805934
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six fr...
StarcoderdataPython
3498341
# Multi-Collinearity: https://stackoverflow.com/questions/25676145/capturing-high-multi-collinearity-in-statsmodels # Imputation: https://www.theanalysisfactor.com/multiple-imputation-in-a-nutshell/ # Visualisation: catscatter for categoricals: https://towardsdatascience.com/visualize-categorical-relationships-with-ca...
StarcoderdataPython
11382274
<gh_stars>1-10 # # Lockstep Software Development Kit for Python # # (c) 2021-2022 Lockstep, Inc. # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. # # @author <NAME> <<EMAIL>> # @copyright 2021-2022 Lockstep, Inc. # @version 2022.4 # @...
StarcoderdataPython
5001568
#Here's some strange new stuff, remember type it exactly :) days = "Mon Tue Wed Thu Fri Sat Sun" months="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\n" print("Here are the days:", days) print("Here are the months", months) print("""There's something going on here. With the three double-quotes. We'll be able to type as mu...
StarcoderdataPython
6609243
import aiohttp import asyncio from colorama import * class Auxiliary: config = { } def show_options(self): print(Fore.YELLOW+"Options\t\tNecessity\t\tDefault"+Style.RESET_ALL) print(Fore.YELLOW+"-------\t\t---------\t\t-------"+Style.RESET_ALL) for key in sorted(self.config.keys()): print(Fore.YELLOW+"%...
StarcoderdataPython
5002568
""" Script is a duplicate of https://github.com/pytorch/pytorch/blob/v1.1.0/torch/utils/data/dataloader.py Except this dataloader makes use of datasets that takes in list for __getitem__ """ import torch.utils.data import torch.multiprocessing as multiprocessing from torch.utils.data import SequentialSampler, RandomSa...
StarcoderdataPython
6495987
<filename>code/sample_2-1-8.py x = 4*3 print(x)
StarcoderdataPython
1798390
<reponame>eivinasbutkus/lightning-pose import glob import os import numpy as np import hydra import torch from omegaconf import DictConfig, OmegaConf from pose_est_nets.utils.plotting_utils import ( predict_videos, ) from pose_est_nets.utils.io import ( get_absolute_hydra_path_from_hydra_str, ckpt_path_fro...
StarcoderdataPython
11221118
event_data_list = { "TEST": { "MESSAGE": '{"body":"Hello World !!!"}', "TOPIC_ARN": 'arn:aws:sns:eu-west-1:558711342920:development_TEST', } } def fetch_event_data_list(): return event_data_list
StarcoderdataPython
11201153
<reponame>jjj-design/pyhees<gh_stars>0 # ============================================================================ # 付録 A 機器の性能を表す仕様の決定方法 # ============================================================================ # ============================================================================ # A.2 定格暖房能力 # =====...
StarcoderdataPython
11315144
""" Item 39: Use @classmethod Polymorphism to Construct Objects Generically """ #!/usr/bin/env PYTHONHASHSEED=1234 python3 # Reproduce book environment import random random.seed(12345) import logging from pprint import pprint from sys import stdout as STDOUT # Write all output to a temporary directory import ate...
StarcoderdataPython
1755642
import logging class GeoQuery(object): """ Object that encapsulates a query for a particular GeoJSON polygon or multi-polygon. """ def __init__(self, loc_field_list, poly_region): self.loc_field_list = loc_field_list self.region = poly_region def get_query(self): ...
StarcoderdataPython
1618518
"""Unit test package for test_cookie_cutter_v2."""
StarcoderdataPython
6597575
from typing import Text import matplotlib.pyplot as plt import numpy as np import random import TuneUp_functions as maths import csv import pygame import time as t from time import sleep import pygame.freetype pygame.freetype.init() #thrust curves courtesy of https://www.thrustcurve.org/ e12_thrust = [ [0.052, 5.0...
StarcoderdataPython
6648813
<reponame>dbergqvist/K8s_demo import sys import ConfigParser from StringIO import StringIO def main(config_filename, config_key): if config_filename == '-': config_file = sys.stdin else: config_file = open(config_filename) with config_file: parser = ConfigParser.SafeConfigParser() ...
StarcoderdataPython
3343094
<gh_stars>0 """ * @name Pocet Stvorcov * @language Python * @author FekyDEV * @authorId 603505971507101698 * @version 1.1.0 * @invite sKKEyUn * @source https://github.com/FekyDEV/python-school/edit/main/Pocet%20Stvorcov/basic_version.py * @license MIT """ ## VSTUP ## import turtle pero = turtle.T...
StarcoderdataPython
5109344
<reponame>pratheeshrussell1992/generator-djangoacs from django.shortcuts import render from http import HTTPStatus from django.views.decorators.csrf import csrf_exempt from ..models.serializers.userSerializer import UserRegisterSerializer from ..models.user import User import io from rest_framework.parsers import JSON...
StarcoderdataPython
11300612
<gh_stars>10-100 # --*-- coding : utf-8 --*-- """Author: Trinity Core Team MIT License Copyright (c) 2018 Trinity Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including w...
StarcoderdataPython
216419
#!/usr/bin/env python # -*- coding: utf8 -*- # # Copyright (c) 2014 unfoldingWord # http://creativecommons.org/licenses/MIT/ # See LICENSE file for details. # # Contributors: # <NAME> <<EMAIL>> # # Requires PyGithub. ''' Creates a Github repo for the specified namespace. ''' import os import sys import codecs f...
StarcoderdataPython
6611478
<reponame>leschzinerlab/myami-3.2-freeHand #!/usr/bin/env python import sys import math import time import numpy from appionlib import apDisplay """ File of functions that solve least square problems in matrix notation: X * beta = Y which is equivalent to: beta[1] * X[1,1] + beta[2] * X[1,2] + ... = y[1] bet...
StarcoderdataPython
5054898
<reponame>hmelberg/snotra import pandas as pd import os from .core import * # todo: make a proper config file _PATH = os.path.abspath(core.__file__) # %% monkeypatch to the functions become methods on the dataframe # could use decorators/pandas_flavor # pandas_flavor: good, but want to eliminate dependencies # appro...
StarcoderdataPython
1683922
<filename>model.py from typing import Dict, Text import ddsp import tensorflow as tf def get_model(SAMPLE_RATE,CLIP_S,FT_FRAME_RATE,Z_SIZE,N_INSTRUMENTS,IR_DURATION,BIDIRECTIONAL,USE_F0_CONFIDENCE,N_HARMONICS,N_NOISE_MAGNITUDES): class CustomRnnFcDecoder(ddsp.training.nn.OutputSplitsLayer): """RNN and F...
StarcoderdataPython
227273
<reponame>athalonis/CCL-Verification-Environment #!/usr/bin/env python3 #Copyright (c) 2014, <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: # #* Redistributions of source code must ...
StarcoderdataPython
6517930
<reponame>AndrewZhuZJU/Finetune-pytorch ######################################## # Created by andrew # 2018/6/12 # predict label with a trained model ######################################## import torch.utils.data as data from torchvision import transforms import numpy as np from PIL import Image import os class Te...
StarcoderdataPython
5195971
<reponame>thomaspinder/treeo import dataclasses import re import typing as tp import jax import jax.numpy as jnp import numpy as np import typing_extensions as tpe A = tp.TypeVar("A") B = tp.TypeVar("B") key = jax.random.PRNGKey _pymap = map _pyfilter = filter OpaquePredicate = tp.Callable[["Opaque", tp.Any], bool]...
StarcoderdataPython
3231875
from distutils.core import setup, Extension module1 = Extension('jay', sources = ['cmodule.c']) setup(name = 'jay', version = '1.0', description = 'This is a demo package from Jay.', ext_modules = [module1])
StarcoderdataPython
8187767
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^accounts/', include('allauth.urls')), url(r'^accounts/login/profile/', views.profile, name="profile"), url(r'^ajax/validate_username/$', views.validate_username, name='validate_username'), ]
StarcoderdataPython
198289
<gh_stars>0 from lib.commonlib import notify, get_current_time_parameters import shutil def check_space(config): """ This is the template method which calls all the required methods for space checking and alert generation. :param config: The config.json configuration. :return: None, ideally should ret...
StarcoderdataPython
9776956
<gh_stars>1-10 # Copyright (c) 2013-2015 Centre for Advanced Internet Architectures, # Swinburne University of Technology. All rights reserved. # # Author: <NAME> (<EMAIL>) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are m...
StarcoderdataPython
1660269
"""This module contains the base classes for dealing with extensions.""" from __future__ import annotations import ast from griffe.agents.nodes import ObjectNode class BaseVisitor: """The base class for visitors.""" def visit(self, node: ast.AST) -> None: """Visit a node. Parameters: ...
StarcoderdataPython
6449159
import sys from .base import jax_wrap import jax.numpy as jnp # Add the fft functions module = sys.modules[__name__] names = [ "fft", "ifft", "fft2", "ifft2", "fftn", "ifftn", "rfft", "irfft", "rfft2", "irfft2", "rfftn", "irfftn", "fftfreq", "rfftfreq", "iff...
StarcoderdataPython
1621404
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- """ Find optimal RCA parameters for each test case by optimizing over 9000 different parameter combinations. """ import os import glob from functools import partial import numpy as np from psutil import cpu_count from sporco.util import grid_search from cdl...
StarcoderdataPython
6446572
<gh_stars>0 from telnyx.aio.api_resources.abstract import ListableAPIResource, UpdateableAPIResource class ShortCode(ListableAPIResource, UpdateableAPIResource): OBJECT_NAME = "short_code"
StarcoderdataPython
11387175
from struct import unpack from ..six import xrange, btou class BinaryDecoder: """Decoder for the avro binary format. NOTE: All attributes and methods on this class should be considered private. Parameters ---------- fo: file-like Input stream """ def __init__(self, fo): ...
StarcoderdataPython
8184221
"""This module contains some auxiliary functions shared across the utility scripts.""" import argparse import difflib import os import subprocess as sp LABS_ROOT = os.environ["PROJECT_ROOT"] + "/labs" LABS_NAME = [] LABS_NAME += ["optimization", "integration", "approximation"] LABS_NAME += ["linear_equations", "nonli...
StarcoderdataPython
8185019
<reponame>umkcdcrg01/ryu_openflow # Iperf_controller_v1.py # <NAME> # Iperf Match filed # in_port=int(inport), eth_dst=dst_mac, eth_src=src_mac, eth_type=0x0800, ipv4_src=src_ip, # ipv4_dst=dst_ip, ip_proto=6, tcp_dst=tcp_dst_port, tcp_src=t...
StarcoderdataPython
9691106
<gh_stars>0 class WaterLevel: """Represents waterlevel in the api""" def __init__(self, value, time, data_type, tide=None): """ :param value: height of the tide :param time: time of this height of the tide :param data_type: data type. Myst be prediction, observation, weathereffec...
StarcoderdataPython
8025021
<gh_stars>0 """Top-level import for all CLI-related functionality in apitools. Note that importing this file will ultimately have side-effects, and may require imports not available in all environments (such as App Engine). In particular, picking up some readline-related imports can cause pain. """ # pylint:disable=w...
StarcoderdataPython
394983
from config import Configuration from model import Model import utils as ut import numpy as np import tensorflow as tf import sys import time import os def train(config, model, session, X, X_length, X_mask, alpha, schedule, beta, Y, Y_length, Y_mask): #We're interested in keeping track of the loss during training...
StarcoderdataPython
5008752
from django.db import models from django.utils.translation import ugettext_lazy as _ FORM_TYPES = ( ('contact', _('Contact form')), ('question', _('Questions form')) ) class FormType(models.Model): class Meta: app_label = 'feedback' verbose_name = _('Form type') verbose_name_plura...
StarcoderdataPython
9638133
<filename>flybirds/core/plugin/plugins/default/ios/page.py # -*- coding: utf-8 -*- """ ios page core api implement """
StarcoderdataPython
3207038
import random welcomeMessage = """ ------------------------------------ | | | Welcome to the Number Guesser! | | | ------------------------------------ Do q or quit to quit. """ print(welcomeMessage) def Function(): try: am...
StarcoderdataPython
11335644
#!/usr/bin/env python # Copyright 2017, 2018 Google, 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 re...
StarcoderdataPython
4829260
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list ...
StarcoderdataPython
12800753
import unittest from speechkit.exceptions import RequestError class RequestErrorTestCase(unittest.TestCase): def test_raise_data_1(self): with self.assertRaises(RequestError) as cm: raise RequestError({'code': 3, 'message': 'message'}) the_exception = cm.exception self.assert...
StarcoderdataPython
6441607
<filename>tests/test_02_actions/test_echo.py import pytest # noinspection PyPackageRequirements import json from aionetworking.actions.echo import InvalidRequestError from aionetworking.utils import aone class TestEcho: @pytest.mark.asyncio async def test_00_do_one(self, echo_action, echo_request_object, e...
StarcoderdataPython
3577956
#FLM: Font: Generate OT Features from alternates # VER: 1.9 #---------------------------------- # Foundry: FontMaker # Typeface: Bolyar Sans # Date: 28.01.2019 #---------------------------------- # - Dependancies import fontlab as fl6 from typerig.proxy import pFont from typerig.string import figureNames from c...
StarcoderdataPython
1898635
<filename>data.py import datetime import random from discord.ext.commands import Bot as Bot_ from utils.io import JSONFile class Bot(Bot_): def __init__(self, config): self.token = config.token self.config = config super().__init__(command_prefix=config.prefix) self.data = JSONFil...
StarcoderdataPython
3570072
<gh_stars>10-100 from pymongo import MongoClient from time import time import model import config class DAO: def __init__(self, coll, item_type, bot_id=None): self.coll = coll assert issubclass(item_type, model.Model) self.type = item_type self.bot_id = bot_id def get_by_id(s...
StarcoderdataPython
1753794
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-11-21 14:18 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('geneseekr', '0004_topblasthit_gene_name'), ] ...
StarcoderdataPython
3444512
<gh_stars>0 """ Copyright (c) IBM 2015-2017. All Rights Reserved. Project name: c4-system-manager This project is licensed under the MIT License, see LICENSE """ from datetime import datetime import json import logging import re from c4.system.backend import Backend from c4.utils.logutil import ClassLogger from c4.ut...
StarcoderdataPython
4811534
# # Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved. # import os from PySide import QtGui def LoadFabricPixmap(basename): """Loads the contents of the pixmap below Args: basename (str): Stylesheet base name. Returns: pixmap """ fabricDir = os.enviro...
StarcoderdataPython
9669051
# programming project for CS563 - Fall2017 # written by <NAME> # # any questions please email: <EMAIL> from Tkinter import * from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Cipher import AES import tkMessageBox # Asymmetric class class Asymmetric: # Asymmetric initializer def __init__...
StarcoderdataPython
6431432
<reponame>RuiCunhaM/snmpsim<gh_stars>100-1000 # # This file is part of snmpsim software. # # Copyright (c) 2010-2019, <NAME> <<EMAIL>> # License: http://snmplabs.com/snmpsim/license.html # # SNMP Agent Simulator # from snmpsim import error from snmpsim.reporting.formats import alljson from snmpsim.reporting.formats imp...
StarcoderdataPython
5088146
<reponame>Alex-Roudjiat/Federated-ML-AI-Federated-ML- import logging import torch from torch import nn, optim from fedml_api.distributed.fedgkt import utils class GKTClientTrainer(object): def __init__(self, client_index, local_training_data, local_test_data, local_sample_number, device, client...
StarcoderdataPython
1715322
import re from collections import OrderedDict ########################################################################################## # # Functions # ########################################################################################## def split_quoted(text): matches=re.findall(r'\"(.+?)\"',text) re...
StarcoderdataPython
8030800
from tsunami.conf import settings from tsunami import web import functools import pickle class BaseHandler: async def get(self, request): raise web.HTTPMethodNotAllowed('get', '*') async def post(self, request): raise web.HTTPMethodNotAllowed('post', '*') async def delete(self, request)...
StarcoderdataPython
1973013
<filename>aula09.py frase = 'Curso em Vídeo Python' print(frase[3]) # printa a quarta letra print(frase[:13]) # fatiamento print(frase.count('o')) # conta quantas letras o número de letras o print(frase.upper().count('O')) # transforma em caixa alta e conta o números de letras O print(len(frase)) # conta o tamanho...
StarcoderdataPython
12854165
<filename>waio/factory/models/contact.py from dataclasses import dataclass from typing import List, Optional, Union @dataclass class PayloadSender: phone: int name: str @dataclass class BaseModel: sender: PayloadSender payload_id: str @dataclass class PayloadContactName: first_name: str fo...
StarcoderdataPython
1978846
from euler import elapsed_time, factors, memorize from functools import lru_cache @memorize() def D(n): # assumption: factors() returns 1 and 2 in the first # 2 positions of the result set. return sum(factors(n)[2:]) + 1 def is_amicable(n): a = D(n) return n == D(a) and n != a @elapsed_time() ...
StarcoderdataPython
1620538
from bs4 import BeautifulSoup import requests import sys reload(sys) sys.setdefaultencoding('utf8') def download(title, url, m): # req = request.Request(url) # print (url) response = requests.get(url) # response = response.read().decode('utf-8') response.encoding = 'utf-8' print (response.sta...
StarcoderdataPython
5019557
# coding: utf-8 # # Copyright 2014 The Oppia Authors. 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 requi...
StarcoderdataPython
1660020
""" Email: <EMAIL> Date: 2018/9/28 """ import datetime as dt import numpy as np import torch import torch.nn as nn from .loader import get_txt_data class Timer(): """计时器类""" def start(self): self.start_dt = dt.datetime.now() def stop(self): end_dt = dt.datetime.now() spend = (...
StarcoderdataPython
9640416
<reponame>saber-khakbiz/WebScripting-Digikala<filename>InPutSetting.py<gh_stars>0 from tkinter.constants import ACTIVE from typing import DefaultDict import tkinter as tk window =tk.Tk() window.geometry("300x200") window.resizable(width = False, height = False) window.title("SQL Configuration") User_var = tk.Strin...
StarcoderdataPython
4845036
<gh_stars>0 import pandas as pd from googleapiclient.discovery import Resource def required_scopes() -> list: return ['https://www.googleapis.com/auth/spreadsheets'] def write_to_spreadsheet(service: Resource, spreadsheet_id: str, spreadsheet_range: str, df: pd.DataFrame, **kwargs) -> dict: value_input_opti...
StarcoderdataPython
6638252
<filename>djangocms_transfer/cms_plugins.py import json from django.core.exceptions import PermissionDenied from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.urls import re_path, reverse from django.utils.http import urlencode from django.utils.translation imp...
StarcoderdataPython
12827421
<filename>pyy1/.pycharm_helpers/pydev/_pydevd_bundle/pydevd_trace_dispatch_regular.py import traceback from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_imps._pydev_saved_modules import threading from _pydevd_bundle.pydevd_constants import get_thread_id from _pydevd_bundle.pydevd_dont_trace_f...
StarcoderdataPython
1946437
from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) url = models.URLField() poster = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) # this is to show the po...
StarcoderdataPython
3583777
import atexit import bisect import collections import gzip import os import re import subprocess import tempfile import utils from pyminisolvers import minisolvers class MinisatSubsetSolver(object): def __init__(self, infile, rand_seed=None, store_dimacs=False): self.s = minisolvers.MinisatSubsetSolver() ...
StarcoderdataPython
3245803
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter def DrawQuiver(): X = np.arange(-10, 10, 1) Y = np.arange(-10, 10, 1) U, V = np.meshgrid(X, Y) fig, ax = plt.subplots() ...
StarcoderdataPython
3309548
<filename>mogptk/gpr/util.py from . import Parameter, Mean, Kernel def _find_parameters(obj): if isinstance(obj, Parameter): yield obj elif isinstance(obj, list): for i, v in enumerate(obj): yield from _find_parameters(v) elif issubclass(type(obj), Kernel) or issubclass(type(obj...
StarcoderdataPython
4875567
<filename>js/leaflet/__init__.py from fanstatic import Library, Resource library = Library('leaflet', 'resources') leaflet_css = Resource( library, 'leaflet.css', minified='leaflet.min.css', minifier='cssmin' ) leaflet = Resource( library, 'leaflet-src.js', minified='leaflet.js', mini...
StarcoderdataPython
1634294
<filename>analyse/caches.py #! /usr/bin/env python3.3 ######################################################################################## import argparse import csv import datetime import json import os import os.path import sys ####################################################################################...
StarcoderdataPython
3521486
<filename>jsonzilla/protocol.py<gh_stars>0 import functools import json import logging import os import random import requests DEBUG = os.getenv('JSONZILLA_DEBUG', False) if DEBUG: import httplib httplib.HTTPConnection.debuglevel = 1 #logging.basicConfig() # you need to initialize logging, otherwise you ...
StarcoderdataPython
12828178
# coding=utf8 from .base import EChartsMixin from .backend import EChartsBackendView from .frontend import EChartsFrontView __all__ = ['EChartsMixin', 'EChartsBackendView', 'EChartsFrontView']
StarcoderdataPython
9638906
<filename>ramda/without_test.py<gh_stars>10-100 from ramda.private.asserts import assert_iterables_equal from .without import without def uniq_nocurry_test(): assert_iterables_equal(without([1, 2], [1, 2, 1, 3, 4]), [3, 4]) def take_curry_test(): assert_iterables_equal(without([1, 2])([1, 2, 1, 3, 4]), [3, ...
StarcoderdataPython
365417
<gh_stars>100-1000 # This adds github based oauth to your everware setup # You will have to create a OAuth app on github.com # and store information about it in your environment import os c.JupyterHub.authenticator_class = 'everware.GitHubOAuthenticator' c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_...
StarcoderdataPython
9603884
from django.test import TestCase from views import translate_text # Create your tests here. class testLanguageChange(TestCase): def testTranslateText(self): self.assertEqual(translate_text('fr', 'Hello'), 'Bonjour', msg="Wrong translation!") self.assertEqual(translate_text('de', 'Hello'), 'Hallo',...
StarcoderdataPython
1674337
<filename>src/pss_tournament.py from datetime import datetime from typing import List from discord import Colour, Embed import pss_core as core import utils # ---------- Tournament ---------- def convert_tourney_embed_to_plain_text(embed: Embed) -> List[str]: result = [f'**{embed.author.name}**'] for field...
StarcoderdataPython
6407022
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from . import utilities, tables class Network...
StarcoderdataPython
3448196
import mysql.connector list_detect=['13CS03','13CS07' cnx = mysql.connector.connect(user='root', password='<PASSWORD>', host='127.0.0.1', database='project') if(cnx): if(cnx): cursor=cnx.cursor() q1="select count(*) from sregister" cursor.execute(q1) result1=cursor.fetchone() ...
StarcoderdataPython
103732
#!/usr/bin/env python try: from functools import reduce except: pass def mandelbrot(a): return reduce(lambda z, _: z*z + a, range(50), 0) def step(start, step, iterations): return (start + (i * step) for i in range(iterations)) rows = (('*' if abs(mandelbrot(complex(x, y))) < 2 else ' ' for x in ...
StarcoderdataPython
8148310
import sdl2 import sdl2.ext import glm import math # Draws robot (box) on the colored surface def draw_rect(surface, position, width, height, color): # draw rect from upper left hand corner x = position[0] y = position[1] w = width h = height # Draw the filled rect with the specified colo...
StarcoderdataPython
5139600
from moonfire_tokenomics.data_types import Allocation, AllocationRecord, Blockchain, Category, CommonType, Sector, Token mft = Token( name="MFT", project="Mainframe", sector=Sector.DEFI, blockchain=[Blockchain.ETH], category=[Category.GOV], capped=True, allocations=[ Allocation( ...
StarcoderdataPython
8104658
<filename>tests/factories.py from faker import Factory, Faker from db import db from models import CreatorModel, SecretModel class BaseFactory(Factory): @classmethod def create(cls, **kwargs): object = super().create(**kwargs) db.session.add(object) db.session.flush() return o...
StarcoderdataPython
5156502
# $Id: gzip.py 23 2006-11-08 15:45:33Z dugsong $ """GNU zip.""" import struct, zlib import dpkt # RFC 1952 GZIP_MAGIC = '\x1f\x8b' # Compression methods GZIP_MSTORED = 0 GZIP_MCOMPRESS = 1 GZIP_MPACKED = 2 GZIP_MLZHED = 3 GZIP_MDEFLATE = 8 # Flags GZIP_FTEXT = 0x01 GZIP_FHCRC = 0x02 GZIP_FEXTRA = 0x04 GZIP_FNAME =...
StarcoderdataPython
1631417
<filename>srunner/metrics/examples/basic_metric.py #!/usr/bin/env python # Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ This module provide Ba...
StarcoderdataPython
12810607
<filename>tests/train/losses_tests.py import nose.tools import numpy as np import tensorflow as tf import micro_dl.train.losses as losses def test_mae_loss(): y_true = np.zeros((5, 10, 1), np.float32) y_true[:, :5, 0] = 2 y_pred = np.zeros_like(y_true) + 2. y_true = tf.convert_to_tensor(y_true, dtype...
StarcoderdataPython
1826203
<gh_stars>1-10 """ author: <NAME> time: 12/03/2016 link: https://github.com/un-knight/machine-learning-algorithm """ from func.tools import * from sklearn.metrics import classification_report import numpy as np def sigmoid(z): return 1 / (1 + np.exp(-z)) def main(): theta1, theta2 = read_weights_from_mat('e...
StarcoderdataPython
3485247
#!/usr/bin/env python # https://wiki.deepracing.io/Customise_Local_Training import json from collections import OrderedDict from .get import metadata_model, hyperparameters, metadata_stage, results_evaluation, results_training def retrieve_path(): from .get import path path_metadata_model = path.finder('mod...
StarcoderdataPython
1931299
import os import json import gzip import ftplib import string import random import datetime from common.params import Params from common.op_params import opParams op_params = opParams() uniqueID = op_params.get('uniqueID') def upload_data(): filepath = "/data/openpilot/selfdrive/data_collection/gps-data" if os.pat...
StarcoderdataPython
3380305
""" Simple toy example to see how map_coordinates works. """ import numpy as np from scipy.ndimage import interpolation as interp if __name__ == '__main__': in_data = np.array([[0., -1., -2.], [2., 1., 0.], [4., 3., 2.]]) # z = 2.*x - 1.*y # want the second arg...
StarcoderdataPython