id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1642309 | import csv
import json
import os
import matplotlib.pyplot as plt
import commonfunctions as cf
import matplotlib as mpl
root_directory = os.path.abspath(os.path.dirname(os.path.abspath(os.curdir)))
directory = os.path.join(root_directory, cf.working_directory)
with open('sentiment-time-winnerloser.json', 'r') as f:
... | StarcoderdataPython |
161337 | #this code is just an example from 2018 nur luege /
from flask import Flask, request, render_template, abort
import os, requests
app = Flask(__name__)
class user:
def __init__(self, username, password):
self.username = username
self.__password = password
self.files = []
def getPass(se... | StarcoderdataPython |
136688 | <filename>mne/preprocessing/nirs/_beer_lambert_law.py
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import os.path as op
import re as re
import numpy as np
from scipy import linalg
from ...io import BaseRaw
from ...io.pick import _picks_to_idx
from ..... | StarcoderdataPython |
1745890 | <reponame>vivin-christy/ud-catalog
import sys
sys.path.insert(0, '/var/www/catalog')
from catalog import app as application
application.secret_key = 'New secret key. Change it on server'
application.config['SQLALCHEMY_DATABASE_URI'] = (
'postgresql://'
'catalog:password@localhost/catalog')
| StarcoderdataPython |
161645 | # -*- coding: utf-8 -*
"""Implementation of the ``repeat_analysis`` step
The ``repeat_analysis`` step takes as the input the results of the ``ngs_mapping`` step
(aligned reads in BAM format) and performs repeat expansion analysis. The result are variant files
(VCF) with the repeat expansions definitions, and associat... | StarcoderdataPython |
101184 | from flask import Flask, render_template
from subprocess import call
app = Flask(__name__)
SENDER_CONFIG = '10101'
SEND_CONFIG = ['-u', '-s']
RECEIVER = {
'A': '1',
'B': '2',
'C': '3',
'D': '4',
}
STATES = {
'on':'1',
'off':'0'
}
def send_signal(receiver, state):
call(['./send', SENDER_CO... | StarcoderdataPython |
20978 | import csv
import json
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
formats = ['png', 'pdf', 'svg', 'eps']
metrics = [
{'gmetric': 'groc', 'lmetric': 'lroc', 'metric': 'AUC'},
{'gmetric': 'gauc', 'lmetric': 'lauc', 'metric': 'PRAUC'},
]
datasets = [
... | StarcoderdataPython |
1739707 |
class LaplaceSmoother(object):
'''
Add delta smoothing algorithme module
'''
def __init__(self, delta=1):
self.delta = delta
def smooth(self, counter, words):
'''
return P(w_n | w_1, w_2, ... w_n-1) = C(w_n | w_1, w_2, ... w_n-1) + delta / C(w_1, w_2, ... w_n-1) + |V| * del... | StarcoderdataPython |
3210924 | <reponame>PeterWolf93/PupilLabs_VR_Calibration<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 07:26:07 2018
@author: <NAME>
title: start_calib
"""
#%% Imports
import numpy as np
from calib_main import calib_main
from load_pickle import load_pickle
#%% Version number
version_num = 'V9'
... | StarcoderdataPython |
3312641 | <gh_stars>0
#!/usr/bin/python3
# parse.py
#
# <NAME> 28-Dec-2021
#
# Copyright (C) Randix LLC. All rights reserved.
#
# This reads from the serial port and parses the data from the
# microwizard.com Fast Track Model K2
#
# output the raw data to the file "raw.log"
# output the parsed data to "times.csv"
import os
imp... | StarcoderdataPython |
73800 | # coding: utf8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# 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 requ... | StarcoderdataPython |
101343 | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
s = []
for v in input().strip():
if v != 'B':
s.append(v)
else:
if s:
s.pop()
print(''.join(s))
| StarcoderdataPython |
3209515 | <gh_stars>0
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['addition', 'multiply']
# Cell
from fastcore.all import *
from typing import Union
# Cell
from typing import Union
def addition(a:Union[int, float], b:Union[int, float]) -> Union[int, float]:
"""
A... | StarcoderdataPython |
166885 | import requests
from exceptions import RequestError
from log import Log
from .ladder import Ladder
from .player import Player
class API:
@staticmethod
def get_current_season_id(params: dict) -> int:
r = requests.get("https://us.api.battle.net/data/sc2/season/current", params)
if r.status_code... | StarcoderdataPython |
1787511 | import asyncio
import logging
from functools import wraps
import inspect
from typing import (
Any,
Awaitable,
Callable,
NamedTuple,
Tuple,
Type,
TypeVar,
Union,
cast,
)
_T = TypeVar("_T")
_log = logging.getLogger(__name__)
async def _noop(*args, **kwargs):
pass
def retryab... | StarcoderdataPython |
136852 | <filename>projeto-01/measure.py
from subprocess import run
from os import path, makedirs
import csv
if not path.exists("./sort"):
run(["make", "build"])
makedirs(path.join(path.curdir, "data"), exist_ok=True)
for sort_method in ("merge", "heap", "bubble"):
with open(path.join(path.curdir, "data", f"{sort_met... | StarcoderdataPython |
3223109 | <reponame>dpouris/chore-battle<gh_stars>1-10
from rest_framework_simplejwt.authentication import JWTAuthentication
from django.conf import settings
from rest_framework.authentication import CSRFCheck
from rest_framework import exceptions
def enforce_csrf(request):
"""
Enforce CSRF validation.
"""
chec... | StarcoderdataPython |
169018 | # Copyright Amazon.com Inc. or its affiliates. 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. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanyin... | StarcoderdataPython |
1720983 | <filename>Controllers/Utilities.py
from flask import jsonify
from flask_restful import Resource
# Authentication #
from Other.Authentication import require_auth
from Other.SharedResources import g_user
class ValidateIP(Resource):
def get(self):
return jsonify({"answer":"True"})
... | StarcoderdataPython |
3229023 | <filename>users/management/commands/dispensary_import.py<gh_stars>1-10
import datetime
from django.core.management.base import BaseCommand
from openpyxl import load_workbook
import clients.models as clients
class Command(BaseCommand):
def add_arguments(self, parser):
"""
:param path - файл с кар... | StarcoderdataPython |
1676743 | <reponame>adolabsnet/HatSploit
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2021 EntySec
#
# 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 |
1699562 | from typing import List, Optional
from pydantic import Field, BaseModel
from tottle.types.objects.alert import ProximityAlertTriggered
from tottle.types.objects.animation import Animation
from tottle.types.objects.audio import Audio
from tottle.types.objects.chat import Chat
from tottle.types.objects.contact import Co... | StarcoderdataPython |
3201699 | <reponame>Hickey3197/educoder<filename>Handwritten_digit_recognition/Handwritten.py
import numpy
import scipy.special
import matplotlib.pyplot
import imageio
import glob
# 神经网络类定义
class neuralNetwork:
# 初始化神经网络
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# 设置每个输入... | StarcoderdataPython |
58896 | <filename>SNIC/data.py
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("snic-provincias.csv")
print(df.head())
print(df.columns)
print(df.anio.describe())
plt.plot(df.anio, df.cantidad_hechos)
plt.show() | StarcoderdataPython |
1693869 | <reponame>HarshShah03325/Emotion_Recognition
import model
import json
from util import VolumeDataGenerator
def train_model(steps_per_epoch, n_epochs, validation_steps):
'''
trains a 3D Unet for give parameters:
steps_per_epoch
n_epochs
validation_steps
The function uses train generator and vali... | StarcoderdataPython |
1754860 | <gh_stars>0
# coding: utf-8
"""dynamic_raw_id filters."""
from django import forms
from django.contrib import admin
from dynamic_raw_id.widgets import DynamicRawIDWidget
class DynamicRawIDFilterForm(forms.Form):
"""Form for dynamic_raw_id filter."""
def __init__(self, rel, admin_site, field_name, **kwarg... | StarcoderdataPython |
1750074 | <filename>events/forms.py
from django.utils.safestring import mark_safe
from django import forms
from django.forms.widgets import TextInput, Media
from django.core.validators import validate_email
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.contrib.auth.models ... | StarcoderdataPython |
1617133 | #!/usr/bin/env python
# -*- coding: utf-8
# Copyright 2017-2019 The FIAAS Authors
#
# 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
#
# Unle... | StarcoderdataPython |
3233713 | <gh_stars>1-10
#!/usr/bin/python
##
## GIFEFFIT: Graphical User Interface to the IFEFFIT XAFS Analysis Library
##
## Copyright (c) 1997--2000 <NAME>, The University of Chicago
## Copyright (c) 1992--1996 <NAME>, University of Washington
##
## Permission to use and redistribute the source code or binary forms of
#... | StarcoderdataPython |
3367822 | <reponame>Corb3nik/fixenv
#!/usr/bin/env python2
import sys
import argparse
import binascii
from pwn import *
# python solution.py -e remote ./echoservice -i echo.stillhackinganyway.nl -p 1337
# You need the binary (echoservice) in the same directory
# You need the libc (libc6_2.23-0ubuntu9_amd64.so) with hash 885acc... | StarcoderdataPython |
117288 | <filename>ddpg-bipedal/pytorch-imp/MyAgent.py
import numpy as np
import torch
import torch.nn.functional as F
from MyModel import *
import copy
from collections import deque, namedtuple
import random
# import heapq
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
class ReplayBuffer():
def ... | StarcoderdataPython |
3272000 | <filename>reference_book/api/filters.py
from rest_framework import filters
class CustomSearchFilter(filters.SearchFilter):
search_param = 'q'
| StarcoderdataPython |
1766158 | <reponame>qyl2021/certbot<filename>tools/pip_install.py
#!/usr/bin/env python
# pip installs packages using pinned package versions. If CERTBOT_OLDEST is set
# to 1, a combination of tools/oldest_constraints.txt and
# tools/dev_constraints.txt is used, otherwise, tools/requirements.txt is used.
from __future__ import ... | StarcoderdataPython |
3295915 | # Copyright 2017. <NAME>. All rights reserved
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# dis... | StarcoderdataPython |
157583 | """Estimation of lambdaN"""
import matplotlib.pyplot as plt
import networkx as nx
from numpy import *
import scipy
def maximum_eigen():
list1 = []
list2 = []
for i in range(10, 31):
for j in range(0, 10):
G1 = nx.barabasi_albert_graph(500, i, seed=j)
degree_sequence = [d f... | StarcoderdataPython |
191919 | <gh_stars>10-100
from abc import ABC, abstractmethod
from typing import Generator, Type
from open_sea_v1.endpoints.client import ClientParams
from open_sea_v1.responses.abc import BaseResponse
class BaseEndpoint(ABC):
@property
@abstractmethod
def __post_init__(self):
"""Using post_init to run p... | StarcoderdataPython |
3278847 | import os
from jennie.ubuntu.nginxfiles import *
def install_phpmyadmin():
os.system("wget https://files.phpmyadmin.net/phpMyAdmin/5.1.0/phpMyAdmin-5.1.0-all-languages.tar.gz")
os.system("tar -xvf phpMyAdmin-5.1.0-all-languages.tar.gz")
os.system("mv phpMyAdmin-5.1.0-all-languages /var/www/html/phpmyadmin"... | StarcoderdataPython |
4800909 | <filename>airwaveapiclient/tests/test_apdetail.py
# -*- coding: utf-8 -*-
"""UnitTests for airwaveapiclient."""
import os
import unittest
from airwaveapiclient import APDetail
from airwaveapiclient.tests import test_utils
class APDetailUnitTests(unittest.TestCase):
"""Class APDetailUnitTests.
Unit test fo... | StarcoderdataPython |
3327454 | # HEAD
# Modules - Creating and using directory module as package
# DESCRIPTION
# Describes the usage of package init.py file with other file module
# Imports file module explicitly - bypasses __init__.py scoping
# Imports also uses alias for the imported file module
# Describes usage of import statements
# and ... | StarcoderdataPython |
1689458 | <gh_stars>1-10
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
class SIR_Cell(layers.Layer):
def __init__(self, population, **kwargs):
'''
Initialization of the Cell. state_size and output_size are mandatory elements.
Since this is a simple Markov Chain, there is no hidden state
... | StarcoderdataPython |
1708111 | <filename>src/evoml/framework/datasets/_base.py
from genericpath import exists
from math import e
from os import environ, listdir, makedirs, rmdir, path
from os.path import dirname, expanduser, isdir, join, splitext, basename
from typing import Tuple
import pandas as pd
import shutil
from scipy.sparse import data
from ... | StarcoderdataPython |
1635995 | <reponame>benjamin-gar/clonesquad-ec2-pet-autoscaler
import os
import sys
import re
import hashlib
import json
import math
import gzip
# Hack: Force gzip to have a deterministic output (See https://stackoverflow.com/questions/264224/setting-the-gzip-timestamp-from-python/264303#264303)
class GzipFakeTime:
def time(... | StarcoderdataPython |
3366125 | <reponame>abhinavtripathy/Volog
"""
File Name: Validators
Purpose: Functions for verifying that input is in an acceptable format.
Comments:
"""
from django.core.exceptions import ValidationError
from django.utils.timezone import now
def no_past_dates(date):
"""
This validator will raise a validation error if... | StarcoderdataPython |
56223 | <reponame>leedongminAI/Reinforcement_Basic<filename>RL_Lab_04_1.py
"""
Dummy Q-learning (table)
exploit&exploration and discounted future reward 에 대한 코드입니다.
"""
"""
exploit&exploration and discounted future reward을 해주는 이유는
Lab3에서는 랜덤하지 못하게(유연하지 못하게) state를 돌기 때문입니다.
안가본 곳도 가봐야 더 좋은 길이 있을 수도 있고, 더 효율성이 증가하기 때문에
안가본 곳도 ... | StarcoderdataPython |
1683632 | import argparse
def get_args():
parser = argparse.ArgumentParser()
# Data file
parser.add_argument('--train_file',
type=str,
default=None,
help='Training file')
parser.add_argument('--dev_file',
type=str,... | StarcoderdataPython |
1745614 | # -*- coding: utf-8 -*-
"""
flask.module
~~~~~~~~~~~~
Implements a class that represents module blueprints.
:copyright: (c) 2011 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
import os
from .blueprints import Blueprint
def blueprint_is_module(bp):
"""Used to figure out if som... | StarcoderdataPython |
1648791 | import warnings
import glob
import os
from scipy.stats import linregress, norm
import xarray as xr
import pandas as pd
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
with warnings.catch_warnings():
warnings.simp... | StarcoderdataPython |
1694660 | <gh_stars>0
import os
import sys
#print(os.path.abspath('../../..'))
def tester():
"""
here are some things but idk
"""
return 0 | StarcoderdataPython |
1653462 | <reponame>bareblackfoot/faster-rcnn.selection<gh_stars>0
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME> and <NAME>
# --------------------------------------------------------
from __future__ import absolu... | StarcoderdataPython |
3389698 | <reponame>bessoh2/integration_station
import fnmatch
from intake.catalog import Catalog
import os
import xarray as xr
"""
IMPORTANT NOTES
This code is currently UNDER DEVELOPMENT for the icepyx (https://github.com/icesat2py/icepyx) library for working with ICESat-2 data.
This version of the code is static and will on... | StarcoderdataPython |
127949 | '''
__iter__
如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法
__getitem__
使实例可以像list一样通过下标获取元素
'''
class demo02:
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a,b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
if self.a != 0:... | StarcoderdataPython |
166267 | import os
import unittest
from dotenv import dotenv_values
from skyflow.service_account._token import *
from skyflow.service_account import is_expired
class TestGenerateBearerToken(unittest.TestCase):
def setUp(self) -> None:
self.dataPath = os.path.join(
os.getcwd(), 'tests/service_account/... | StarcoderdataPython |
3336664 |
from transformers import pipeline
unmasker = pipeline('fill-mask', model='bert-base-uncased')
unmasker("Hello I'm a [MASK] model.")
[{'sequence': "[CLS] hello i'm a fashion model. [SEP]",
'score': 0.1073106899857521,
'token': 4827,
'token_str': 'fashion'},
{'sequence': "[CLS] hello i'm a role model. [SE... | StarcoderdataPython |
73752 | import pytest
from click.testing import CliRunner
import dodola.cli
import dodola.services
@pytest.mark.parametrize(
"subcmd",
[
None,
"biascorrect",
"buildweights",
"rechunk",
"regrid",
"train-qdm",
"apply-qdm",
"correct-wetday-frequency",
... | StarcoderdataPython |
3207915 | # Copyright 2019 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | StarcoderdataPython |
1639483 | from django.urls import path
from .views import upload_file_view
urlpatterns = [
path("", upload_file_view, name="upload-view"),
] | StarcoderdataPython |
3365268 | <reponame>TobiasBrx/AlphaToe
"""
It is important to note that if the second player is randomized without knowing the rules,
their performance is so bad that the DQN algorithm simply learns how to play legal moves
and waits until the random opponent makes an illegal move which causes the DQN agent to win.
It is extremel... | StarcoderdataPython |
23226 | # Copyright (c) 2012 <NAME> <<EMAIL>>
#
# This is free software released under the MIT license.
# See COPYING file for details, or visit:
# http://www.opensource.org/licenses/mit-license.php
#
# The file is part of FSMonitor, a file-system monitoring library.
# https://github.com/shaurz/fsmonitor
import sys, os, time,... | StarcoderdataPython |
3369937 | <reponame>albfan/pudb
from __future__ import absolute_import, division, print_function
from pudb.py3compat import PY3
# {{{ breakpoint validity
def generate_executable_lines_for_code(code):
l = code.co_firstlineno
yield l
if PY3:
for c in code.co_lnotab[1::2]:
l += c
yield... | StarcoderdataPython |
69336 | import tensorflow as tf
import numpy as np
from PIL import Image
import os
import glob
import platform
import argparse
from scipy.io import loadmat,savemat
from preprocess_img import align_img
from utils import *
from face_decoder import Face3D
from options import Option
is_windows = True
def parse_args():
des... | StarcoderdataPython |
3378945 | from __future__ import print_function
import numpy as np
import time
import data_util
weight_names = ["w_in", "b_in", "w_out", "b_out",
"rnn/multi_rnn_cell/cell_0/basic_lstm_cell/weights",
"rnn/multi_rnn_cell/cell_0/basic_lstm_cell/biases",
"rnn/multi_rnn_cell/cell_1/bas... | StarcoderdataPython |
1714399 | # noqa
x = # Cause import error
| StarcoderdataPython |
26854 | <reponame>DarkSession/fd-api
# vim: textwidth=0 wrapmargin=0 tabstop=2 shiftwidth=2 softtabstop=2 smartindent smarttab
from setuptools import setup, find_namespace_packages
setup(
name="org.miggy",
packages=find_namespace_packages()
)
| StarcoderdataPython |
162569 | <filename>testing/test_homework_01/conftest.py
# from utils import add_homework_path
#
# add_homework_path(__file__)
| StarcoderdataPython |
194645 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | StarcoderdataPython |
181203 | <reponame>cthorey/Grid<filename>grid/clients/keras.py
from . import base
from ..lib import utils
from .. import channels
import ipywidgets as widgets
import json
import random
from ..lib import keras_utils
class KerasClient(base.BaseClient):
def __init__(self,
min_om_nodes=1,
kn... | StarcoderdataPython |
25518 | <filename>src/search_items/models.py
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
# Create your models here.
class Search(models.Model):
name = models.CharField(max_length=120)
link = models.CharField(max_length=120)
def __unicode__(self):
return self.n... | StarcoderdataPython |
3260645 | # Generated by the Protocol Buffers compiler. DO NOT EDIT!
# source: extension.proto
# plugin: grpclib.plugin.main
import abc
import typing
import grpclib.const
import grpclib.client
if typing.TYPE_CHECKING:
import grpclib.server
import extension_pb2
class PodExtensionBase(abc.ABC):
@abc.abstractmethod
... | StarcoderdataPython |
32821 | <reponame>nm-wu/RAMLFlask<filename>RAMLFlask/Server.py
import os
from importlib import import_module
from flask import Flask
import ConfigParser
import Printer
class Server:
def __init__(self, generator, comparison, config_file='config.ini'):
# Generator class
self.gen = generator
# Compa... | StarcoderdataPython |
56834 | <gh_stars>1-10
from waflib.Task import Task
class src2cpp(Task):
run_str = '${SRC[0].abspath()} ${SRC[1].abspath()} ${TGT}'
color = 'PINK'
from waflib.TaskGen import extension
@extension('.src')
def process_src(self, node):
tg = self.bld.get_tgen_by_name('comp')
comp = tg.link_task.outputs[0]
tsk = self.create... | StarcoderdataPython |
3396226 | #################################
# This script performs the data loading, data preparation and feature enginnering.
# It takes two arguments:
# 1. The configuration file which contains the Azure
# storage account name, key and data source location.
# By default, it is "./Config/storageconfig.json"
# 2. a DEBUG... | 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 |
3295790 | # -*- coding: UTF-8 -*-
import sys,os,dlib,glob,numpy
from skimage import io
import cv2
import imutils
import php
my = php.kit()
if len(sys.argv) != 2:
print("缺少要辨識的圖片名稱")
exit()
# 人臉68特徵點模型路徑
predictor_path = "shape_predictor_68_face_landmarks.dat"
# 人臉辨識模型路徑
face_rec_model_path = "dlib_face_r... | StarcoderdataPython |
3359713 | <filename>Python/Encrypt credentials/Encryption sample/services/getdatasource.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import requests
class GetDatasourceService:
headers = None
def get_datasources_in_group(self, access_token, group_id, dataset_id):
''' Returns al... | StarcoderdataPython |
180793 | import math
import torch
from HyperSphere.BO.utils.normal_cdf import norm_cdf
def norm_pdf(x, mu=0.0, var=1.0):
return torch.exp(-0.5 * (x-mu) ** 2 / var)/(2 * math.pi * var)**0.5
def expected_improvement(mean, var, reference):
std = torch.sqrt(var)
standardized = (-mean + reference) / std
return (std * norm_... | StarcoderdataPython |
1738443 | <reponame>Paradigm-shift-AI/paradigm-brain
import requests
import os
class SequenceRearrange:
"""
SequenceRearrange
Class that create SequenceRearrange question, it use the sequence defined in
the plugin and the intersection of the tags discovered in the transcript to
create the question
Argu... | StarcoderdataPython |
4805361 | from zabbix_enums.common import _ZabbixEnum
class TaskType(_ZabbixEnum):
DIAGNOSTIC = 1
CHECK_NOW = 6
class TaskStatus(_ZabbixEnum):
NEW = 1
IN_PROGRESS = 2
COMPLETED = 3
EXPIRED = 4
class TaskStatisticResult(_ZabbixEnum):
ERROR = -1
CREATED = 0
| StarcoderdataPython |
3252711 | from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from products.models import Product
from sales.models import SaleItem, Payment, Sale, Shipping
# sale = models.OneToOneField(Sale, on_delete=models.CASCADE)
# amount = models.PositiveIntegerField(defa... | StarcoderdataPython |
4803567 | <reponame>thagusta/LEEM-analysis
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3... | StarcoderdataPython |
1727162 | import logging
from unittest import TestCase
from tests.utils.hvac_integration_test_case import HvacIntegrationTestCase
class TestInit(HvacIntegrationTestCase, TestCase):
def test_read_init_status(self):
read_response = self.client.sys.read_init_status()
logging.debug("read_response: %s" % read_r... | StarcoderdataPython |
1645821 | <reponame>mustious/iGlass-infinity
import speech_recognition as sr
import os
project_root_path = os.path.abspath(os.path.dirname(__file__))
beep_tone_path = os.path.join(project_root_path, ".tones/beep_ping.wav")
google_keys_path = os.environ.get("google_keys_path")
# checks whether the environment variable va... | StarcoderdataPython |
175094 | import utils
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from modules.transformer import TransformerEncoder
class ClassEmbedding(nn.Module):
def __init__(self, cfg, trainable=True):
super(ClassEmbedding, self).__init__()
idx2vocab = utils.load_files(cfg["... | StarcoderdataPython |
181397 | """Extra utilities for state machines, to make them more usable."""
from weakref import WeakKeyDictionary
class ProxyString(str):
"""String that proxies every call to nested machine."""
def __new__(cls, value, machine):
"""Create new string instance with reference to given machine."""
strin... | StarcoderdataPython |
1703162 | <reponame>michalkoziara/IoT-RESTful-Webservice
import json
import pytest
from app.main.model.user_group import UserGroup
from app.main.repository.user_group_repository import UserGroupRepository
from app.main.util.auth_utils import Auth
from app.main.util.constants import Constants
def test_get_list_of_user_groups_... | StarcoderdataPython |
3280054 | <reponame>AlexandraAlter/tourboxneo
from dataclasses import dataclass
from evdev import UInput, ecodes as e
from pathlib import Path
import serial
import logging
logger = logging.getLogger(__name__)
RELEASE_MASK = 0x80
REVERSE_MASK = 0x40
BUTTON_MASK = ~(RELEASE_MASK | REVERSE_MASK)
UEVENT_PRODUCT = 'PRODUCT=2e3c/574... | StarcoderdataPython |
3299089 | <filename>JumpscaleLibs/tools/markdowndocs/macros/gpdf.py
import re
DOC_INFO_REGEX = r"([a-zA-Z]+)\/d\/([a-zA-Z0-9-_]+)"
def gpdf(doc, link, **kwargs):
"""generate pdf download link from google drive link to document or presentation
:param doc: current document
:type doc: Doc
:param link: full url ... | StarcoderdataPython |
1601111 | '''
Created on 27 Jul 2017
@author: julianporter
'''
import traceback
from numbers import Number
import logging
class OSGridError(Exception):
def __init__(self,message,inner=None):
super(OSGridError,self).__init__()
self.message='OSGridConverter error: {}'.format(message)
self.inner=i... | StarcoderdataPython |
3223790 | import os
from typing import Any
from pydantic import BaseSettings as Settings
from pydantic import EmailStr, validator
from fastapi_mail.schemas import validate_path
from jinja2 import Environment, FileSystemLoader
class ConnectionConfig(Settings):
MAIL_USERNAME: str
MAIL_PASSWORD: str
MAIL_PORT: int = ... | StarcoderdataPython |
177383 | import uasyncio as asyncio
class LedStripController:
def __init__(self, enc, button_pin, fader_pins):
''' enc should be an instance of Encoder.
button_pin is expected to be an instance of machine.Pin.
fader_pins is expected to be an iterable of machine.PWM's.
'''
s... | StarcoderdataPython |
94358 | def save_file(contents):
with open("path_to_save_the_file.wav", 'wb') as f:
f.write(contents)
return "path_to_save_the_file.wav"
| StarcoderdataPython |
179929 | <filename>nematus/settings.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Configuration containers.
"""
import uuid
class DecoderSettings(object):
def __init__(self, parsed_console_arguments=None):
"""
Decoder settings are initialised with default values, unless parsed
console argu... | StarcoderdataPython |
1637926 | <reponame>bjester/project-leda<gh_stars>0
#!/usr/bin/python3
import os
import time
import sys
from argparse import ArgumentParser
from leda import leda, factory, debug
print("Python version " + sys.version)
# RPi cam
cam_period = 5 # in seconds
# Daughter (sensor) board over twi
twi_period = 1 ... | StarcoderdataPython |
3353110 | from discord.ext import commands
import sys
import logging
from interface import DisrapidDb
from helpers import YouTubeHelper
from pythonjsonlogger import jsonlogger
from datetime import datetime
ADMINISTRATOR = 0x00000008
class Disrapid(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init_... | StarcoderdataPython |
3321288 | from model.project import Project
def test_del_project(app, config):
app.session.login("administrator", "root")
app.project.open_project()
if len(app.project.get_project_list()) == 0:
app.project.create()
app.project.fill_form_project(Project(name_project=str("test"), status="stable",
... | StarcoderdataPython |
160590 | <filename>sandcastle/__init__.py<gh_stars>1-10
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
from sandcastle.api import Sandcastle, VolumeSpec, MappedDir # NOQA
from sandcastle.exceptions import ( # NOQA
SandcastleException,
SandcastleTimeoutReached,
SandcastleCommandFai... | StarcoderdataPython |
1680852 | <filename>draft.py<gh_stars>0
from discord import *
import asyncio
import json
import random
from session import DraftSession, DraftState
from errors import *
client: Client = Client()
COMMAND_PREFIX = "!"
SESSIONS = {}
CAPTAINS = {}
DRAFT_CHANNEL_ID = 698678134085779466
GUILD = 599028066991341578
NAIL_BOT_ID = 7046... | StarcoderdataPython |
3230646 | <reponame>danieldeutsch/nlpstats<gh_stars>0
import numpy as np
import numpy.typing as npt
from typing import Callable, List, Sequence, Tuple, Union
def _resample_systems(matrices: List[np.ndarray], **kwargs) -> List[np.ndarray]:
_resample_systems_iv(matrices)
m = matrices[0].shape[0]
rows = np.random.choi... | StarcoderdataPython |
3288879 | <reponame>eleeeeeee/abc<filename>tests/test_plugin_vk.py
import unittest
from streamlink.plugins.vk import VK
class TestPluginVK(unittest.TestCase):
def test_follow_vk_redirect(self):
# should redirect
self.assertEqual(VK.follow_vk_redirect(
"https://vk.com/videos-24136539?z=video-241... | StarcoderdataPython |
3369091 | import json
import os.path as osp
from collections import namedtuple, OrderedDict, defaultdict
from enum import Enum
from numbers import Number
import numpy as np
GitInfo = namedtuple(
'GitInfo',
[
'directory',
'code_diff',
'code_diff_staged',
'commit_hash',
'branch_nam... | StarcoderdataPython |
144342 | <gh_stars>10-100
import base64
import hashlib
from io import BytesIO
import logging
from pathlib import Path
from typing import Dict, Union
import PIL
from django.core.files import File as DjangoFile
import imagehash
try:
from storages.backends.s3boto3 import S3Boto3StorageFile as BotoFile
except ImportError:
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.