id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6582905 | # -*- coding: utf-8 -*-
'''
Copyright (C) 2014 <NAME> <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program... | StarcoderdataPython |
366853 | <reponame>voyagersearch/tasks<gh_stars>1-10
"""
Simple script to test the existance of the spacy module
Called from the java plugin.
"""
import os
import glob
import sys
import platform
# Import required Python libraries required for NLP.
def append_or_set_path(path):
try:
p = os.environ['PATH']
if len(p) >... | StarcoderdataPython |
3463585 | import numpy as np
import pandas as pd
from scipy.special import gammaln
from text_prep import run_preprocess
import string
from gensim.test.utils import common_texts
from gensim.corpora.dictionary import Dictionary
import gensim
from gensim.models import LdaModel
from gensim.test.utils import common_corpus
import matp... | StarcoderdataPython |
8116242 | <gh_stars>1-10
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2008, <NAME> <<EMAIL>>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyrig... | StarcoderdataPython |
9677371 | import pygame
import pygame.draw
import pygame.freetype
import pygame.font
from src.tutorial import environment
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
cell_size = 96, 96
wall_size = 5
map_size = environment.field_length * 96, environment.field_length * 96
p... | StarcoderdataPython |
1871900 | # ===============================================================================
# Copyright 2013 <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/... | StarcoderdataPython |
12864873 | <gh_stars>0
import unittest
from app.models import Article
class ArticleTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Article class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = Article('<NAME>, <NA... | StarcoderdataPython |
11358360 | import hydra
from omegaconf import DictConfig
from popgen.setup import setup_worker, setup_loaders
@hydra.main(config_path="config/config.yaml")
def train(cfg: DictConfig) -> None:
# get the experiment name
name = cfg.get("name", False)
if not name:
raise Exception("Must specify experiment name o... | StarcoderdataPython |
12814617 | <filename>api/user.py
#!/usr/bin/python3
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from models import models
from schema import schemas
from schema.hash import Hash
def create(request: schemas.User, db: Session):
"""
Create a new user
Args:
request (schemas.Us... | StarcoderdataPython |
216062 | from django.shortcuts import render
from . import models
from . import serializers
from rest_framework import viewsets, status, mixins, generics
class ContactReqViewSet(viewsets.ModelViewSet):
"""Manage contact requests in the database"""
serializer_class = serializers.ContactReqSerializer
queryset = mod... | StarcoderdataPython |
9669986 | import json
from tests.integration.integration_test_case import IntegrationTestCase
class TestQuestionnaireEndpointRedirects(IntegrationTestCase):
def test_given_not_complete_questionnaire_when_get_thank_you_then_data_not_deleted(self):
# Given we start a survey
self.launchSurvey('test', 'percen... | StarcoderdataPython |
5167004 | <gh_stars>100-1000
from oauth2_provider.oauth2_backends import OAuthLibCore
from oauth2_provider.settings import oauth2_settings
from .oauth2_endpoints import SocialTokenServer
class KeepRequestCore(oauth2_settings.OAUTH2_BACKEND_CLASS):
"""
Subclass of `oauth2_settings.OAUTH2_BACKEND_CLASS`, used for the sa... | StarcoderdataPython |
8125849 | # -*- coding:
# Project: Linear Regression
import pandas as pd
import numpy as np
import math
import pylab
import statsmodels.api as sm
from statsmodels.formula.api import ols
from sklearn.model_selection import train_test_split
import scipy.stats as spstats
import seaborn as sns
import matplotlib.pyplot as pl... | StarcoderdataPython |
4985238 | from sympy import symbols
from sympy.physics.mechanics import Point, Particle
def test_particle():
m, m2 = symbols('m m2')
P = Point('P')
P2 = Point('P2')
p = Particle('pa', P, m)
assert p.mass == m
assert p.point == P
# Test the mass setter
p.mass = m2
assert p.mass == m2
# Tes... | StarcoderdataPython |
11222215 | import sys
sys.path.insert(0,'./../../..')
from limix.core.cobj import *
from limix.utils.preprocess import regressOut
from limix.core.mean.mean import compute_X1KX2
from limix.core.mean.mean import compute_XYA
import limix.utils.psd_solve as psd_solve
import numpy as np
import scipy.linalg as la
import copy
i... | StarcoderdataPython |
3311081 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def make_qqplot(data, print_plots = True):
'''
Create QQ-plot for each continuous variable in the data
Parameters
-------
data : ndarray, list, dict, or DataFrame
Data to be tested for normality. ALL data must be numeri... | StarcoderdataPython |
11391658 | <filename>blowdrycss/log.py
""" Basic logging configuration utilities.
Allows logging to std.stdout at the console and logging to a file.
"""
# python 2.7
from __future__ import absolute_import, unicode_literals, print_function
# builtins
import logging
import sys
from logging.handlers import RotatingFileHandler
fr... | StarcoderdataPython |
3439836 | from clrnet.utils import Registry, build_from_cfg
import torch
from functools import partial
import numpy as np
import random
from mmcv.parallel import collate
DATASETS = Registry('datasets')
PROCESS = Registry('process')
def build(cfg, registry, default_args=None):
if isinstance(cfg, list):
modules = [... | StarcoderdataPython |
6518561 | <filename>make_thumbnails.py<gh_stars>0
import sys
import os
from glob import glob
from wand.image import Image
THUMBNAILS = 'precinct_tn'
def make_tn(src):
"""
Make a thumbnail from the first page of a PDF documents.
src is the full path to the source PDF doc
THUMBNAILS is the directory to write the ... | StarcoderdataPython |
11320324 | <filename>src/reidentlamp2m.py<gh_stars>1-10
#!/usr/bin/env python
import glob
from pyraf import iraf
from astropy.io import fits
import json
import os
import sys
from shutil import copy2
CWD = os.getcwd()
dbpath = os.path.join(os.path.dirname(sys.argv[0]), '../database')
with open('myfosc.json') as file:
setting... | StarcoderdataPython |
11394599 | <reponame>dexterchan/DailyChallenge
from Jan2020.FullBinaryTree import fullBinaryTree, Node as fNode
from Jan2020.DecodeString import decodeString
from Jan2020.CircleOfChainedWords import chainedWords
from Jan2020.JumpToTheEnd import jumpToEnd
from Jan2020.H_Index import hIndex
from Jan2020.SymmetricKaryTree import is_... | StarcoderdataPython |
264733 | <reponame>allansrc/fuchsia
#!/usr/bin/env python3.8
# Copyright 2021 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Create a Driver Manifest from a list of driver paths"""
import json
import argparse
def main():
p... | StarcoderdataPython |
59094 | <filename>exhibit/catalogue/forms/activity.py
from django import forms
from tempus_dominus.widgets import DatePicker
from ..models import Artwork, Series, Location, Exhibition, WorkInExhibition, ArtworkImage, SaleData
from .utils import PlaceholderMixin
class WorkInExhibitionForm(forms.ModelForm):
class Meta():
... | StarcoderdataPython |
6658602 | <filename>src/quick_sort.py
from random import randint
def out_of_place(sample):
if len(sample) < 2:
return sample
pivot = sample[randint(0, len(sample) - 1)]
less, greater, equal = [[] for _ in range(3)]
for item in sample:
if item < pivot:
less.append(item)
eli... | StarcoderdataPython |
3427675 | <gh_stars>0
# Covid19 mapper
class Mapper:
def map_continent(self, data, continent):
'''
input:
continent - name of continent
data - [{country-daily-record}*], e.g.
{
"dateRep": "12/04/2020",
"day": "12",
"month": "4",
"yea... | StarcoderdataPython |
1902787 | #!/usr/bin/env python
# requires to install python3-gpiozero
# flashes A few leds
print("Loading gpiozero..")
from gpiozero import LED
from time import sleep
led1 = LED(4)
led2 = LED(18)
x = 1
print("Flashing two leds like an alarm..")
while(x < 5):
print(x, "/ 4", "flashing..")
led1.on()
sleep(0.5)
led1.o... | StarcoderdataPython |
8036632 | import builtins
from types import TracebackType
from typing import Any, AsyncIterator, List, Optional, Type
import httpx
from pych_client.base import get_credentials, get_http_params
from pych_client.constants import DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_WRITE_TIMEOUT
from pych_client.exceptions import ClickHouseExce... | StarcoderdataPython |
8015190 | <filename>pylearn2/packaged_dependencies/theano_linear/unshared_conv/unshared_conv.py<gh_stars>0
"""
XXX
"""
from __future__ import print_function
import numpy
from six.moves import xrange
import theano
# Use grad_not_implemented for versions of theano that support it
try:
grad_not_implemented = theano.gradient.... | StarcoderdataPython |
6635648 | <gh_stars>0
"""Create a testing trust map for pkix_web_verify."""
import argparse
import json
from dane_discovery.dane import DANE
parser = argparse.ArgumentParser()
parser.add_argument("--ssid")
parser.add_argument("--dnsname")
parser.add_argument("--aki")
parser.add_argument("--outfile")
parser.add_argument("--cert... | StarcoderdataPython |
72394 | <gh_stars>1-10
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class Parse(Error):
""" Error parsing the program"""
pass
class Output(Error):
""" Error parsing the program"""
pass
class Symbol(Error):
""" Error parsing the program"""
pass
| StarcoderdataPython |
106121 | <reponame>ciex/diary-peter<gh_stars>0
#!/usr/bin/env python
"""Test fixtures and utilities."""
# Copyright 2016 <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.ap... | StarcoderdataPython |
8185781 | import numpy
from ..utils import to_time_series_dataset
from .utils import _set_weights
__author__ = '<NAME> <EMAIL>[at]<EMAIL>'
def euclidean_barycenter(X, weights=None):
"""Standard Euclidean barycenter computed from a set of time series.
Parameters
----------
X : array-like, shape=(n_ts, sz, d)
... | StarcoderdataPython |
6511739 | import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
def load_embedding_model(pt_file, embedding_size):
"""Return an EmbeddingNet model with saved model weights, usable for inference only."""
model = EmbeddingNet(embedding_size)
# Explicitly map CUDA-trained models to CPU ... | StarcoderdataPython |
9683880 | # Generated by Django 3.1.7 on 2021-06-29 22:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('audios', '0002_auto_20210629_1905'),
]
operations = [
migrations.AddField(
model_name='audio',
name='hash_text',
... | StarcoderdataPython |
11242461 | from editdistance import distance
def cer(ref: str, hyp: str) -> float:
"""Calculate CER as in https://github.com/finos/greenkey-asrtoolkit/blob/master/asrtoolkit/wer.py"""
return distance(ref, hyp) / len(ref)
| StarcoderdataPython |
3224027 | <gh_stars>1-10
# Copyright (c) 2013, www.ossph.com and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class ROChecklistItem(Document):
pass
| StarcoderdataPython |
1837959 | <filename>claripy/smtlib_utils.py
import json
import pysmt
from pysmt.shortcuts import Symbol, get_env
from pysmt.smtlib.parser import SmtLibParser, PysmtSyntaxError
def make_pysmt_const_from_type(val, type):
return getattr(pysmt.shortcuts, str(type))(val)
class SMTParser:
def __init__(self, tokens):
... | StarcoderdataPython |
5193804 | <filename>pycloud/pycloud/vm/vmnetx.py
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL ... | StarcoderdataPython |
225877 |
""" game.py: Contains the Game class. """
import random
import pygame.constants as constants
import pygame.time
import pygame.event
import config
from field import *
from generator import *
from omino import *
class Game:
""" The game class which handles the application while in the game. """
de... | StarcoderdataPython |
1914382 | <reponame>merretbuurman/PYHANDLE
'''
This module contains the exceptions that may occur in
libraries interacting with the Handle System (Database).
Author: <NAME>, DKRZ, 2016-2017
'''
from __future__ import absolute_import
class DBHandleNotFoundException(Exception):
''' Raises when handle not found in database... | StarcoderdataPython |
12850684 | from functools import partial
import logging
from typing import Callable, Any, Iterable
from collections import defaultdict
from kombu import Connection
from kombu.mixins import ConsumerMixin
from classic.components import component
from .handlers import MessageHandler, SimpleMessageHandler
from .scheme import Broke... | StarcoderdataPython |
4918847 | <reponame>jsafrane/openlmi-scripts
# Storage Management Providers
#
# Copyright (C) 2014 Red Hat, Inc. 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 reta... | StarcoderdataPython |
1846561 | <filename>building_labeled_paragraphs.py
import random
vocabulary = []
set(clean_books)
# We will be using a dictionary where the author is the key and their work is the value (as a list of tokenized words)
# If you want to do this for multiple texts at once, you can construct a loop as we did. That's why some of... | StarcoderdataPython |
3247452 | <reponame>soskek/XQA<filename>config.py
from os.path import join, expanduser, dirname
"""
Global config options
"""
DATA_DIR = "/data3/private/liujiahua/new/data"
TRANS_DATA_DIR = "/data1/private/liujiahua"
NEW_EN = join(DATA_DIR, "en")
NEW_EN_TRANS_DE = join(TRANS_DATA_DIR, "_wiki_data_en/translate_de")
NEW_EN_TRA... | StarcoderdataPython |
9668599 | <filename>data/examples/sparkour/working-dataframes/src/main/python/csv_to_json.py
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this ... | StarcoderdataPython |
3403758 | """Functions are perfect for separating logic into named chunks"""
def hello():
print("Hello, World!")
hello()
def return_hello():
return "Hello, World!"
print(return_hello())
def hello_name(name="World"):
print(f"Hello, {name}")
hello_name(name="Jake")
hello_name()
def multiply(num1, num2=5):
... | StarcoderdataPython |
255315 | from itertools import permutations
def split_row(row):
tmp = row.split()
sign = 1
if tmp[2] == 'lose':
sign = -1
return (tmp[0], tmp[-1][:-1]), sign * int(tmp[3])
def compute_happiness(seat_arr):
nb_attendees = len(attendees)
return sum(
happiness_rules[(key := (seat_arr[i], ... | StarcoderdataPython |
6651192 | """3.Escreva um programa que exiba o resultado de 2a × 3b, onde a vale 3 e b vale 5"""
a = 3
b = 5
print((2 * a) * (3 * b)) | StarcoderdataPython |
5104058 | from inspect import Parameter, Signature
from typing import Callable, List
from fastapi import Depends, Response
def health(conditions: List[Callable]):
def endpoint(**dependencies):
if all([dependency for dependency in dependencies.values()]):
return Response(status_code=200)
return ... | StarcoderdataPython |
1899349 | <filename>data/data_tool/__init__.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author:1111
# datetime:2019/9/2 15:32
# software: PyCharm
from .triplet_sampler import RandomIdentitySampler
from .bases import BaseImageDataset, BaseDataset
from .dataset_loader import ImageDataset
from .random_erasing import... | StarcoderdataPython |
1881355 | <reponame>swordysrepo/youtube_discord_bot<gh_stars>1-10
# youtube_api.py
import click
from src.command_prompt.cli_command_ch import channel_proc
from src.command_prompt.cli_command_srch import search_proc
from pprint import pprint
@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
if ctx.in... | StarcoderdataPython |
3513049 | from unittest import TestCase
import random
import math
import decimal
from rectpack.guillotine import GuillotineBssfSas
from rectpack.maxrects import MaxRectsBssf
from rectpack.skyline import SkylineMwfWm
from rectpack.packer import PackerBFF, float2dec
def random_rectangle(max_side, min_side):
width = decimal.... | StarcoderdataPython |
92468 | # flake8: noqa
from construct import *
from xbox.sg.utils.struct import XStruct
from xbox.sg.utils.adapters import XEnum, PrefixedBytes
from xbox.nano.enum import AudioCodec
from xbox.nano.adapters import ReferenceTimestampAdapter
fmt = XStruct(
'channels' / Int32ul,
'sample_rate' / Int32ul,
'codec' / XEnu... | StarcoderdataPython |
1897901 | <reponame>connorrunyan1/ragnarok
from django.urls import path
from . import views
urlpatterns = [
path('paypal/create', views.PayPalCreatePaymentViewSet.as_view({
'post': 'create'
}), name='paypal_create'),
path('paypal/execute', views.PayPalExecutePaymentViewSet.as_view({
'get': 'retrieve... | StarcoderdataPython |
296003 | import bsddb3
import sqlite3
import os
import time
import logging
from datetime import datetime
from xclib.utf8 import unutf8
class sq3c_debugger(sqlite3.Connection):
# def execute(self, sql, *args, **kwargs):
# logging.debug('EXECUTE: %s' % sql)
# return super().execute(sql, *args, **kwargs)
def... | StarcoderdataPython |
3206289 | #!/usr/bin/env python3
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
#
# All rights reserved. Use of this source code is governed by a modified BSD
# license that can be found in the LICENSE file.
#import astropy.units as u
#import numpy as np
#import scipy.stats as ss
from ..ABSpopulation import Population
from... | StarcoderdataPython |
1874729 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import csv
import cv2
import multiprocessing
import numpy as np
import os
import struct
import sys
import threading
import time
import yaml
import zmq
class ZMQLogger():
def __init__(self, cfg):
# Decide output path based on datetime
start_datetime = tim... | StarcoderdataPython |
5160835 | # Coded by <NAME>, Lumyo Capstone Group
from __future__ import print_function
import os
from Tkinter import Tk
from tkFileDialog import askdirectory
import pandas as pd
import matplotlib as mpl
from timeit import timeit
class DataAnalyzer():
def __init__(self):
emgData = None
gyroData = No... | StarcoderdataPython |
3375363 | <reponame>pshn111/CMPUT-366
#!/usr/bin/env python
"""
"""
import numpy.random as rnd
def rand_in_range(max): # returns integer, max: integer
return rnd.randint(max)
def rand_un(): # returns floating point
return rnd.uniform()
def rand_norm (mu, sigma): # returns floating point, mu: floating point, sigma:... | StarcoderdataPython |
1791348 | <reponame>catornot/Followed<filename>main.py
import pygame
import sys
from states.intro import Intro
from states.menu import Menu
from states.game import Game
from states.transition import Transition
from states.editor import Editor
from utils import music_manager as Music_Manager
import random
class Main(object):
... | StarcoderdataPython |
11222031 | <reponame>erling6232/imagedata
#!/usr/bin/env python3
# import nose.tools
import unittest
import numpy as np
import copy
# import logging
import pydicom.datadict
from .context import imagedata
from imagedata.series import Series
import imagedata.axis
class TestSeries(unittest.TestCase):
<EMAIL>("skipping test_... | StarcoderdataPython |
6433861 | #!/usr/bin/env python
#TODO inspect bug where n_remnants 1 sets the remnant ratio to 0.5: #DONE
#TODO look into quantiles rather than gaussian errors
#TODO output histograms of the parameters fit during the grid
__author__ = "<NAME>, <NAME>"
__date__ = "25/02/2021"
import numpy as np
import math
import pylab
from m... | StarcoderdataPython |
6619560 | #!/usr/bin/env python3
import sys
import json
cast_files = sys.argv[1:]
t_offset = 0
t_last = 0
entry = [0]
max_idle = 5
for idx, cast_file in enumerate(cast_files):
lines = open(cast_file, 'r').read().split('\n')
meta = lines[0]
data = lines[1:]
if idx == 0:
print(meta)
for entry_raw ... | StarcoderdataPython |
6681908 | from Class.HakAkses import HakAkses
from Database.Orm.UserOrm import UserOrm
from Database.base import sessionFactory
class User:
def __init__(self, username, password, HakAkses):
self.__username = username
self.__password = password
self.__hakAkses = HakAkses
@property
def usern... | StarcoderdataPython |
123687 | <gh_stars>1-10
#!/usr/bin/env python
import SocketServer
import SimpleHTTPServer
import threading
import time
import unittest
from ngcccbase.p2ptrade.comm import HTTPComm, ThreadedComm, CommThread
class MockAgent(object):
def dispatch_message(self, m):
pass
class TestServer(threading.Thread):
def _... | StarcoderdataPython |
225744 | import os
import json
import argparse
from subprocess import call
parser = argparse.ArgumentParser()
parser.add_argument('--num-train-steps', type=int, default=300)
args = parser.parse_args()
annotations_file = os.path.join(os.environ['DATA_DIR'], '_annotations.json')
with open(annotations_file) as f:
annotations_... | StarcoderdataPython |
3235341 | class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
digits = 1
ith = 1
base = 9
while n > digits * base:
n -= digits * base
digits += 1
ith += base
base *= 10
nn = ... | StarcoderdataPython |
9791604 | <reponame>noverde/serpens<gh_stars>1-10
import logging
from functools import wraps
from datetime import datetime, timedelta
cache = {}
logger = logging.getLogger(__name__)
def cached(cache_name, ttl_in_seconds):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
cache_k... | StarcoderdataPython |
5231 | <reponame>mikeboers/Spoon
import sqlalchemy as sa
from ..core import db
class GroupMembership(db.Model):
__tablename__ = 'group_memberships'
__table_args__ = dict(
autoload=True,
extend_existing=True,
)
user = db.relationship('Account',
foreign_keys='GroupMembership.user_id'... | StarcoderdataPython |
9673915 | <reponame>nkrios/deen
import hashlib
from .. import DeenPlugin
class DeenPluginNtlm(DeenPlugin):
name = 'ntlm'
display_name = 'NTLM'
cmd_name = 'ntlm'
cmd_help = 'Hash password with NTLM'
def __init__(self):
super(DeenPluginNtlm, self).__init__()
def process(self, data):
sup... | StarcoderdataPython |
1715388 | <reponame>tekktrik/disbadge
import re
import gc
try:
from typing import Dict
except ImportError:
pass
def _is_alphanumeric(character: str) -> bool:
return re.match("^[a-zA-Z0-9]+$", character)
def _encode_character(character: str) -> str:
if not isinstance(character, str):
raise TypeError(... | StarcoderdataPython |
3244108 | import os
import vtk
import ctk
import qt
import slicer
from EditOptions import HelpButton
import LabelEffect
__all__ = [
'WandEffectOptions',
'WandEffectTool',
'WandEffectLogic',
'WandEffect'
]
#
# This defines the hooks to be come an editor effect.
#
#
# WandEffectOptions - see LabelEffect, EditOptions a... | StarcoderdataPython |
196159 | import time
import cv2
import imutils
import numpy as np
import pyautogui
from imutils.video import WebcamVideoStream
from .finger_tracking import HandDetector
class FingerDetector:
def __init__(self, cam, smooth=9):
self.cam = cam
self.width = 640
self.height = 480
self.screen_s... | StarcoderdataPython |
3278168 | <gh_stars>0
#!/usr/bin/env python
import sys
import json
from powerline.colorscheme import cterm_to_hex
from itertools import groupby
try:
from __builtin__ import unicode
except ImportError:
unicode = str # NOQA
if len(sys.argv) == 1 or sys.argv[1] == '--help':
sys.stderr.write('''
Usage: generate_gradients.py ... | StarcoderdataPython |
198965 | """ Contains the main scripts for training and evaluation.
"""
from tqdm import tqdm
import torch
import torch.nn.functional as F
def train_fn(model, device, data_loader, optimizer, epoch):
"Performs and epoch of training"
# set the model into eval mode
model.train()
# iterate through the training dat... | StarcoderdataPython |
9786526 | import cStringIO
import PIL.Image
from ssim import compute_ssim
def get_ssim_at_quality(photo, quality):
"""Return the ssim for this JPEG image saved at the specified quality"""
ssim_photo = cStringIO.StringIO()
# optimize is omitted here as it doesn't affect
# quality but requires additional memory... | StarcoderdataPython |
8154138 | <gh_stars>1-10
import asyncio
import unittest
from decimal import Decimal
from typing import Dict
from unittest import mock
from bidict import bidict
from yarl import URL
from hummingbot.connector.exchange.binance.binance_api_order_book_data_source import BinanceAPIOrderBookDataSource
from hummingbot.core.mock_api.m... | StarcoderdataPython |
3326307 | <filename>claraw10/clustering.py
from sklearn import datasets
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
import statistics as st
from sklearn.metrics.cluster import adjusted_rand_score
def create_clusters(x,y,numberofclusters):
distance_from_centroid = []
sc... | StarcoderdataPython |
9601767 | <filename>mysite/payment/admin.py
from django.contrib import admin
from .models import Payment, PaymentLine
admin.site.register(Payment)
admin.site.register(PaymentLine)
| StarcoderdataPython |
357917 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 17:13:10 2018
@author: kmykoh97
"""
def main():
ssrLink = getLink(url)
information = decoder(ssrLink)
print(information)
if __name__ == "__main__":
from scrapper import getLink
from ssrDecoder import decoder
# specify the url
... | StarcoderdataPython |
1920101 | # from subtlepatterns.com
bg = """\
<KEY>
"""
| StarcoderdataPython |
3577025 | '''
Library for bin creation
'''
import sys
import json
import os.path
from os import listdir
from os.path import isfile, join
from appConfig import *
from urdmlMiningPartialWindows import *
def getRateBin(rateType):
# Check for rate bin file
if not os.path.isfile(INPUT_RATE_BIN):
print("Rate bin file ... | StarcoderdataPython |
9745995 | <gh_stars>0
import argparse
from src import CNNPreProc, unet
from src import nmf
from src.utils import download_dataset
import train_frcnn_kitti as rcn
def main(args):
parser = argparse.ArgumentParser(description='Execute Elder commands')
parser.add_argument('-model', '--model', default='unet')
# Down... | StarcoderdataPython |
3568780 | import sys
import numpy as np
import math
from copy import copy, deepcopy
import time
from CalcDistPointToCubic import calcDistPointToCubic
class CubicFunction :
def __init__(self, a, b, c, d, lower, upper):
self.a = a
self.b = b
self.c = c
self.d = d
self.domain_lower = lower
... | StarcoderdataPython |
265365 | import molehill
from molehill.utils import build_query
def test_build_query():
ret_sql = f"""\
-- client: molehill/{molehill.__version__}
select
col1
, col2
from
sample_datasets
;
"""
assert build_query(['col1', 'col2'], 'sample_datasets') == ret_sql
def test_build_query_without_semicolon():
ret_s... | StarcoderdataPython |
1778688 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import defaultdict
from copilot.conf import settings
from copilot.api import CopilotClient
from copilot.events.api_models import EventManager
import logging
logger = logging.getLogger('djangocms-copilot')
class Artist(object):
def _... | StarcoderdataPython |
4881581 | <filename>ini/Client_ini.py
# MIT License
#
# Copyright (c) 2022 <NAME> [srccircumflex]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the... | StarcoderdataPython |
3582729 | <reponame>TanJianjun/MyProject
num =111
| StarcoderdataPython |
264543 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import pandas as pd
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # or any {DEBUG, INFO, WARN, ERROR, FATAL}
from tensorflow.keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
import t... | StarcoderdataPython |
1735180 | <filename>flipper_thrift/python/feature_flag_store/constants.py
# Copyright 2018 eShares, Inc. dba Carta, Inc.
#
# 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
#
# https://www.apache.org/l... | StarcoderdataPython |
8022530 | __title__ = "playground"
__author__ = "murlux"
__copyright__ = "Copyright 2019, " + __author__
__credits__ = (__author__, )
__license__ = "MIT"
__email__ = "<EMAIL>"
# Global imports
from typing import Any, Dict, List
from flask import request
# Local imports
from playground.abstract import APIServer, Endpoint
from p... | StarcoderdataPython |
8097058 | <reponame>greghor/realestate-cashflow
##{
import numpy as np
import json
##}
##{
class Scenario():
def __init__(self, scenario_path):
self.scenario_path = scenario_path
self.load_data()
self.check_data()
self.set_attributes()
self.set_downtine_payment()
self.set_m... | StarcoderdataPython |
3546603 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(name='PyWrapOrigin',
version='1.0.0',
description='A python wrapper that simplifies sending data to and plotting in OriginLab from python, and it allows plotting OriginLab graphs without needing a gr... | StarcoderdataPython |
59318 | <filename>tests/test_compatibility.py
"""
This module holds tests for compatibility with other py.test plugins.
Created on Apr 15, 2014
@author: pupssman
"""
from hamcrest import assert_that, contains, has_property
def test_maxfail(report_for):
"""
Check that maxfail generates proper report
"""
rep... | StarcoderdataPython |
3403766 | <filename>py_pdf_term/endtoend/_endtoend/caches/method/nocache.py
from typing import Any, Callable, Dict, List, Union
from py_pdf_term.methods import MethodTermRanking
from py_pdf_term.methods._methods.rankingdata import RankingData
from ...configs import MethodLayerConfig
from .base import BaseMethodLayerDataCache, ... | StarcoderdataPython |
6261 | <filename>DPSparkImplementations/paf_kernels.py
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright (c) 2019 Tealab@SBU"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import numpy as np
import numba as nb
'''
Iterative kernels
'''
def u... | StarcoderdataPython |
12862384 | from ._load_hetrec import load_hetrec_to_df
from ._df2ffm import DF2FFMConverter
from ._utils import load_ffm, save_ffm, load_pickle, save_pickle
| StarcoderdataPython |
1918499 | <filename>batchprocessing/semantic/conceptsEnrichment.py<gh_stars>1-10
# -*- coding: utf-8 -*-
import logging
from typing import Iterable, Dict, Set, Union, Sized
from parsers.semantic.dbpediaClients import EntitiesTypesRetriever, \
LinksCountEntitiesRetriever, EntityCount
from parsers.semantic.model import TextCo... | StarcoderdataPython |
6459992 | '''
Este script define a classe de cada elemento da população
Este arquivo pode ser importado como um módulo utilizando:
from src.models.node import Node
Esta importação é feita apenas dentro da pasta models. Para
alterar esta condição modifique o __init__ que encontra-se
junto a este arquivo.
'''
import numpy as ... | StarcoderdataPython |
5153848 | <gh_stars>0
# Title: Curses Programming Example
# Plot some math functions
# Controls:
# Left/Right arrows, adjust k parameter
# Up/Down arrows, adjust amplitude
# s: sine
# c: cosine
# t: tangent
# h: make it hyperbolic
# q: quit the program
# Author: <NAME>
# We need to impo... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.