id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3263105
from django.contrib import admin from .models import Course, Department, User, Student, ExamPaper, Material, Announcement, CourseAllotment,Bookmark, Feedback, Stat, Contributor admin.site.empty_value_display = '(None)' # Register your models here. class CourseAdmin(admin.ModelAdmin): list_display = ('name','dept','...
StarcoderdataPython
1610725
# -*- coding: utf-8 -*- #@+leo-ver=5-thin #@+node:ekr.20090502071837.3: * @file leoRst.py #@@first #@+<< docstring >> #@+node:ekr.20090502071837.4: ** << docstring >> """Support for restructured text (rST), adapted from rst3 plugin. For full documentation, see: http://leoeditor.com/rstplugin3.html To generate documen...
StarcoderdataPython
152497
from django.test import TestCase from django.core.urlresolvers import reverse class ViewsTestCase(TestCase): def test_about_view(self): response = self.client.get(reverse('about')) self.assertEqual(response.status_code, 200) self.assertContains(response, "About") def test_contact_page...
StarcoderdataPython
3238619
<reponame>avilash/TikTokApi import argparse from TikTokAPI import TikTokAPI from utils import read_json_from_file def getVideoById(video_id): api = TikTokAPI(read_json_from_file("cookie.json")) return api.getVideoById(video_id) def downloadVideoById(video_id): api = TikTokAPI(read_json_from_file("cookie...
StarcoderdataPython
1708101
import os from models.person import Person from models.room import LivingSpace, Office, Room from .base_db import (DBDoesNotExistException, OverWriteException, UpdateException, create_session, create_tables, load_engine) class Dojo(): """ models Dojo facillity ...
StarcoderdataPython
1624186
#!/usr/python # -*- coding: utf-8 -*- # from qpython import qconnection # from qpython import qcollection from binascii import hexlify import numpy from qpython import* # https://github.com/exxeleron/qPython # https://kx.com/documentation.php q = qconnection.QConnection(host='192.168.3.10', port=9001, ...
StarcoderdataPython
3377435
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Sun Aug 8 15:12:05 2021 @author: samuel """ import re import json import requests from bs4 import BeautifulSoup from tqdm import tqdm import difflib from pprint import pprint import time import os import shutil import pandas as pd ## importing custom files / module...
StarcoderdataPython
1732724
from itertools import chain from operator import itemgetter from collections import defaultdict import numpy as np from gym import spaces from coordination.environment.deployment import ServiceCoordination class NFVdeepCoordination(ServiceCoordination): COMPUTE_UNIT_COST = 0.2 MEMORY_UNIT_COST = 0.2 DATA...
StarcoderdataPython
18287
import requests from bs4 import BeautifulSoup import json def loadMasterStock(): url = "http://www.supremenewyork.com/mobile_stock.json" user = {"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0 Mobile/14D27 Safari/602.1"} # user = {"User-Ag...
StarcoderdataPython
3329281
<reponame>ZhiruiFeng/CarsMemory # -*- coding: utf-8 -*- import json import math import pandas as pd import flask import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import plotly.plotly as py from plotly import graph_objs as go import da...
StarcoderdataPython
1619410
# ----------------------------------------------------- THUMOS CONFIG ------------------------------------------------ #PATH THUMOS_CLASSIDX = '/ssd1/users/km/OTAL/THUMOS/meta/classidx.txt' # '/NAS2/CIPLAB/users/kyh/thumos/json/classidx.txt' THUMOS_ANNOTATION_PATH_TRAIN = '/ssd1/users/km/OTAL/THUMOS/meta/annotations_v...
StarcoderdataPython
1667783
<gh_stars>1-10 # encoding=utf8 __author__ = 'wcong' import web import util import config import pdbc urls = ( '/', 'Index' ) class Index(): def GET(self): return config.render.login() def POST(self): email = web.input().get("email") password = web.input().get("password") ...
StarcoderdataPython
1681007
<reponame>affjljoo3581/canrevan import json import os from canrevan.parsing import extract_article_urls, parse_article_content def _get_resource_content(name: str) -> str: res_path = os.path.join(os.path.dirname(__file__), "resources", name) with open(res_path, "r") as fp: return fp.read() def test...
StarcoderdataPython
3217154
from __future__ import print_function, division, absolute_import import itertools import numpy as np import regreg.atoms.group_lasso as GL import regreg.api as rr import nose.tools as nt from .test_seminorms import Solver, all_close, SolverFactory from .test_cones import ConeSolverFactory class GroupSolverFactor...
StarcoderdataPython
23207
#!/usr/local/bin/python # -*- coding: utf-8 -*- """ """ __author__ = 'joscha' __date__ = '03.08.12'
StarcoderdataPython
97950
<filename>modules/deprado.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import multiprocessing as mp import pandas as pd import numpy as np from tqdm import tqdm, tqdm_notebook import time import datetime as dt import sys def getDailyVolatility(close, span0=100): """ From <NAME> - Daily Volatility Da...
StarcoderdataPython
1644877
# Copyright 2008 Divmod, Inc. See LICENSE file for details # -*- test-case-name: xmantissa.test.test_webapp,xmantissa.test.test_publicweb,xmantissa.test.test_website -*- """ This unfortunate module exists to contain code that would create an ugly dependency loop if it were somewhere else. """ from zope.interface impor...
StarcoderdataPython
1786671
<reponame>patrick-finke/mecs<filename>mecs.py<gh_stars>1-10 """An implementation of the Entity Component System (ECS) paradigm.""" from itertools import repeat as _repeat __version__ = '1.2.1' class CommandBuffer(): """A buffer that stores commands and plays them back later. *New in version 1.1.* """ ...
StarcoderdataPython
3319849
# -*- coding: utf-8 -*- """ Created on Thu Sep 5 23:33:06 2019 @author: toothsmile,CQU @email: <EMAIL> """ import sys,getopt import os def mkdir(path): # 去除首位空格 path=path.strip() # 去除尾部 \ 符号 path=path.rstrip("\\") # 判断路径是否存在 # 存在 True # 不存在 False isExists=os.path.exists(path...
StarcoderdataPython
1727485
""" Django settings for demo_backend project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import ...
StarcoderdataPython
4826348
<reponame>alueschow/srupy """Utility classes and functions.""" import re from collections import defaultdict def get_namespace(element): """Return the namespace of an XML element. :param element: An XML element. """ return re.search('({.*})', element.tag).group(1) # https://stackoverflow.com/a/100...
StarcoderdataPython
99057
<reponame>HawxChen/barrelfishOS from arm_ds.debugger_v1 import Debugger from arm_ds.debugger_v1 import DebugException import os # The CPU driver is linked at this address LINKADDRESS = 0 debugger = Debugger() ec = debugger.getCurrentExecutionContext() es = ec.getExecutionService() # Run until the end of molly, to di...
StarcoderdataPython
3392794
# -*- coding: utf-8 -*- """API model for working with system configuration.""" import math from ..mixins import ChildMixins, Model class Meta(ChildMixins): """Child API model for working with instance metadata.""" def about(self) -> dict: """Get about page metadata. Returns: :ob...
StarcoderdataPython
1671876
from typing import Union, Dict, NamedTuple FormattingRule = Union[None, Dict, bool] FormattingResult = NamedTuple( "FormattingResult", [("text", str), ("dumping_config", dict), ("loading_config", dict)], )
StarcoderdataPython
4806996
<reponame>marsven/conan-center-index<gh_stars>1-10 from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration import os class FoxgloveWebSocketConan(ConanFile): name = "foxglove-websocket" url = "https://github.com/conan-io/conan-center-index" homepage = "https://github...
StarcoderdataPython
165281
from selenium import webdriver from selenium.webdriver.chrome.options import Options def get_driver(): opt = webdriver.ChromeOptions() opt.add_experimental_option("debuggerAddress", "localhost:8989") driver = webdriver.Chrome(executable_path="E:\\chromedriver\\chromedriver.exe", chrome_option...
StarcoderdataPython
3290
# 获取调课、改课通知例子 from zfnew import GetInfo, Login base_url = '学校教务系统的主页url' lgn = Login(base_url=base_url) lgn.login('账号', '密码') cookies = lgn.cookies # cookies获取方法 person = GetInfo(base_url=base_url, cookies=cookies) message = person.get_message() print(message)
StarcoderdataPython
1647428
import numpy as np from src.models.dnam.tabnet import TabNetModel import torch import lightgbm as lgb import pandas as pd import hydra from omegaconf import DictConfig from pytorch_lightning import ( LightningDataModule, seed_everything, ) from experiment.logging import log_hyperparameters from pytorch_lightnin...
StarcoderdataPython
119472
<gh_stars>1-10 # Generated by Django 3.1.5 on 2021-03-15 11:52 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('blogapp', '0007_post_likes'), ] operations = [ migrations.AddField( mo...
StarcoderdataPython
3395111
from django.urls import path from menus.views import SystemMenuView from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('system/', csrf_exempt(SystemMenuView.as_view())), ]
StarcoderdataPython
11394
<reponame>hadleyhzy34/reinforcement_learning<gh_stars>0 import numpy as np import gym from utils import * from agent import * from config import * def train(env, agent, num_episode, eps_init, eps_decay, eps_min, max_t): rewards_log = [] average_log = [] eps = eps_init for i in range(1, 1 + num_episode...
StarcoderdataPython
21066
import html import json import re from datetime import date from autoslug import AutoSlugField from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.validators import MinLengthValidator from django.db.models.aggregates import Count from django.db import models fr...
StarcoderdataPython
3258260
<reponame>datalexum/UNIX-time-from-NTP import calendar import subprocess from ntplib import NTPClient from datetime import datetime, timezone, timedelta from socket import gaierror def time_from_ntp(arguments): arguments ntp_client = NTPClient() try: response = ntp_client.request(arguments['serve...
StarcoderdataPython
1796454
import pandas as pd import numpy as np from typing import List import psycopg2 from psycopg2.extensions import register_adapter, AsIs import src.util import src.helpers # Setup system connection mode = "DEV" psycopg2.extensions.register_adapter(np.int64, AsIs) logger_wrapper = src.util.LoggerWrapper(algo_id=None) d...
StarcoderdataPython
100085
from slack_sdk.web.async_client import AsyncWebClient class AsyncUpdate: """`update()` utility to tell Slack the processing results of a `save` listener. async def save(ack, view, update): await ack() values = view["state"]["values"] task_name = values["task_name_inpu...
StarcoderdataPython
3276071
import os from functools import wraps from flask import request from swagger_server.response_code.cors_response import cors_401 def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if os.getenv('VOUCH_COOKIE_NAME') not in request.cookies: return cors_401(details='Log...
StarcoderdataPython
75098
""" Module with reading functionalities for calibration spectra. """ import os import configparser from typing import Optional, Dict, Tuple import h5py import spectres import numpy as np from typeguard import typechecked from scipy.optimize import curve_fit from species.analysis import photometry from species.core...
StarcoderdataPython
3274558
<reponame>GabrielAmare/TextEngine from typing import Iterator from item_engine import * from .mood_lexer import mood_lexer __all__ = ['gen_networks'] def gen_networks(mood_lexer_cfg: dict) -> Iterator[Network]: yield Network(function=mood_lexer, **mood_lexer_cfg)
StarcoderdataPython
37653
<gh_stars>0 import datetime import htmlgenerator from django.utils.translation import gettext as _ from .button import Button from .icon import Icon KIND_ICON_MAPPING = { "error": "error--filled", "info": "information--filled", "info-square": "information--square--filled", "success": "checkmark--fill...
StarcoderdataPython
3391674
<gh_stars>100-1000 # -*- coding: utf-8 -*- """ Basic ProcfileLexer Test ~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import pytest from pygments.token import Name, Punctuation, Text from pygments.lexers.procfile im...
StarcoderdataPython
3220897
# egrep.py # Here is a script that reads in lines of text and spits back out the ones that match a regular expression: import sys, re # sys.argv is the list of command-line arguments # sys.argv[0] is the name of the program itself # sys.argv[1] will be the regex specified at the command line regex = sys...
StarcoderdataPython
1694773
<gh_stars>1-10 import os import numpy as np import pickle import datetime import matplotlib.pyplot as plt from scipy.interpolate import interp1d from functools import partial from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import pyqtgraph as pg from supra.GUI.Tools.Theme import th...
StarcoderdataPython
3361218
<reponame>quentinLeDilavrec/semantic load( "@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", ) _all_example_repos = { "numpy": { "data": [ "**/*.py", ], "commit": "0<PASSWORD>", "repo": "numpy/numpy", "sha256": "8e60c567cbab3309afa9508ee61df...
StarcoderdataPython
1772096
<gh_stars>0 # -*- coding: utf-8 -*- import sys, os, requests try: sourceFileFullName = os.path.abspath(sys.argv[1]) sourceFileName = sourceFileFullName.replace("/","\\").split("\\")[-1] except: print("Missing input file") sys.exit() try: sourceFileType = sys.argv[2].lower() if sourceFileType !...
StarcoderdataPython
3254475
<reponame>ahcode0919/python-ds-algorithms def pangram(string: str) -> bool: alpha_set = set() for char in string: if char.isalpha(): alpha_set.add(char.lower()) return len(alpha_set) == 26
StarcoderdataPython
3316642
'''Implementation of the Gamma distribution.''' import torch from .baseprior import ExpFamilyPrior class GammaPrior(ExpFamilyPrior): '''Gamma distribution. parameters: a: shape b: rate natural parameters: eta1 = -b eta2 = a - 1 sufficient statistics: T_1(x) ...
StarcoderdataPython
1759503
import numpy as np from scipy.optimize import minimize from optimize_utils import * def _minimize_rhc(*args, **kwargs): # randomized hill-climbing options = kwargs["options"] method = options.pop("method") kwargs["method"] = method remaining = options["maxiter"] best_result = None while r...
StarcoderdataPython
3218612
<gh_stars>1-10 # -*- coding: utf-8 -*- """ flask.sessions ~~~~~~~~~~~~~~ Implements cookie based sessions based on itsdangerous. :copyright: (c) 2015 by <NAME>. :license: BSD, see LICENSE for more details. """ import uuid import hashlib from base64 import b64encode, b64decode from datetime import...
StarcoderdataPython
1718866
<gh_stars>1-10 from collections import namedtuple # Names of each of the buffers holding the runtime simulation state, which are passed to OpenCL kernels. # For more information on what these buffers represent see doc/model_design.md Buffers = namedtuple( "Buffers", [ "place_activities", "place...
StarcoderdataPython
55431
from abc import ABC, ABCMeta, abstractmethod class IDatastore(ABC): @abstractmethod def put(self, key: str, value: str): ''' Implement this function to insert data into database ''' @abstractmethod def get(self, key: str): ''' Implement this function to retrie...
StarcoderdataPython
13183
""" Generate coulomb matrices for molecules. See Montavon et al., _New Journal of Physics_ __15__ (2013) 095003. """ import numpy as np from typing import Any, List, Optional from deepchem.utils.typing import RDKitMol from deepchem.utils.data_utils import pad_array from deepchem.feat.base_classes import MolecularFeat...
StarcoderdataPython
87701
# import Criv pre-processing script import prep_file # -- Load parameters from user_param.txt param = prep_file.read_input_file() # -- Plot model geometry # output saved in CrivApp/output/model.png prep_file.build_model(param) # -- Calculate Xfar # output saved in CrivApp/output/plot_xfar.png prep_file.compute_Xfar(...
StarcoderdataPython
3213993
<filename>api_watchdog/hooks/result_group/abstract.py from abc import ABC, abstractmethod from api_watchdog.collect import WatchdogResultGroup class ResultGroupHook(ABC): """Abstract class for handling post run result group processing.""" @abstractmethod def __call__(self, result_group: WatchdogResultGr...
StarcoderdataPython
3357796
# Copyright (c) The InferLO authors. All rights reserved. # Licensed under the Apache License, Version 2.0 - see LICENSE. import numpy as np from inferlo import PairWiseFiniteModel from inferlo.pairwise.optimization.map_lp import map_lp from inferlo.testing import grid_potts_model, tree_potts_model, \ line_potts_m...
StarcoderdataPython
1759927
<reponame>investing-algorithms/investing-algorithm-framework<filename>investing_algorithm_framework/core/market_services/market_service.py<gh_stars>1-10 from abc import ABC, abstractmethod class MarketService(ABC): @abstractmethod def pair_exists(self, target_symbol: str, trading_symbol: str): pass ...
StarcoderdataPython
3395234
<reponame>lucianomc/casepro<filename>casepro/pods/base.py import json from confmodel import Config as ConfmodelConfig from confmodel import fields from django.apps import AppConfig class PodConfig(ConfmodelConfig): """ This is the config that all pods should use as the base for their own config. """ ...
StarcoderdataPython
117569
<filename>sigma_graph/envs/figure8/rewards/rewards_simple.py from math import ceil # default hyper-parameters for rewards DEFAULT_REWARDS = { "step": {"reward_step_on": True, "red_2_blue": 4, "blue_2_red": -3, "red_overlay": -2, }, "episode": { "reward_episode_on": True, "episode_decay_soft": Tru...
StarcoderdataPython
130136
<filename>torchsample/transforms/affine3d_transforms.py """ Affine transforms implemented on torch tensors, and requiring only one interpolation """ import math import random import torch as th from ..utils import th_affine3d, th_random_choice class RandomAffine3D(object): def __init__(self, ...
StarcoderdataPython
1736499
<filename>prod-1/6-reduce/datavisualization/plot_hamming.py import bmw import numpy as np import matplotlib.pyplot as plt problem = bmw.Problem.parse(filepath='../../../data/3-refined') dat1 = np.load('../../2-prod/test-0.npz') constellation1 = dat1['constellation'] constellation_type_indices1 = dat1['constellation...
StarcoderdataPython
4809802
<filename>model/1_prepare_data_and_inference.py<gh_stars>0 ''' MIT License Copyright (c) 2020 <NAME> 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 without limitat...
StarcoderdataPython
25749
from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GOval, GRect from campy.gui.events.mouse import onmouseclicked import random WINDOW_WIDTH = 600 WINDOW_HEIGHT = 400 ZONE_WIDTH = 100 ZONE_HEIGHT = 100 BALL_RADIUS = 15 MAX_SPEED = 6 MIN_Y_SPEED = 2 class ZoneGraphics: def __init__(se...
StarcoderdataPython
1799524
<filename>base/views/herosec_views.py from rest_framework.decorators import api_view from rest_framework.response import Response from base.models import HeroSectionImage from base.serializers import HeroSerializer @api_view(['GET']) def get_all_heroSec(request): products = HeroSectionImage.objects.all() ser...
StarcoderdataPython
3262352
#!/home/ash/anaconda3/envs/pytorch/bin/python import numpy as np import torch import torch.nn as nn from torchsummary import summary from torch.autograd import Variable import torch.nn.functional as F from layers import conv1x1 class CRPBlock(nn.Module): def __init__(self, in_planes, out_planes, n_stages): ...
StarcoderdataPython
29211
<reponame>congvmit/mipkit<filename>mipkit/faces/helpers.py<gh_stars>1-10 """ The MIT License (MIT) Copyright (c) 2021 <NAME> 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 restricti...
StarcoderdataPython
1768328
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
StarcoderdataPython
3365092
######################################################################################## ### Closing and Opening import cv2 import numpy as np # Reading image from its path img = cv2.imread(".\\chest_xray\\chest_xray\\train\\NORMAL\\NORMAL-28501-0001.jpeg") # img = cv2.imread(".\\chest_xray\\chest_xray\\train\\PNEUMON...
StarcoderdataPython
3340336
# -*- coding: utf-8 -*- """ demeter name:tcp.py author:rabin """ import socket import time from demeter.core import * from demeter.mqtt import * from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop from tornado import stack_context from tornado.escape import native_str class Connection(ob...
StarcoderdataPython
1709175
<filename>src/tf/load_data.py ''' Data pre process for AFM and FM @author: <NAME> (<EMAIL>) <NAME> (<EMAIL>) ''' import numpy as np import os import pandas as pd from scipy.sparse import csr_matrix from sklearn.feature_extraction import DictVectorizer class LoadData(object): '''given the path of data, return the...
StarcoderdataPython
1715818
""" AVM Fritz!BOX SmartHome Client ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dokumentation zum Login-Verfahren: http://www.avm.de/de/Extern/files/session_id/AVM_Technical_Note_-_Session_ID.pdf Smart Home Interface: http://www.avm.de/de/Extern/files/session_id/AHA-HTTP-Interface.pdf """ from __future__ i...
StarcoderdataPython
4827256
<gh_stars>0 # terrascript/resource/github.py import terrascript class github_branch_protection(terrascript.Resource): pass class github_issue_label(terrascript.Resource): pass class github_membership(terrascript.Resource): pass class github_organization_block(terrascript.Resource): pass class...
StarcoderdataPython
3354405
import os import sys import urllib import time import logging import json import shutil import gc import pytest import mock def pytest_addoption(parser): parser.addoption("--slow", action='store_true', default=False, help="Also run slow tests") # Config if sys.platform == "win32": PHANTOMJS_PATH = "tools/ph...
StarcoderdataPython
3210765
#!/usr/bin/env python3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # # device registry - layer for common used functions # """IoT DR: device registry functions. Will be deployed as Lambda layer.""" import logging import sys import time import boto3 log...
StarcoderdataPython
1628498
''' It is an example script that makes sum of two numbers separated by space in the input stream... ''' a, b = [int(num) for num in input().split()] print('Sum:', a + b)
StarcoderdataPython
74311
<gh_stars>1-10 # Generated by Django 2.2.10 on 2020-02-12 16:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0007_auto_20200206_0844'), ] operations = [ migrations.RenameField( model_name='historicalmessageaudit', ...
StarcoderdataPython
43094
<filename>fedlearner/scheduler/scheduler_service.py<gh_stars>1-10 # Copyright 2020 The FedLearner 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://...
StarcoderdataPython
1765532
<filename>src/printable.py #! /usr/bin/env python3 # printable.py - print a table of printable ASCII characters in base 2, 8, 10, and 16 for i in range(32, 127): print(f"{i:07b} | {i:03o} | {i:03d} | {i:2x} | {chr(i):1s}")
StarcoderdataPython
1768779
import http import logging import sys import time from collections import abc from copy import copy from os import getpid import click TRACE_LOG_LEVEL = 5 class ColourizedFormatter(logging.Formatter): """ A custom log formatter class that: * Outputs the LOG_LEVEL with an appropriate color. * If a l...
StarcoderdataPython
9735
<reponame>adidas/m3d-api<filename>test/core/s3_table_test_base.py import os from test.core.emr_system_unit_test_base import EMRSystemUnitTestBase from test.core.tconx_helper import TconxHelper class S3TableTestBase(EMRSystemUnitTestBase): default_tconx = \ "test/resources/s3_table_test_base/tconx-bdp-em...
StarcoderdataPython
1700312
<gh_stars>0 from pathlib import Path from fhir.resources.codesystem import CodeSystem from oops_fhir.utils import CodeSystemConcept __all__ = ["DeviceMetricColor"] _resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json")) class DeviceMetricColor: """ DeviceMetricColor Describes the typi...
StarcoderdataPython
4809976
<filename>seaice/images/test/util.py from datetime import date from functools import wraps from unittest.mock import patch class mock_today(object): def __init__(self, year, month, day, module, datetime='dt'): """Fix the value of datetime.date.today() to easily test functionality that depends on t...
StarcoderdataPython
137503
<gh_stars>1-10 import argparse import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.decomposition import PCA from sklearn.metrics import accuracy_score, f1_score from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.cluster import KMeans from pr...
StarcoderdataPython
4824001
#!/usr/bin/python # # Copyright (c) 2019 Hewlett Packard Enterprise Development LP # # 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
1669533
import numpy import matplotlib.pyplot as plt def fig4plot(): #setup plots fig = plt.figure(figsize=(10.0, 7.5)) fig.subplots_adjust(left=0.1, right=0.9, wspace=0.3) ax1 = fig.add_subplot(221) ax1.set_yscale('log') ax1.set_ylabel('|m|') ax1.set_ylim(5.e-5, 1.e-2) ax1.set_xlabel('n$_{\mat...
StarcoderdataPython
1624254
import numpy as np import random from boxenv import * from agent import * NB_SKILLS = 6 COND = 'OUR' STATE_DIM = 2 DIM = STATE_DIM policy_function = GaussianPolicyFunction(STATE_DIM + NB_SKILLS, 2) policy = GaussianPolicy() d = SkillDiscriminator(DIM, NB_SKILLS) # initial training task list # TASKS = [(0.5, 0.8), (...
StarcoderdataPython
3324494
import time import socket import sys import os import pygame import threading from pongClient import Paddle, Ball, WIDTH, HEIGHT, UP, DOWN from constants import LEFT_PADDLE_ID, RIGHT_PADDLE_ID, DEFAULT_PORT, PADDLE_HEIGHT, PADDLE_WIDTH, FPS, SYMMETRIC, ASYMMETRIC , SERVER_NAME import logging from MyCrypt import * loggi...
StarcoderdataPython
111274
<gh_stars>1-10 #!/usr/bin/python # Copyright (c) 2013 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Tools for parsing ELF headers. from driver_log import DriverOpen, DriverClose, Log, FixArch class ELFHeader(obj...
StarcoderdataPython
1764529
<gh_stars>0 #!/usr/local/bin/python2.7 import sys import os try: if basePythonCodePath is not None: pass except NameError: basePythonCodePath = os.curdir sys.path.append(basePythonCodePath) from mi.logging import config config.add_configuration(os.path.join(basePythonCodePath, 'res', 'config', 'mi-l...
StarcoderdataPython
1653881
<filename>message_media_webhooks/models/update_webhook_request.py # -*- coding: utf-8 -*- """ message_media_webhooks.models.update_webhook_request This file was automatically generated for MessageMedia by APIMATIC v2.0 ( https://apimatic.io ) """ class UpdateWebhookRequest(object): """Implem...
StarcoderdataPython
3217093
<reponame>rupeshshrestha123/end2end-asr-pytorch<filename>utils/lm_functions.py import torch import os import math import torch.nn as nn from models.lm.transformer_lm import TransformerLM from utils.optimizer import NoamOpt from utils import constant # def save_model(model, epoch, opt, metrics, label2id, id2label, be...
StarcoderdataPython
3210620
<reponame>FHPythonUtils/Blackt """Provides the wrapper methods to black. Requires black to be on the system path""" from __future__ import annotations import argparse import os import re import subprocess import sys from argparse import ArgumentParser from pathlib import Path THISDIR = Path(__file__).resolve().paren...
StarcoderdataPython
3232713
<reponame>Sundaybrian/hood-watch<gh_stars>0 from django.contrib import admin from .models import * # Register your models here. class NeighbourhoodAdmin(admin.ModelAdmin): filter_horizontal=('locations',) admin.site.register(Post) admin.site.register(Business) admin.site.register(Occupant) admin.site.register(Ne...
StarcoderdataPython
1675762
<reponame>MihaiBalint/sanic-restplus # -*- coding: utf-8 -*- from __future__ import unicode_literals import re import pytz import pytest from datetime import date, datetime from six import text_type from sanic_restplus import inputs class Iso8601DateTest(object): @pytest.mark.parametrize('value,expected', [ ...
StarcoderdataPython
4805615
<gh_stars>1-10 from ... import weather as rk_weather from ... import util as rk_util from .wind_workflow_manager import WindWorkflowManager import numpy as np def onshore_wind_merra_ryberg2019_europe(placements, merra_path, gwa_50m_path, clc2012_path, output_netcdf_path=None, output_variables=None): # TODO: Add ra...
StarcoderdataPython
9370
<reponame>opencv/openvino_training_extensions<filename>external/model-preparation-algorithm/tests/conftest.py # Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # try: import e2e.fixtures from e2e.conftest_utils import * # noqa from e2e.conftest_utils import pytest_addopt...
StarcoderdataPython
3399716
<filename>search.py<gh_stars>10-100 """ This file contains an example search engine that will search the inverted index that we build as part of our assignments in units 3 and 5. """ import sys,os,re import math import sqlite3 import time # use simple dictionary data structures in Python to maintain lists with hash ke...
StarcoderdataPython
112884
<reponame>Anari-AI/pygears-vivado<filename>tests/ipgen/test_add.py from pygears.lib import add from pygears_vivado.test_utils import ipgen_test from pygears import Intf from pygears.typing import Tuple, Uint @ipgen_test(top='/add', intf={'din': 'axi', 'dout': 'axi'}) def test_basic(tmpdir): add(Intf(Tuple[Uint[16...
StarcoderdataPython
1648970
#!/usr/bin/env python # Copyright 2020 <NAME>, <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 ...
StarcoderdataPython
1712079
#!/usr/bin/python3 from secret import * import sys import requests if(len(sys.argv) != 2): print("error") quit() files = {'file': open(sys.argv[1], 'rb')} param = {'token':token, 'channels':channel} res = requests.post(url="https://slack.com/api/files.upload",params=param, files=files)
StarcoderdataPython
3249607
import PyPDF2 pdfReader = PyPDF2.PdfFileReader(open('encrypted.pdf', 'rb')) print(pdfReader.isEncrypted) pdfReader.decrypt('rosebud') page = pdfReader.getPage(0) print(page)
StarcoderdataPython
1733399
<reponame>Leofltt/rg_sound_generation<gh_stars>0 from typing import Dict # "base_dir": "D:\soundofai\\pitch_shifted_all", def get_config() -> Dict: conf = { "base_dir": "D:\soundofai\\pitch_shifted_all", "csv_file_path": "D:\soundofai\\annot_data\\data\\may_13.csv", "preprocess_dir": "tmp"...
StarcoderdataPython