id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
1887619
import json from django.http import HttpResponse from django.conf import settings def render_json(data, code=200): """ 自定义render函数, code默认值为200, 返回正常 """ result = { 'data': data, 'code': code, } # 开发为了显示清晰使用 if settings.DEBUG: json_str = json.dumps( res...
StarcoderdataPython
3575729
<gh_stars>1-10 # 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 in...
StarcoderdataPython
11218347
from __future__ import absolute_import from __future__ import unicode_literals import time from functools import wraps from celery.task import periodic_task from corehq.util.datadog import statsd, datadog_logger from corehq.util.decorators import ContextDecorator from corehq.util.soft_assert import soft_assert from c...
StarcoderdataPython
58976
""" qoc - a directory for the main package """ from .core import (evolve_lindblad_discrete, grape_lindblad_discrete, evolve_schroedinger_discrete, grape_schroedinger_discrete,) __all__ = [ "evolve_lindblad_discrete", "grape_lindblad_discrete", "evo...
StarcoderdataPython
6699306
<gh_stars>100-1000 import logging import datetime from directory_utilities import validate_or_make_directory date = "{:%Y-%m-%d}".format(datetime.datetime.now()) log_file_string = "../logs/{}.log".format(date) validate_or_make_directory(log_file_string) logging.basicConfig(filename=log_file_string, level=logging.WA...
StarcoderdataPython
8121340
<gh_stars>0 from socket import socket,AF_INET,SOCK_DGRAM import sys, random, traceback from datetime import datetime from threading import Thread from time import sleep MY_PORT = int(sys.argv[1]) ALICE_IP = sys.argv[2] ALICE_PORT = int(sys.argv[3]) ALICE_ADDR = (ALICE_IP, ALICE_PORT) MODE = int(sys.argv[4]) s = sock...
StarcoderdataPython
6699642
import os import igem_wikisync as sync sync.run( team = os.environ.get('WIKISYNC_TEAM'), src_dir = os.environ.get('WIKISYNC_SOURCE'), build_dir = os.environ.get('WIKISYNC_BUILD'), poster_mode = os.environ.get('WIKISYNC_POSTER') )
StarcoderdataPython
1902150
<reponame>254Davidhashisoma/blog import unittest from app.models import Post, User, Comment class TestPost(unittest.TestCase): def setUp(self): self.user_Collins = User(first_name = "David", last_name = "Hashisoma", username = "@Hashi", ...
StarcoderdataPython
1900237
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-12-12 00:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0024_auto_20171210_1808'), ] operations = [ migrations.Alte...
StarcoderdataPython
4821954
n, m = input().split() arr = list(input().split()) A = set(input().split()) B = set(input().split()) def happiness(array, happy_set, unhappy_set): h = 0 for num in array: if happy_set.__contains__(num): h += 1 elif unhappy_set.__contains__(num): h -= 1 return h pr...
StarcoderdataPython
5025015
<filename>ex0020.py<gh_stars>0 '''import random aluno1 = input("nome do primeiro aluno ") aluno2 = input("nome do aluno dois ") aluno3 = input("nome do terceiro aluno ") aluno4 = input("nome do quarto aluno") ''' # salve rosendo que ta vendo os exerciocios, você não conseguiu entender a parte do [0,0,0,0] import random...
StarcoderdataPython
1925047
import h5py import matplotlib.pyplot as plt import numpy as np import os import os.path import tensorflow as tf from keras.backend import floatx from keras.layers import Conv1D, Conv2D, Dense from keras.layers.core import Flatten, Reshape from keras.models import load_model, Sequential from keras import optimizers fr...
StarcoderdataPython
1601949
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 22 11:24:01 2021 @author: ja17375 """ import pygmt import numpy as np import pandas as pd import xarray as xr import netCDF4 as nc def plot_forte_gmt(): tx2008 = np.loadtxt('/Users/ja17375/SWSTomo/ForteModels/Flow_Models/TX2008/forteV2_1deg_15...
StarcoderdataPython
9711170
import os.path DATA_DIR = './data' TRAIN_DIR = os.path.join(DATA_DIR, 'train_hq') TRAIN_MASK_DIR = os.path.join(DATA_DIR, 'train_masks') TEST_DIR = os.path.join(DATA_DIR, 'test_hq') TRAIN_IMAGESET_PATH = os.path.join(DATA_DIR, 'train.csv') VAL_IMAGESET_PATH = os.path.join(DATA_DIR, 'val.csv') OUTPUT_DIR = './outp...
StarcoderdataPython
5060895
__author__ = 'Matt' import math import cmath from UI.network.DataTransferProtocol import sendData import UI.WheelComputation as WheelComputation from MathHelpers import * import numpy class DriveControl: def __init__(self, x, y, size, data, data_client): self.x = x self.y = y self.size =...
StarcoderdataPython
4858143
<gh_stars>10-100 """Test groupfinder.""" import pytest from pyramid_fullauth.auth import groupfinder @pytest.mark.parametrize( ["is_admin", "is_active", "groups"], [ (True, True, ["s:superadmin", "s:user"]), (True, False, ["s:superadmin", "s:inactive"]), (False, True, ["s:user"]), ...
StarcoderdataPython
3508329
<filename>Yandex_contest_HW/YC_HW2/task_2F.py from _collections import deque """n, k = int(input()), int(input()) p = list(map(str, input().split())) p_deque = deque(p) cnt = 0 for i in range(0, n): while cnt != k: if p_deque[i] < p_deque[i + 1]: p_deque.append(p[i]) p_deque.pople...
StarcoderdataPython
6681007
<reponame>rjt-gupta/USHUAIA from django.contrib import admin from django.urls import path from django.conf.urls import url from music.views import album_detail, song_detail, artist_detail, playlist_detail, create_artist, create_album, create_song, add_to_playlist, delete_song from music.views import delete_song_playlis...
StarcoderdataPython
3230391
<filename>examiner/exam_test_case.py """ Overriding TestCase for exam tool. """ import re import unittest import importlib from examiner.exceptions import TestFuncNameError, TestClassNameError import examiner.helper_functions as hf class ExamTestCase(unittest.TestCase): """ Override methods to help customize o...
StarcoderdataPython
4966611
<filename>resumos/cursos/cs50/all-challenges/labs/birthdays/application.py import os from cs50 import SQL from flask import Flask, flash, jsonify, redirect, render_template, request, session # Configure application app = Flask(__name__) # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True ...
StarcoderdataPython
6518459
from unittest import TestCase, mock from usecase.extract_datasets_infos_from_database import ( extract_gtfs_datasets_infos_from_database, extract_gbfs_datasets_infos_from_database, extract_previous_sha1_hashes, extract_source_infos, ) from utilities.constants import ( CLAIMS, MAINSNAK, DATA...
StarcoderdataPython
3430831
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'qt/configuredialog.ui' # # Created: Thu Jun 25 09:17:51 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_ConfigureDialog(object): ...
StarcoderdataPython
11268625
# -*- coding: utf-8 -*- """Tests for sandwich robust covariance estimation see also in regression for cov_hac compared to Gretl and sandbox.panel test_random_panel for comparing cov_cluster, cov_hac_panel and cov_white Created on Sat Dec 17 08:39:16 2011 Author: <NAME> """ import numpy as np from numpy.testing impor...
StarcoderdataPython
1994144
# -*- coding: utf-8 -*- """ 1947. Maximum Compatibility Score Sum https://leetcode.com/problems/maximum-compatibility-score-sum/ Example 1: Input: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]] Output: 8 Explanation: We assign students to mentors in the following way: - student 0 to mentor...
StarcoderdataPython
12808182
<reponame>moocowmoo/paywall #!/usr/bin/python3 import cgi import cgitb import datetime import json import os import re import requests import subprocess import sys import time from bmdjson import check_address print("Content-Type: text/plain\n") print("testing keybase") print() print("PASS:") signature = "BEGIN KE...
StarcoderdataPython
3257737
<gh_stars>10-100 # coding: utf-8 """ Automated Tool for Optimized Modelling (ATOM) Author: Mavs Description: Unit tests for training.py """ # Standard packages import pytest # Own modules from atom.training import ( DirectClassifier, DirectRegressor, SuccessiveHalvingClassifier, SuccessiveHalvingReg...
StarcoderdataPython
4999720
<filename>voicemd/models/long_filter_cnn.py import logging import torch import torch.nn as nn import torch.nn.functional as F # from voicemd.utils.hp_utils import check_and_log_hp logger = logging.getLogger(__name__) class LongFilterCNN(nn.Module): def __init__(self, hyper_params): super(LongFilterCNN...
StarcoderdataPython
6456651
<reponame>akx/upcloud-python-api from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from upcloud_api import Tag def create_cluster(manager, cluster): """Create all servers in cluster.""" for server in cluster: ...
StarcoderdataPython
6542274
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@class='s_product_center']/div[@class='s_hot_right']/div[@class='s_hot_name']/font", 'price' : "//div[@class='Detail_Right']/ul/...
StarcoderdataPython
3468579
<filename>B2G/gecko/testing/marionette/update-smoketests/smoketest.py # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import json import os import subprocess import sys...
StarcoderdataPython
12827721
import sys import os sys.path.append('../') current_dir = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.normpath(os.path.join( current_dir, '../data/', 'optstoic_db_v3'))
StarcoderdataPython
8098143
<filename>torchtime/models/inception.py import math from typing import List, Optional, Any import torch from torch import nn, jit, Tensor activations = { 'relu': nn.ReLU, 'elu': nn.ELU, 'leaky_relu': nn.LeakyReLU, 'sigmoid': nn.Sigmoid, 'tanh': nn.Tanh, 'linear': nn.Identity } class BasicCon...
StarcoderdataPython
1634070
"""Class definitions for adapting acoustic models""" from __future__ import annotations import os import shutil from typing import TYPE_CHECKING, Optional from ..exceptions import KaldiProcessingError from ..models import AcousticModel from ..multiprocessing import ( align, calc_fmllr, compile_information...
StarcoderdataPython
45360
""" Python module. """
StarcoderdataPython
1698315
<reponame>tilan7663/lucene-pyparser import json from .file_reader import FileReader from .utils import * class NormMeta(FileReader): extension = ".nvm" def __init__(self, segment_info, field_infos): super(NormMeta, self).__init__(segment_info) self.f = self.get_file_ptr() self.field_infos = field_infos de...
StarcoderdataPython
5192972
from .Circle import Circle from .Collision import Collision from .CollisionList import CollisionList from .Line import Line from .Object import Object from .System import System from .functions import *
StarcoderdataPython
1676162
#!/usr/bin/env python3 SINGLE_INDENT = 4 * ' ' GRAPH = '''\ {typ} {name} {{ {config} {nodes} {subgraphs} {edges} }}''' SUBGRAPH = ''' {indent}subgraph {name} {{ {config} {nodes} {subgraphs} {edges} {indent}}}''' NODE = ''' {indent}node [{config}] {indent}{name} [label="{label}"]''' EDGE = ''' {indent}edge [{config...
StarcoderdataPython
4813536
import json from storyhub.sdk.service.Argument import Argument from storyhub.sdk.service.HttpOptions import HttpOptions from storyhub.sdk.service.output.OutputAction import OutputAction from tests.storyhub.sdk.JsonFixtureHelper import JsonFixtureHelper output_action_fixture = JsonFixtureHelper.load_fixture("output_ac...
StarcoderdataPython
8189777
<reponame>TransRadOnc-HIT/RADIANTS from nipype.interfaces.base import ( BaseInterface, TraitedSpec, Directory, File, traits, BaseInterfaceInputSpec, InputMultiPath) from radiomics import featureextractor import csv import os.path as op class FeatureExtractionInputSpec(BaseInterfaceInputSpec): paramet...
StarcoderdataPython
200952
<filename>solutions/lowest_common_ancestor_deepest_leaves/solution.py from collections import deque from ..utils import TreeNode def lcaDeepestLeaves(root: TreeNode) -> TreeNode: """Given the 'root' of a binary tree, return the lowest common ancestor of its deepest leaves.""" if not root.left and not roo...
StarcoderdataPython
3407106
from bluebottle.fsm.effects import TransitionEffect from bluebottle.fsm.triggers import ModelChangedTrigger from bluebottle.funding.effects import UpdateFundingAmountsEffect from bluebottle.funding.models import Funding, PlainPayoutAccount, Donation from bluebottle.funding.states import FundingStateMachine, PlainPayout...
StarcoderdataPython
6573405
<gh_stars>1-10 files = ["0-500k", "500k-1M", "1M-1.5M", "1.5M-2M", "2M-2-5M", "2.5M-3M", "3M-3-5M", "3.5M-4M", "4M-4-5M", "4.5M-5M","5M-5-5M", "5.5M-6M", "6M-6-5M", "6.5M-7M", "7M-7-5M"] for i in range(len(files)): filedata = None print("lendo {}".format(files[i])) with open('paris_' + fi...
StarcoderdataPython
1778643
print("*********** BOOLEAN OPERATORS EXAMPLES ************") """ and *************************** TRUE and TRUE -> TRUE TRUE and FALSE -> FALSE FALSE and FALSE -> FALSE *************************** or *************************** TRUE or TRUE -> TRUE TRUE or FALSE -> TRUE FALSE or FALSE -> FALSE ************************...
StarcoderdataPython
8110762
<reponame>mcflugen/rafem #! /usr/bin/env python from setuptools import find_packages, setup import versioneer setup( name="rafem", version=versioneer.get_version(), author="<NAME>", author_email="<EMAIL>", description="River Avulsion Flooplain Evolution Model", long_description=open("README.r...
StarcoderdataPython
6501982
<reponame>schmouk/ArcheryVideoTraining<filename>src/Utils/periodical_thread.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ 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...
StarcoderdataPython
1841299
<filename>quadratic_mc.py import os, sys import glob import platform import math import numpy as np import torch from cffi import FFI class QuadraticMarchingCubes: def __init__(self): self.ffi = FFI() with open("Src/exported_routines.h") as header: header_str = header.read() cstr = "" igno...
StarcoderdataPython
3249038
from lightweaver.fal import Falc82 from lightweaver.rh_atoms import H_6_atom, H_6_CRD_atom, H_3_atom, C_atom, O_atom, OI_ord_atom, Si_atom, Al_atom, CaII_atom, Fe_atom, FeI_atom, He_9_atom, He_atom, He_large_atom, MgII_atom, N_atom, Na_atom, S_atom import lightweaver as lw import numpy as np import scipy.interpolate as...
StarcoderdataPython
1808821
from setuptools import setup, find_packages version = '0.1' setup( name='ckanext-ldap', version=version, description="CKAN plugin to provide LDAP authentication", url='https://github.com/NaturalHistoryMuseum/ckanext-ldap', packages=find_packages(), namespace_packages=['ckanext', 'ckanext.ldap'], entry_point...
StarcoderdataPython
8181639
<reponame>rikeshi/galaxy from galaxy.jobs import runners def test_default_specs(): # recheck_missing_job_retries is integer >= 0 params = runners.RunnerParams(specs=runners.BaseJobRunner.DEFAULT_SPECS, params=dict(recheck_missing_job_retries="1")) assert params.recheck_missing_job_retries == 1 assert ...
StarcoderdataPython
12852447
<reponame>ranigb/Set-Tree<filename>exps/jets/top_quark_gbdt.py import os import numpy as np import argparse import logging import random import pickle from pprint import pformat from exps.data import ParticleNetDataset from settree.set_data import SetDataset, OPERATIONS, merge_init_datasets import exps.eval_utils as e...
StarcoderdataPython
1710472
def array_max_consecutive_sum_short(a, k): c = m = sum(a[:k]) for i in range(len(a) - k): c = c + a[i + k] - a[i] m = max(c, m) return m def array_max_consecutive_sum(a, k): # works, but has O(n^2) time which is undesirable result_array = [] for i in range(len(a) - (k-1)): ...
StarcoderdataPython
1922366
<filename>model_zoo/research/hpc/ocean_model/src/oa_operator.py # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/license...
StarcoderdataPython
12833047
import torch def accuracy(logits, y): return torch.mean((torch.argmax(logits, dim=-1) == y).float()) def loss(logits, y): return torch.nn.functional.cross_entropy(logits, y) def print_metrics(metrics): for metric, value in metrics.items(): print(f"{metric}: {value}")
StarcoderdataPython
20112
<gh_stars>0 # coding=utf-8 from __future__ import unicode_literals from tornado.testing import AsyncTestCase from apps.core.models import (ModelBase, _get_master_engine, _get_slave_engine) from tornado.options import options from apps.core.urlutils import urlp...
StarcoderdataPython
3491630
from flask_jsonvalidator import ( JSONValidator, StringValidator ) class ReplyValidator(JSONValidator): validators = { "content" : StringValidator(nullable=False), "report_public_id" : StringValidator(nullable=False), } class ReplyEditValidator(JSONValidator): valid...
StarcoderdataPython
11396970
<reponame>kyper999/SmartHome-Demo2 # -*- coding: utf-8 -*- """ Base task class """ from celery.utils.log import get_task_logger class BaseTask(object): """ Base class for Celery task """ Error = None Desc = "Base task Object" def run(self): pass @property de...
StarcoderdataPython
4855706
## @package presence.py # Used to check whether a user is online from flask import request, jsonify, Response, session, redirect, make_response from flask.views import MethodView from sqlalchemy import and_, or_ from backend import db, app from backend.database.models import Presence, User import gevent, json prese...
StarcoderdataPython
6415620
<reponame>CityPulse/CP_Resourcemanagement<gh_stars>1-10 import threading import Queue from time import sleep from virtualisation.misc.log import Log as L __author__ = '<NAME> (<EMAIL>)' class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for ...
StarcoderdataPython
6671656
<reponame>igormilovanovic/python-data-viz-cookbook<gh_stars>10-100 import numpy import matplotlib.pyplot as plt def _get_mask(t, t1, t2, lvl_pos, lvl_neg): if t1 >= t2: raise ValueError("t1 must be less than t2") return numpy.where(numpy.logical_and(t > t1, t < t2), lvl_pos, lvl_neg) def generate_...
StarcoderdataPython
9789147
<reponame>ketgo/quantum-computing from .circuit import QuantumCircuit from .functions import Hybrid, HybridFunction
StarcoderdataPython
4946814
from a10sdk.common.A10BaseClass import A10BaseClass class List(A10BaseClass): """This class does not support CRUD Operations please use parent. :param a1: {"minimum": 1, "type": "number", "maximum": 10, "format": "number"} :param a2: {"minLength": 1, "maxLength": 32, "type": "string", "description":...
StarcoderdataPython
1682972
<filename>starter_code/migrations/versions/c0de0819f9f0_.py """empty message Revision ID: c0de0819f9f0 Revises: c3880377ac48 Create Date: 2020-02-04 15:45:02.049082 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'c0de0819f9f0' down_revision = 'c3880377ac48' br...
StarcoderdataPython
154991
from django.shortcuts import render, get_object_or_404 from rest_framework import status from django.http import HttpResponse, JsonResponse # importing the models from .models import CarBrands, Employees, EmployeeDesignations, Snippet, Persons, PersonTasks # importing a APIView class based views from rest_framwork from...
StarcoderdataPython
325879
<reponame>sabidib/hikari # -*- coding: utf-8 -*- # Copyright (c) 2020 Nekokatt # Copyright (c) 2021 davfsa # # 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 wit...
StarcoderdataPython
11200999
# load general packages and functions # (none) # load program-specific functions from parameters.constants import constants as C import gnn.mpnn import util # defines the models with parameters from `constants.py` def initialize_model(): """ Initializes the model to be trained. Possible model: "GGNN". Retu...
StarcoderdataPython
11218012
import os import sys import logging.config import yaml import requests import time from datetime import datetime #--------------------importing process configs and setting logger--------------------- sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import properties.config as config wit...
StarcoderdataPython
294015
#!/usr/bin/env python """ lib.py General ROMS utils Written by <NAME> on 05/24/13 Copyright (c)2010--2021 University of Hawaii under the MIT-License. """ import numpy as np import seapy from seapy.lib import default_epoch, secs2day import netCDF4 from warnings import warn fields = {"zeta": {"grid": "rho", "...
StarcoderdataPython
6560469
# Copyright (c) 2009-2012 testtools developers. See LICENSE for details. """Content - a MIME-like Content object.""" __all__ = [ 'attach_file', 'Content', 'content_from_file', 'content_from_stream', 'json_content', 'text_content', 'TracebackContent', ] import codecs import inspect imp...
StarcoderdataPython
4845797
# Generated by Django 3.2.4 on 2021-08-15 08:21 from django.db import migrations, models import src.users.services.image_services class Migration(migrations.Migration): dependencies = [ ("users", "0021_alter_contact_user"), ] operations = [ migrations.RemoveField( model_name...
StarcoderdataPython
105689
<filename>demo/sensors/button.py<gh_stars>10-100 # spikedev libraries from spikedev.button import ButtonLeft from spikedev.logging import log_msg log_msg("start") btn = ButtonLeft() btn.wait_for_pressed(5000) log_msg("finish")
StarcoderdataPython
8182611
import argparse import logging import os import sys import appdirs import hangups.auth from slackups.server import Server def runit(): logging.basicConfig(level=logging.INFO, stream=sys.stdout) logging.getLogger('hangups').setLevel(logging.WARNING) dirs = appdirs.AppDirs('hangups', 'hangups') default...
StarcoderdataPython
8138574
<reponame>scottwedge/OpenStack-Stein # Copyright (c) 2015 VMware, 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...
StarcoderdataPython
4809597
<filename>cpu_cores/common.py # This file is part of cpu_cores released under the MIT license. # See the LICENSE file for more information. import sys class CPUCoresCounter(object): platform = None _physical_cores_count = None _physical_processors_count = None def _count(self, *args, **kwargs): ...
StarcoderdataPython
9772230
""" Image Match 의 ImageSignature 모듈로 이미지 시그니쳐 벡터를 추출하는 모듈입니다. """ import os import numpy as np from image_match.goldberg import ImageSignature from tqdm import tqdm from config import * def extract_signature(): img_paths = os.listdir(IMG_DIR) img_paths.sort() img_paths = [os.path.join(IMG_DIR...
StarcoderdataPython
374312
import xml.etree.ElementTree as ET import re import os ######################################################## # this is meant to be run from the docs folder # if running manually, cd docs first ######################################################## tasknames = os.listdir('../xml/tasks') # loop through each task ...
StarcoderdataPython
8047908
class MedianFinder: def __init__(self): self.min_heap: List[int] = [] self.max_heap: List[int] = [] def addNum(self, num: int) -> None: heappush(self.max_heap, -heappushpop(self.min_heap, num)) if len(self.max_heap) > len(self.min_heap): heappush(self.min_h...
StarcoderdataPython
1707408
<filename>qiling/qiling/extensions/coverage/formats/base.py #!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework # from abc import ABC, abstractmethod class QlBaseCoverage(ABC): """ An abstract base class for concrete code coverage collectors. To add suppo...
StarcoderdataPython
11369904
<gh_stars>0 """Module to parse the settings file. This file first reads the default settings file, and then optionally reads a settings file in the working directory to override any of the settings. """ import json import os # Figure out the root directory for our package. dirname = os.path.dirname package_root_direc...
StarcoderdataPython
1804329
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Dec 20 12:06:21 2017 @author: cuijiaxu """ import numpy as np import scipy.io import scipy.stats import pylab as pl from plotshadedErrorBar import plotshadedErrorBar2 from matplotlib.ticker import FuncFormatter def getconvcurve(data): curve=np.zer...
StarcoderdataPython
4961290
<reponame>git2samus/praw """PRAW exception classes. Includes two main exceptions: :class:`.APIException` for when something goes wrong on the server side, and :class:`.ClientException` when something goes wrong on the client side. Both of these classes extend :class:`.PRAWException`. """ from typing import Optional ...
StarcoderdataPython
11351676
import torch import numpy as np import yaml from . import networks from . import math_utils from ...common.utils import pprint_dict def _combine(accel_pred, metric_pred, jacobians, extra_metrics): B = [] C = [] for i in range(len(jacobians)): jacobian = jacobians[i] metric = metric_pred[i...
StarcoderdataPython
6528402
<filename>test/tello/test_protocol.py from unittest.mock import Mock from tello.tello_protocol import TelloProtocol def test_connection_made(): tello_protocol = TelloProtocol("test command", Mock()) tello_protocol.connection_made(Mock()) tello_protocol.transport.sendto.assert_called_once_with(b"test com...
StarcoderdataPython
11394289
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html #encoding: utf-8 import os def ParseFilePath(url, id): # user should change this folder path outfolder = "e:\\data\\FinT...
StarcoderdataPython
11258571
import sys import time from lib.tracing import init_tracer from opentracing_instrumentation.request_context import get_current_span, span_in_context def say_hello(hello_to): with tracer.start_span('say-hello') as span: span.set_tag('hello-to', hello_to) with span_in_context(span): hell...
StarcoderdataPython
5134379
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.contrib import admin from .models import Favorite class FavoriteAdmin(admin.ModelAdmin): list_display = ('product','user',) admin.site.register(Favorite,FavoriteAdmin)
StarcoderdataPython
4817185
<reponame>CesarArroyo09/light_geodesics_thesis #!/usr/bin/env python #Import packages import numpy as np import matplotlib.pyplot as plt #Open data file f1 = open('/home/cesar/light_geodesics_thesis/frw/geodesic_solution_gamma_zero.dat','r') f2 = open('/home/cesar/light_geodesics_thesis/perturbed_minkowski/geodesic_s...
StarcoderdataPython
1896068
<gh_stars>0 import torch import torch.nn as nn from src.lap_solvers.sinkhorn import Sinkhorn from src.feature_align import feature_align from src.gconv import Siamese_ChannelIndependentConv #, Siamese_GconvEdgeDPP, Siamese_GconvEdgeOri from models.PCA.affinity_layer import Affinity from src.lap_solvers.hungarian impor...
StarcoderdataPython
5180084
<gh_stars>0 import os import matplotlib.pyplot as plt from stable_baselines3.common.callbacks import BaseCallback from stable_baselines3.common.results_plotter import load_results, ts2xy import numpy as np class SaveOnBestTrainingRewardCallback(BaseCallback): """ Callback for saving a model (the check is done ...
StarcoderdataPython
6444111
# coding=utf-8 # the path of the Doxyfile DOXFILE_PATH = '/Users/niels/Documents/repositories/json/doc/Doxyfile'
StarcoderdataPython
346911
import json import os import pandas def filter_word(input_word): tmp_output = '' for c in input_word: if c in 'zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP': tmp_output += c return tmp_output def counting_pairs_from_yelp_parsed_data(parsed_data, verb_nsubj_amod_dict, verb_dobj...
StarcoderdataPython
1858243
""" Nothing to see here """ import sys __version__ = "0.3" __uri__ = 'https://github.com/garbled1/pybalboa' __title__ = "pybalboa" __description__ = 'Interface Library for Balboa Spa' __doc__ = __description__ + " <" + __uri__ + ">" __author__ = '<NAME>' __email__ = '<EMAIL>' __license__ = "Apache 2.0" __copyright__...
StarcoderdataPython
3428897
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-14 20:30 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ac_seguridad', '0004_auto_20170808_1926'), ] operations = [ migrations....
StarcoderdataPython
1617693
from .coordattention import CoordAttention, H_Sigmoid, H_Swish from .involution import Involution from .identity import Identity from .droppath import DropPath, droppath
StarcoderdataPython
1680750
<gh_stars>0 from fractions import Fraction as Frac def probs(n,m): #returns a set of probabilities of winning, #drawing and losing given your opponent must take n steps and you must take m win = Frac() draw = Frac() loss = Frac() i=0 while (i<6): i+=1 j=0 while j<6: ...
StarcoderdataPython
3348715
<gh_stars>0 # coding: utf-8 """ Test suite for performance profiling and testing with isolated HTTP WEB Server in a standalone process """ from app01.app01_imp import app from multiprocessing import Process from time import sleep import socket import unittest from urllib3 import HTTPConnectionPool import os import time...
StarcoderdataPython
1963160
<reponame>k-manish2001/1901CB23_2021<filename>proj2/home/admin.py from django.contrib import admin from home.models import Index admin.site.register(Index) # Register your models here.
StarcoderdataPython
3221109
<reponame>qx-teo/covidcast-indicators """Tests for running the signal generation functions.""" import pandas as pd import numpy as np from delphi_hhs_facilities.generate_signals import generate_signal, sum_cols class TestGenerateSignals: def test_generate_signals(self): test_input = pd.DataFrame( ...
StarcoderdataPython
8010503
import pandas as pd import json import sys import os def load_curr(path): df = pd.read_csv(path, sep=',', quotechar='"', index_col='index') return df def create_curr(): df = pd.DataFrame(columns=['index', 'hours', 'title', 'link', 'content']).set_index('index') return df def save_curr(df, path): ...
StarcoderdataPython
3516281
<filename>HowmanySimulationAreSufficient.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: <EMAIL> """ import os import glob import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn import preprocessing import seaborn as sns import matplotlib.pyplot as plt import random from skl...
StarcoderdataPython
9672398
# -*- coding:utf-8 -*- import os import time import six import eventlet import cPickle import contextlib import mysql import mysql.connector from simpleutil.config import cfg from simpleutil.log import log as logging from simpleutil.utils.systemutils import ExitBySIG from simpleutil.utils.systemutils import UnExceptE...
StarcoderdataPython