id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
10541
<filename>model_hub/model_hub/mmdetection/utils.py """ Various utility functions for using mmdetection in Determined that may be useful even if not using the provided MMDetTrial. build_fp16_loss_scaler is large derived from the original mmcv code at https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/hooks/opti...
StarcoderdataPython
176806
<reponame>myarist/Codecademy<filename>Data Scientist Career Path/7. Summary Statistics/8. Associations between Variables/1. Quantitative and Categorical/2. mean median.py import numpy as np import pandas as pd students = pd.read_csv('students.csv') scores_urban = students.G3[students.address == 'U'] scores_rural = stu...
StarcoderdataPython
113851
<filename>scripts/scatter.py import numpy as np import matplotlib.pyplot as plt import pandas as pd np.random.seed(19680801) N = 100 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = 2 #np.pi * (15 * np.random.rand(N))**2 scaffolds='/lustre/scratch117/sciops/team117/hpag/fg6/analysis/D...
StarcoderdataPython
75116
from .patcher import commands_init, slash_command_wrapper, slash_command_parent, update_commands_list from .slash_command import CommandsContext, CommandsMessage, SlashCommand
StarcoderdataPython
4834335
class P4Rule(): def __init__(self, table, action, mparams, aparams, default=False): self.table = table self.action = action self.mparams = mparams self.aparams = aparams self.default = default def __str__(self): ret = self.table if self.default: ret += '*' ret += ' ' + self.ac...
StarcoderdataPython
1786944
<filename>fixture/soap.py from suds.client import Client from suds import WebFault from model.project import Project class SoapHelper: def __init__(self, app): self.app = app def can_login(self, username, password): client = Client(self.app.base_url + "api/soap/mantisconnect.php?wsdl") ...
StarcoderdataPython
56706
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainWindow.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainW...
StarcoderdataPython
1760383
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 ...
StarcoderdataPython
102868
<reponame>Ascend/ascend-deployer #!/usr/bin/env python3 # coding: utf-8 # 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...
StarcoderdataPython
1766674
""" Use HPPC battery cell data to develop a battery cell ECM. Apply current from the 1C, 2C, and 3C battery cell discharge tests to the cell model. Compare the cell model to the discharge voltage and temperature data. """ import matplotlib.pyplot as plt import params from ecm import CellDischargeData from ecm import ...
StarcoderdataPython
159048
""" Profile ../profile-datasets-py/div83/062.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div83/062.py" self["Q"] = numpy.array([ 2.135165, 2.544134, 3.283269, 4.205042, 4.999855, 5.317752, 5.205453, 5.320982, ...
StarcoderdataPython
55571
#!/usr/bin/env python """ Estimates the static background in a STORM movie. The estimate is performed by averaging this might not be the best choice for movies with a high density of real localizations. This may be a good choice if you have a largish fixed background and a relatively low density of real localizations...
StarcoderdataPython
4802744
<reponame>jklymak/dolfyn from setuptools import setup, find_packages import os import shutil # Change this to True if you want to include the tests and test data # in the distribution. include_tests = False try: # This deals with a bug where the tests aren't excluded due to not # rebuilding the files in this ...
StarcoderdataPython
3235035
<filename>Python_5/script_2/lambda_1.py<gh_stars>0 """ Program to show the use of lambda functions double = lambda x: x * 2 print(double(5)) Output 10 Part 1: Write a Python program to count the even, odd numbers in a given array of integers using Lambda. Take list as user Input. Hint : filter Expected Input Output A...
StarcoderdataPython
3262563
# -*- coding: utf-8 -*- """ Copyright 2013 <NAME>, <EMAIL> 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 agree...
StarcoderdataPython
4815668
# Programowanie I R # Funkcje: definiowanie i wywoływanie # Materiały: # https://www.w3schools.com/python/python_functions.asp # https://realpython.com/defining-your-own-python-function/ def f(): # definicja funkcji o nazwie "f" msg = "Funkcja f()" print(msg) print("*** Wywołanie funkcji f() ***") pr...
StarcoderdataPython
4833960
<reponame>feightwywx/iamok<gh_stars>0 from . import apiurl from .login import get_token from .api.aes import aes_encrypt from . import logger from requests.sessions import session from copy import copy import json def bpa(username, password, mailcode): logger.info('学号 {} 同学开始报平安'.format(username)) username = ...
StarcoderdataPython
1649223
""" image_date_organizer.organize ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2019 <NAME> :license: BSD-3-clause """ from datetime import datetime from pathlib import Path import shutil import logging import re from typing import cast, Optional, Dict import magic import pendulum from PIL import Image from PIL.ExifT...
StarcoderdataPython
4817728
#! /usr/bin/env python3 # coding: utf-8 from online_watcher import OnlineWatcher def main(): watcher = OnlineWatcher() watcher.start() if __name__ == '__main__': main()
StarcoderdataPython
4814117
<reponame>acrenwelge/python-stuff<gh_stars>0 import turtle myrtle = turtle.Turtle() dude = turtle.Turtle() myrtle.pencolor("red") dude.pencolor("blue") myrtle.speed(0) dude.speed(0) for i in range(180): myrtle.forward(i+50) myrtle.left(92) dude.forward(i+50) dude.right(92) turtle.done()
StarcoderdataPython
3265418
prob_start = { 'E': -3.14e+100, 'Z': -3.14e+100, 'X': -3.14e+100, 'S': 0.0, 'A': -3.14e+100, 'B': -3.14e+100, 'C': -3.14e+100, 'H': -3.14e+100, 'D': -3.14e+100, 'G': -3.14e+100, }
StarcoderdataPython
3333515
<gh_stars>1-10 # Enter script code keyboard.send_keys("<ctrl>+z")
StarcoderdataPython
1649532
<filename>bitcoin/hash.py # # hash.py # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from __future__ import absolute_import, division, print_function, unicode_literals import struct from bitcoin.serialize import * from ...
StarcoderdataPython
1732943
<reponame>fendaq/Object-Detection-Tensorflow2<gh_stars>0 from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from VGG import vgg16 from fpn_generator import fpn_generator from anchor_generator import anchor_generator from bboxfs import par...
StarcoderdataPython
1767952
<filename>src/playground/test_question100/2.py<gh_stars>0 # description: 2.py # date: 2020/8/3 5:20 下午 # author: objcat # version: 1.0 """ 题目:企业发放的奖金根据利润提成。 利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分, 可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分, 可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于...
StarcoderdataPython
1645341
""" Client/Sender.py ------------------ Sends messages *to* the TroopServer """ from __future__ import absolute_import from .message import * from .config import * from .utils import * import socket from hashlib import md5 class Sender: """ Sends messages to the Server """ def __in...
StarcoderdataPython
187620
import argparse from copy import copy from functools import partial from pathlib import Path from typing import Any from typing import Dict from chainer import cuda from chainer import optimizers from chainer import training from chainer.dataset import convert from chainer.iterators import MultiprocessIterator from ch...
StarcoderdataPython
1725271
<filename>vedacore/modules/__init__.py<gh_stars>10-100 # Copyright (c) Open-MMLab. All rights reserved. from .bricks import (ConvModule, NonLocal1d, NonLocal2d, NonLocal3d, Scale, build_activation_layer, build_conv_layer, build_enhance_module, build_norm_layer, ...
StarcoderdataPython
104514
''' Tests the data merge functions and package. .. moduleauthor:: <NAME> <<EMAIL>> ''' from __future__ import absolute_import import unittest import os from segeval.data.tsv import (input_linear_mass_tsv, input_linear_positions_tsv) from segeval.data.samples import HEARST_1997_STARGAZER class TestTsv(unittest.TestCa...
StarcoderdataPython
3358980
#! -*- coding: utf-8 -*- import numpy as np # Mean Square Error (MSE) def mse(A, B): assert A.shape == B.shape, 'Shape {} is not equal to {}'.format(A.shape, B.shape) return np.square(A-B).mean() # Peak Signal-to-Noise Ratio (PSNR) def psnr(A, B, max_value=255): epsilon = 1e-10 return 20 * np.log10(m...
StarcoderdataPython
156657
from flask_restx import Namespace admin = Namespace('Admin', 'Admin API and User API.', path='/')
StarcoderdataPython
118534
import aiounittest import copy import pydantic from app.github.webhook_model import Webhook data = { "action": 'renamed', "pull_request": { "merged": True }, "repository": { "full_name": "organization/project", "lastName": "p", "age": 71 }, "changes": { ...
StarcoderdataPython
3350248
""" Leia uma temperatura em graus Celsius e apresente-a convertida em graus Kelvin. A fórmula de conversão é: K = C + 273.15, sendo K a temperatura em Kelvin e C a temperatura em Celsius. """ c = float(input('Qual é a temperatura de hoje em graus Celsius ºC? ')) k = c + 273.15 print(f'A temperatura de hoje em Kelvin ...
StarcoderdataPython
1748633
import time import numpy as np import yaml import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix, accuracy_score, cohen_kappa_score def plot_full_barchart(test_score, n_pilots, title="Test accuracy - BCIC IV 2a", fig=None, ax_idx=0): if fig: ax = fig.get_axes()[ax_idx] else: ...
StarcoderdataPython
1762709
<gh_stars>1-10 # file: formCariProduk.py # desain form untuk ubah harga satuan # tgl_buat: 8 OKT 2010 08.40 AM # tgl_revisi : - # lisensi: GPL # dibuat oleh: <EMAIL> from tkinter import * import sqlite3 import tkinter.messagebox as tkMessageBox class FormCariProduk(Toplevel): def __init__(self, parent): ...
StarcoderdataPython
21327
import uvicorn if __name__ == '__main__': <<<<<<< HEAD uvicorn.run('app.main:app', host='0.0.0.0', port=80) ======= uvicorn.run('app.main:app', host='0.0.0.0', port=2323) >>>>>>> c583e3d93c9b7f8e76ce1d676a24740b62ef3552
StarcoderdataPython
1664876
<reponame>JawadAsif/leetcode class Solution(object): def shiftGrid(self, grid, k): l, m, n, k = [num for row in grid for num in row], len(grid), len( grid[0]), k % (len(grid) * len(grid[0])) # grid to list l = l[-k:] + l[:-k] # shift k times return [l[i * n: i * n + n] for i in...
StarcoderdataPython
4801277
<reponame>SherlockHolmes221/GGNe<filename>src/lib/utils/bbox.py import numpy as np import skimage.draw as skdraw from PIL import ImageDraw, Image, ImageFont def text(img, positon, text, color=(0, 0, 255), font_size=30, modify=False): if modify: img_ = img else: img_ = img.copy() img_ = Ima...
StarcoderdataPython
1795895
<reponame>jotaylor/awesimsoss from distutils.extension import Extension def get_package_data(): return {'awesimsoss': ['files/*', 'img/*']}
StarcoderdataPython
1788289
HOME_DIR = "C:/Users/Eddie/Documents/Thesis Code/thesis_flat_earth" DATA_DIR = "C:/Users/Eddie/Documents/Thesis Code/fe_data" TFES_FP = "C:/Users/Eddie/Documents/Thesis Code/fe_data/tfes_forum_anon.db" TFES_TOK_FP = "C:/Users/Eddie/Documents/Thesis Code/fe_data/tfes_posts_anon.json" REDDIT_DIR = "C:/Users/Eddie/Documen...
StarcoderdataPython
138348
<filename>oatomobile/tf/types.py # Copyright 2020 The OATomobile 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...
StarcoderdataPython
1696550
<reponame>congtranv/Unified-Gesture-and-Fingertip-Detection import cv2 import numpy as np from hand_detector.solo.solo_net import model as solo_model from hand_detector.yolo.darknet import model as yolo_model from hand_detector.solo.preprocess.solo_flag import Flag as soloFlag from hand_detector.yolo.preprocess.yolo_fl...
StarcoderdataPython
3373203
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] model = dict(train_cfg=dict(rcnn=dict(sampler=dict(type='OHEMSampler'))))
StarcoderdataPython
3301167
import get_color_pair_number_mapping from get_color_pair_number_mapping import get_color_from_pair_number def print_color_pair_number_mapping(): print ('Pair number | Major color | Minor color \n') for number in range (len(get_color_pair_number_mapping.MINOR_COLORS)*len(get_color_pair_number_mapping.MAJOR_COL...
StarcoderdataPython
107371
#-*- coding:utf-8 -*- import time import requests import credential from bs4 import BeautifulSoup from selenium import webdriver binary= './chromedriver' driver=webdriver.Chrome(binary) f = open('./data/50.txt', 'a') driver.get('https://pann.nate.com/talk/c20005') driver.find_element_by_xpath('//*[@id="GnbWrap"]/div...
StarcoderdataPython
115777
from django.conf import settings from django_rq.management.commands.rqworker import Command as C class Command(C): """ Subclass django_rq's built-in rqworker to listen on all configured queues if none are specified (instead of only the 'default' queue). """ def handle(self, *args, **options): ...
StarcoderdataPython
32432
<reponame>imtapps/django-request-signer import six if six.PY3: from unittest import mock from io import StringIO else: import mock from cStringIO import StringIO from http.client import responses import json from django import test from request_signer.client.generic import Response class ResponseTest...
StarcoderdataPython
3365639
<reponame>nuveo/mmocr # Copyright (c) OpenMMLab. All rights reserved. import argparse import json import math import os.path as osp from functools import partial import mmcv from mmocr.utils.fileio import list_to_file def parse_args(): parser = argparse.ArgumentParser( description='Generate training and...
StarcoderdataPython
4823259
<filename>pyxrd/logs.py #!/usr/bin/python # coding=UTF-8 # ex:ts=4:sw=4:et=on # Copyright (c) 2013, <NAME> # All rights reserved. # Complete license can be found in the LICENSE file. import os import queue import logging from logging.handlers import QueueHandler, QueueListener def setup_logging(basic=False, prefix=...
StarcoderdataPython
1690597
### Import libraries import pprint as pp import time import random import sys import get_yahoo_historical import TDAPI import importlib from datetime import datetime arg = sys.argv if len(arg) < 5: print('Arguments Required: Stonk Ticker, Test or Prod, Buy Start Percentage, Sell Start Percentage') exit() elif ...
StarcoderdataPython
4843084
<filename>holobot/sdk/concurrency/__init__.py from .async_anonymous_disposable import AsyncAnonymousDisposable from .iasync_disposable import IAsyncDisposable from .task import Task, TResult
StarcoderdataPython
97504
import os import sys print('about to import', file=sys.stderr) print('python is', sys.version_info) print('pid is', os.getpid()) import my_pb_mod print('imported, about to call', file=sys.stderr) result = my_pb_mod.add(2, 3) print(result) assert result == 5 print('done!', file=sys.stderr)
StarcoderdataPython
1733545
<filename>core_contracts/feehandler/interfaces.py<gh_stars>10-100 from iconservice import * class IRC2Interface(InterfaceScore): @interface def balanceOf(self, _owner: Address) -> int: pass @interface def transfer(self, _to: Address, _value: int, _data: bytes = None): pass class Go...
StarcoderdataPython
3271599
import re import pandas as pd from gensim.models import Word2Vec from gensim.models.wrappers import FastText print("imported") data = pd.read_csv("song_docs.csv") data.tag_name = data.tag_doc.astype(str) subset = data[0:1000] used_dataset = data.tag_doc.str.lower() print("prepared") # Preprocessing # Inner regex ...
StarcoderdataPython
3316931
<filename>foiamachine/local/lib/python2.7/encodings/shift_jisx0213.py /usr/lib/python2.7/encodings/shift_jisx0213.py
StarcoderdataPython
4805692
from unittest import TestCase import numpy as np from numpy.testing import assert_almost_equal from cate.webapi.minheap import MinHeap class MinHeapTest(TestCase): def test_init_and_properties(self): h = MinHeap(np.zeros(4, dtype=np.float), values=None, size=0) self.assertEqual(h.size, 0) ...
StarcoderdataPython
1678275
from devito.dle.blocking_utils import * # noqa from devito.dle.parallelizer import (NThreads, NThreadsNested, # noqa NThreadsNonaffine, Ompizer, OmpizerGPU) from devito.dle.rewriters import * # noqa from devito.dle.transformer import * # noqa
StarcoderdataPython
3305843
import tensorflow as tf from object_detection.utils import config_util from object_detection.protos import pipeline_pb2 from google.protobuf import text_format PIPELINE_CONF_PATH = 'mymodels\pipeline-update.config' config = config_util.get_configs_from_pipeline_file(PIPELINE_CONF_PATH) pipeline_config = pipeline_pb...
StarcoderdataPython
3354002
<filename>rotkehlchen/tests/api/test_async.py from http import HTTPStatus from unittest.mock import patch import gevent import pytest import requests from rotkehlchen.tests.utils.api import ( api_url_for, assert_error_response, assert_ok_async_response, assert_proper_response, ) from rotkehlchen.tests...
StarcoderdataPython
1757487
<filename>ex107/teste.py """ Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e use algumas dessa funções. """ from ex107 import moeda p = float(input("Digite o preço: R$")) print(f"A metade de {p} é {moeda.me...
StarcoderdataPython
1768493
<reponame>oralvi/rinyuuki # 订阅推主 import json import os import re from collections import defaultdict from dataclasses import dataclass, field from typing import Dict, Iterable, Set import peony from peony import PeonyClient from rin import Service, priv from rin.config import twitter as cfg from rin.typing import Me...
StarcoderdataPython
1687876
<gh_stars>100-1000 """Custom TF 'ops' as meant in the TensorFlow definition of ops.""" import numpy as np import tensorflow as tf from utils import io_utils from tensorflow.python.util import nest def dynamic_sampled_softmax_loss(labels, logits, output_projection, vocab_size, from_sc...
StarcoderdataPython
3363971
# -*- coding: utf-8 -*- """ sonoff_lan_mode_r3 """ __author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ = '1.1.4.1' __url__ = 'https://github.com/mattsaxon/sonoff-lan-mode-homeassistant'
StarcoderdataPython
41171
# Generated by Django 2.1.3 on 2019-02-12 19:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profile', '0002_auto_20180126_1900'), ] operations = [ migrations.CreateModel( name='GlobalAlert', fields=[ ...
StarcoderdataPython
3299608
<gh_stars>100-1000 import time from itertools import count import torch from lagom import Logger from lagom import BaseEngine from lagom.transform import describe from lagom.utils import color_str class Engine(BaseEngine): def train(self, n=None, **kwargs): train_logs, eval_logs = [], [] checkpoi...
StarcoderdataPython
145671
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter import numpy as np def mixup_data(x, y, alpha): # https://github.com/vikasverma1077/manifold_mixup/blob/master/supervised/utils.py '''Compute the mixup data. Return mixed inputs, pairs of targets...
StarcoderdataPython
1799336
import gzip import shutil import subprocess from dataclasses import dataclass, field from pathlib import Path from typing import Dict, Iterator, List, Union, Tuple import numpy as np from Bio import SeqIO from dataclasses_json import config, dataclass_json @dataclass_json @dataclass(frozen=True) class PrimerMatch: ...
StarcoderdataPython
1661008
famous_person = " \t<NAME>\n " print(famous_person) print(famous_person.lstrip()) print(famous_person.rstrip()) print(famous_person.strip())
StarcoderdataPython
1707548
def module4_sub(n1, n2, n3): return n1 - n2 - n3 class ClassInModule4: @staticmethod def sub(n1, n2, n3): return n1 - n2 - n3 - 2
StarcoderdataPython
1774933
<reponame>jbongard/SAIL_ON import constants as c from legPart import LEG_PART class LEG(): def __init__(self,robotType,legIndex): self.legParts = {} self.legParts[c.upperLeg] = LEG_PART(robotType,legIndex,c.upperLeg) self.legParts[c.lowerLeg] = LEG_PART(robotType,legIndex,c.lowerLeg) ...
StarcoderdataPython
1664670
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math import os import numpy as np from numpy import pi,cos,sin import pandas as pd import logging from plotnine import * from scipy.stats.mstats import winsorize from plotnine.stats.stat_summary import bootstrap_statistics #%% put PUPIL LABS data into PANDAS...
StarcoderdataPython
16894
""" Interfaces with Verisure sensors. For more details about this platform, please refer to the documentation at documentation at https://home-assistant.io/components/verisure/ """ import logging from homeassistant.components.verisure import HUB as hub from homeassistant.const import TEMP_CELSIUS from homeassistant.h...
StarcoderdataPython
1649393
import numpy as np import tensorflow as tf import random import param_gedi as param import tensorflow_addons as tfa class Parser: """Parse tfrecord""" def __init__(self, p): self.p = p def tfrec_parse(self, row): """ Parse single item in tfrecord. You most likely want tfrec_batch...
StarcoderdataPython
3309186
import hashlib import sqlite3 import os from base64 import b64encode import sys from version import VERSION, DEV_STABLE, DEV if "GYC_DATABASE" in os.environ: dbpath = os.environ['GYC_DATABASE'] else: dbpath = "database" if os.path.isfile(dbpath): print("Already installed!") exit(0) if DEV and "--contin...
StarcoderdataPython
3295670
<gh_stars>1-10 from hubcheck.pageobjects.po_generic_page import GenericPage class ResourcesToolContributorsPage(GenericPage): """tool resource contributor page""" def __init__(self,browser,catalog,toolname=None): super(ResourcesToolContributorsPage,self).__init__(browser,catalog) if toolname i...
StarcoderdataPython
4823051
from datetime import datetime import pytest from tartiflette import Resolver, create_engine @pytest.mark.asyncio async def test_naive_datetime_ok(): @Resolver("Query.date", schema_name="test_naive_datetime_ok") async def date_resolver(*_args, **_kwargs): return datetime(2019, 9, 23, 13, 44, 0) ...
StarcoderdataPython
1770454
<reponame>PatrickLopesF/donttapv2<filename>bot.py import time import pyautogui import keyboard timeout = 40 timeout_start = time.time() time.sleep(2) while keyboard.is_pressed('w') == False: while time.time() < timeout_start + timeout: im1 = pyautogui.screenshot() r1,g1,b1 = im1.getpi...
StarcoderdataPython
3357760
import numpy as np from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score def accuracy(output, target): pred = np.argmax(output.data, axis=1) acc = accuracy_score(target, pred) # , labels=np.unique(pred)) return acc def precision(output, target, average='micro'): pred =...
StarcoderdataPython
3239162
import torch import math ###################################################################### ############################ MODEL UTILS ############################# ###################################################################### def num_trainable_params(model): total = 0 for p in model.parameters()...
StarcoderdataPython
1736640
import numpy as np import pytest from pyrender import ( DirectionalLight, SpotLight, PointLight, Texture, PerspectiveCamera, OrthographicCamera, ) from pyrender.constants import SHADOW_TEX_SZ def test_directional_light(): d = DirectionalLight() assert d.name is None assert np.all...
StarcoderdataPython
124999
<gh_stars>0 #!/usr/bin/python ##Concat list of .csv files generated by analyse_point_source_scan # python concat_pointing_csv.py -a m063 -e -v *.csv # # Revision History: # * (Ruby) Initial implementation import optparse import numpy import matplotlib.pyplot as plt # Simple function that reads in a file and writes it...
StarcoderdataPython
3213886
<reponame>jpanchal/gildedrose-api from django.contrib import admin from .models import Itemlist from rest_framework.authtoken.admin import TokenAdmin TokenAdmin.raw_id_fields = ('user',) # Register your models here. admin.site.register(Itemlist)
StarcoderdataPython
1654469
<filename>videosucker.py #!/usr/bin/env python """ Video Sucker - pcap file video extractor This is a tool that sucks the videos out of your .pcap files. It reconstructs the original TCP streams, processes HTTP messages, and looks for video transfers in them. The videos are dumped into a chosen folder Tested with: - ...
StarcoderdataPython
3264445
import logging import json import multiprocessing as mp from luafun.game.inspect.base import BasePage from luafun.game.action import IPCMessageBuilder, Action import rpcjs.elements as html log = logging.getLogger(__name__) class Config: def __init__(self, app): # this is supposed to be inverted, not a ...
StarcoderdataPython
1679673
import uuid import random import string random.seed("LKL1_2018_BROADCAST") FLAG = "LKL{{y0u_h4ve_13arnt_w3bs0cket_m4gic_{}}}" ALPHABET = string.ascii_letters + string.digits def get_rand_uuid(): return uuid.UUID(bytes=bytes(bytearray(random.getrandbits(8) for _ in range(16)))) def get_rand_text(): return ...
StarcoderdataPython
1613307
<reponame>jiadaizhao/LeetCode<gh_stars>10-100 import math class Solution: def simplifiedFractions(self, n: int) -> List[str]: result = [] for d in range(2, n + 1): for n in range(1, d): if math.gcd(d, n) == 1: result.append("{}/{}".format(n, d)) ...
StarcoderdataPython
56004
import re import itertools import os import pandas as pd import numpy as np from prettytable import PrettyTable from tqdm import tqdm def get_char(seq): """split string int sequence of chars returned in pandas.Series""" chars = list(seq) return pd.Series(chars) class SeqProcessConfig(object): def __i...
StarcoderdataPython
66237
<filename>process.py def kinda_next(x): try: return next(x) except: return None def process(data): players = [] for round in data: for song in round['songs']: submitter = song['submitter'] if not submitter in players: players.append(submit...
StarcoderdataPython
14218
__author__ = '<NAME>'
StarcoderdataPython
1709401
<filename>setup.py import pathlib from setuptools import setup HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() setup( name = 'hintcast', packages = ['hintcast'], version = '0.1.0', license = 'MIT', description = 'Decorators that allow for automatic type-casting of a...
StarcoderdataPython
47348
<filename>base/site-packages/mobileadmin/templatetags/mobile_admin_media.py from django.template import Library register = Library() def mobileadmin_media_prefix(): """ Returns the string contained in the setting MOBILEADMIN_MEDIA_PREFIX. """ try: from mobileadmin.conf import settings exce...
StarcoderdataPython
81449
<filename>timelogsparser/__init__.py import argparse import os import sys import anyconfig from refreshbooks import api from timelogs import Timelogs parent_parser = argparse.ArgumentParser(description="Timelogs Processor", add_help=False) parent_parser.add_argument('files', nargs='*', help='file sources', type=argpa...
StarcoderdataPython
1785513
<reponame>dfm/aiohttp_spotify<filename>src/aiohttp_spotify/views.py __all__ = ["routes"] import logging import secrets from typing import Any, MutableMapping, Optional, Union from aiohttp import ClientSession, web from . import api logger = logging.getLogger("aiohttp_spotify") try: import aiohttp_session f...
StarcoderdataPython
4824471
<filename>official/vision/detection/ops/sampling_ops.py # Copyright 2019 The TensorFlow 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...
StarcoderdataPython
1708102
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton class WeeklyNotificationSettings(InlineKeyboardMarkup): @staticmethod def create(): turn_on_button = InlineKeyboardButton('Включить', callback_data=f'week_on') turn_off_button = I...
StarcoderdataPython
3274213
<filename>Azahar/BuildOligo.py import pymol from pymol import cmd import os import sys path = os.path.dirname(__file__) sys.path.append(path) from torsionals import set_phi, set_psi, get_phi, get_psi try: from energy import minimize babel = True except ImportError: babel = False def read_input(matrix): ...
StarcoderdataPython
3310456
<filename>src/public_artifact_repo/main.py import base64 import json import logging import sys from os import getenv from google.cloud import artifactregistry from google.api_core import exceptions # pylint: disable=import-error from lockdown_logging import create_logger # pylint: disable=import-error from lockdow...
StarcoderdataPython
1648494
# Copyright 2015-2017 F-Secure # 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 writing, ...
StarcoderdataPython
3241835
from datetime import timedelta, date from django.urls import reverse from ..models import Event, Organization, Role, Person, Tag from .base import TestBase class TestIssuesViews(TestBase): def setUp(self): super()._setUpUsersAndLogin() super()._setUpRoles() super()._setUpTags() ...
StarcoderdataPython
3208394
import re # regex def cornell_cleanup(sentence): # clean up html tags sentence = re.sub(r'<.*?>', '', sentence.lower()) # clean up \n and \r return sentence.replace('\n', '').replace('\r', '') def load_cornell(path_conversations, path_lines): movie_lines = {} lines_file = open(path_lines, '...
StarcoderdataPython