id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6661948 | <filename>base/decorators.py<gh_stars>0
import functools
def abstract(f):
@functools.wraps(f)
def abstract(*args, **kwargs):
f(*args, **kwargs)
raise NotImplementedError()
return abstract
| StarcoderdataPython |
4887460 | <filename>tests/cache/test_cache_storage.py<gh_stars>0
import pytest
from chocs_middleware.cache import InMemoryCacheStorage, CollectableInMemoryCacheStorage, ICacheStorage, CacheItem, \
CacheError
def test_can_instantiate() -> None:
# given
instance = InMemoryCacheStorage()
# then
assert isinst... | StarcoderdataPython |
5167340 | """**Concrete implementations of** `torchdatasets.Dataset` **and** `torchdatasets.Iterable`.
Classes below extend and/or make it easier for user to implement common functionalities.
To use standard PyTorch datasets defined by, for example, `torchvision`, you can
use `WrapDataset` or `WrapIterable` like this::
imp... | StarcoderdataPython |
3380518 | <gh_stars>1-10
import pandas as pd
import numpy as np
from pandas_datareader import data as pdr
import yfinance as yf
import datetime as dt
import datetime
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
import math
class ModelAnalysis():
def __init__(self,start_date... | StarcoderdataPython |
3397884 | <reponame>nwestbury/StockAnalyzer<filename>src/sa/__oldbots/basebot.py
#!/usr/bin/env python3
import json
from abc import ABCMeta, abstractmethod
class BaseBot(metaclass=ABCMeta):
"""
Parent class of all python-based bots, it is presumed that
the function "guess" will be defined in all children classes.
... | StarcoderdataPython |
8206 | <reponame>YuraHavrylko/revenuecat_python
from enum import Enum
class SubscriptionPlatform(Enum):
ios = 'ios'
android = 'android'
macos = 'macos'
uikitformac = 'uikitformac'
stripe = 'stripe'
class AttributionNetworkCode(Enum):
apple_search_ads = 0
adjust = 1
apps_flyer = 2
branch... | StarcoderdataPython |
6632785 | <filename>src/api-engine/api/auth.py
import logging
import os
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import authentication
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import AuthenticationFailed
from rest_frame... | StarcoderdataPython |
8160195 | <reponame>chetan201/PVMismatch
# -*- coding: utf-8 -*-
"""
This is the PVMismatch Package. It contains :mod:`~pvmismatch.pvmismatch_lib`
and :mod:`~pvmismatch.pvmismatch_tk`.
:mod:`~pvmismatch.pvmismatch_lib`
=================================
This package contains the basic library modules, methods, classes and
attrib... | StarcoderdataPython |
4852442 | #!/usr/bin/env python
'''
parse a MAVLink protocol XML file and generate a C# implementation
Copyright <NAME> 2018
Released under GNU GPL version 3 or later
'''
import sys, textwrap, os, time, re
from . import mavparse, mavtemplate
t = mavtemplate.MAVTemplate()
enumtypes = {}
map = {
'float... | StarcoderdataPython |
11337617 | <gh_stars>0
from ._BoundingBox3d import *
from ._BoundingBoxes3d import *
| StarcoderdataPython |
3520195 | from .facility_models import * # noqa
# from .infrastructure import * | StarcoderdataPython |
9608676 | <reponame>gruber-sciencelab/MAPP
"""
##############################################################################
#
# Filter the protein-coding set of exons that have valid(long-enough)
# regions around 5/3-splice-site.
#
# AUTHOR: Maciej_Bak
# AFFILIATION: University_of_Basel
# AFFILIATION: Swiss_Institute... | StarcoderdataPython |
9672662 | <reponame>ASH1998/SuZu
from ..logthings import get_module_logger | StarcoderdataPython |
6428937 | import os
import sys
from flask import send_from_directory
curr_path = os.path.dirname(os.path.abspath(__file__))
src_path = os.path.abspath(os.path.join(curr_path, "../"))
def _build_path():
build_path = os.path.join(src_path, 'ui/build/')
if not os.path.exists(build_path):
raise Exception("Client U... | StarcoderdataPython |
11284181 | import numpy as np
from sklearn.base import BaseEstimator
from HTMLParser import HTMLParser
class FeatureMapper:
def __init__(self, features):
self.features = features
def fit(self, X, y=None):
for feature_name, column_name, extractor in self.features:
extractor.fit(X[column_name],... | StarcoderdataPython |
1880543 | <reponame>K-A-R-T/JacMLDash<filename>mldash/web/ui_methods/config.py
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : config.py
# Author : <NAME>
# Email : <EMAIL>
# Date : 09/06/2019
#
# This file is part of JacMLDash.
# Distributed under terms of the MIT license.
import functools
__all__ = ['register_u... | StarcoderdataPython |
1824553 | <filename>src/dsalgo/subsequence_test.py
import unittest
import dsalgo.subsequence
class Test(unittest.TestCase):
def test_count_common_subsequences(self) -> None:
a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
... | StarcoderdataPython |
11262059 | from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from iso8601 import parse_date
@dataclass
class SourceSystem:
"""Class for describing an Argus Source system"""
pk: int = None
name: str = None
type: str = None
user: int = None
base_url: str = ... | StarcoderdataPython |
8063886 | import angr
path_to_bin = "../binaries/02_angr_find_condition"
# Find callback
def good_job(state):
# Get the output of the state
stdout = state.posix.dumps(1)
# If the program echo'ed "Good Job." then we've found a good state
return "Good Job." in str(stdout)
# Avoid callback
def try_again(state):... | StarcoderdataPython |
1730285 | import dis
import opcode
import weakref
import types
import copy
import importlib
def is_class_instance(o):
return bool(type(o).__flags__ & (1 << 9))
def walk_global_ops(code):
for instr in dis.get_instructions(code):
op = instr.opcode
if op in (opcode.opmap['STORE_GLOBAL'], opcode.opmap['DE... | StarcoderdataPython |
6627680 | <gh_stars>1000+
from collections import OrderedDict
from imagededup.methods.hashing import Hashing
from imagededup.handlers.search.bktree import BKTree, BkTreeNode
# Test BkTreeNode
def initialize_for_bktree():
hash_dict = OrderedDict(
{'a': '9', 'b': 'D', 'c': 'A', 'd': 'F', 'e': '2', 'f': '6', 'g': '7... | StarcoderdataPython |
1653769 | <filename>backend/restful_api/urls.py<gh_stars>0
from django.conf.urls import url
from django.urls import include
from rest_framework import routers
from rest_framework_swagger.views import get_swagger_view
from . import views
router = routers.DefaultRouter()
router.register(r'user_attributes', views.UserAttributesVi... | StarcoderdataPython |
1826050 | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: flattrs_test
import flatbuffers
class AllScalars(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsAllScalars(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x =... | StarcoderdataPython |
5137273 | __version__ = "1.0.3"
from .DialogTag import DialogTag | StarcoderdataPython |
6515706 | <reponame>Rob2n/macro_pack
VBA = \
"""
'Create A Text and fill it
' Will overwrite existing file
Private Sub CreateTxtFile(FilePath As String, FileContent As String)
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile(File... | StarcoderdataPython |
4819517 | # Code for "TSM: Temporal Shift Module for Efficient Video Understanding"
# arXiv:1811.08383
# <NAME>*, <NAME>, <NAME>
# {jilin, <EMAIL>, <EMAIL>
import pdb
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import sys
sys.path.append("..")
from archs import repvgg
class TemporalSh... | StarcoderdataPython |
9608629 | <gh_stars>1-10
from conans import ConanFile, CMake, tools, errors
import os, re
from six import StringIO # Python 2 and 3 compatible
def find_all_headers(root):
result = []
entries = os.walk(root)
for entry in entries:
for file in entry[2]:
if file.endswith('.h'):
resul... | StarcoderdataPython |
6476855 | '''
@author: <NAME> (jakpra)
@copyright: Copyright 2020, <NAME>
@license: Apache 2.0
'''
import sys, argparse
from collections import Counter
import json
from tree_st.util import argparse
from tree_st.util.reader import ASTDerivationsReader, AUTODerivationsReader, StaggedDerivationsReader
from tree_st.util.statistics... | StarcoderdataPython |
5144271 | import json
from typing import List, Tuple
import pandas as pd
from softnanotools.logger import Logger
logger = Logger(__name__)
from ..system import System
from ..topology import Topology
from ...generators import Gel
class CoreReader:
def __init__(
self,
particles: dict = None,
topol... | StarcoderdataPython |
128316 | # import pandas, numpy, and matplotlib
import pandas as pd
from feature_engine.encoding import OneHotEncoder
from category_encoders.hashing import HashingEncoder
from sklearn.model_selection import train_test_split
pd.set_option('display.width', 200)
pd.set_option('display.max_columns', 20)
pd.set_option('display.max_r... | StarcoderdataPython |
3594755 | from collections.abc import MutableMapping
from typing import Any
from unittest import TestCase
from .variable import (
IllegalReferenceError,
UndefinedVariableError,
VariableError,
replace,
)
class VariableTest(TestCase):
def test_replace_empty(self) -> None:
self.assertEqual(({}, []), r... | StarcoderdataPython |
11202750 | #! /usr/bin/env python
import logging
import logging.handlers
from autopyfactory.apfexceptions import ThreadRegistryInvalidKind
class ThreadsRegistry(object):
def __init__(self, kinds=['plugin','queue','util','core']):
self.log = logging.getLogger('autopyfactory')
# the kinds of threads allow... | StarcoderdataPython |
53958 |
from django.test import TestCase
from .models import Posts,Location,Category
# Create your tests here.
class locationTest(TestCase):
def setUp(self):
self.new_location = Location(location="nairobi")
def test_instance(self):
self.assertTrue(isinstance(self.new_location,Location))
def tes... | StarcoderdataPython |
4809517 | <reponame>FermentAI/Fermentation-Station
from engine import Subroutine
from pyfoomb import BioprocessModel
import numpy as np
class MyModel(BioprocessModel):
"""
Defines the model class. Always named MyModel. Always inherits from BioprocessModel
Must define rhs(self,t,y) as a system of ODEs.
"""
... | StarcoderdataPython |
55272 | from unittest.mock import patch, MagicMock, PropertyMock
import pytest
from cincoconfig.core import ConfigFormat
from cincoconfig.formats.json import JsonConfigFormat
from cincoconfig.formats.bson import BsonConfigFormat
from cincoconfig.formats.yaml import YamlConfigFormat
from cincoconfig.formats.xml import XmlConfig... | StarcoderdataPython |
225396 | import re
import calendar
import json
import functools
from datetime import datetime
from random import random
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse_urlparse,
compat_urlparse
)
from ..utils import (
bug_reports_message,
ExtractorError,
get_first,
int_or_n... | StarcoderdataPython |
6419495 | <reponame>kahbenya/k8-test-api
from flask import Flask , request
import random
import requests
import json
app = Flask(__name__)
@app.route("/")
def index():
return "Testing 1 1 2 3\n"
@app.route("/create" , methods=['POST'])
def create():
message = request.json['message']
if not message:
return... | StarcoderdataPython |
4991758 | <filename>util/mongoback.py
#encode=utf-8
import os
from config import mongo_back_path
import time
def back_mongo():
path = mongo_back_path+"/"+str(time.time())
command = "mkdir " + path
back_mongo_command = "/usr/bin/mongodump -d ss -o "+path
try:
os.system(command)
os.syste... | StarcoderdataPython |
3519628 | # -*- coding: utf-8 -*-
__author__ = 'minhtule'
from unittest import TestCase
from gap.parameter import *
class TestParameter(TestCase):
def test_value(self):
self.assertTrue(Parameter("key1", "right format", "text"))
self.assertTrue(Parameter("key2", -54.234, "currency"))
self.assertTru... | StarcoderdataPython |
125156 | <filename>btn_cache/api_types.py
# Copyright (c) 2021 AllSeeingEyeTolledEweSew
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDI... | StarcoderdataPython |
9715956 | # tests.test_classifier.test_classification_report
# Tests for the classification report visualizer
#
# Author: <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
# Created: Sun Mar 18 16:57:27 2018 -0400
#
# ID: test_classification_report.py [] <EMAIL> $
"""
Tests for the classification report visualizer
"""
############... | StarcoderdataPython |
6521910 | <reponame>JasonTheDeveloper/Custom-Vision-Autotrainer
from enum import Enum
class Platform(Enum):
DOCKER = "DockerFile"
CORE_ML = "CoreML"
TENSORFLOW = "TensorFlow"
ONNX = "ONNX"
def __str__(self):
return self.value
class Flavour(Enum):
Linux = "Linux"
Windows =... | StarcoderdataPython |
1928667 | # Copyright 2018 The TensorFlow Probability 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
#
# Unless required by applicable law o... | StarcoderdataPython |
8079614 | <gh_stars>1-10
"""Author: <NAME>, Copyright 2019"""
from best_first.caption_utils import Insertion
from abc import ABC, abstractmethod
import numpy as np
class Ordering(ABC):
def __init__(
self,
max_violations=0
):
self.max_violations = max_violations
def get_orderings(... | StarcoderdataPython |
1826642 | from typing import List, Optional
import matplotlib.pyplot as plt
import numpy
from matplotlib.figure import Figure
from tifffile import imread
from hylfm.plot.plotting import turbo_colormap
def plot_img_projections(img: numpy.ndarray, b=0) -> Figure:
assert len(img.shape) == 5 # bczyx
img = img[b]
ass... | StarcoderdataPython |
5180849 | <gh_stars>100-1000
# coding: utf-8
import os
import warnings
from pathlib import Path
from functools import reduce
from itertools import chain
from collections import Counter
import numpy as np
import pandas as pd
import gender_guesser.detector as gender
from sklearn.preprocessing import MultiLabelBinarizer
warnings.... | StarcoderdataPython |
1618215 | <reponame>schlauch/DataFinder
#
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
#
# All rights reserved.
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the follo... | StarcoderdataPython |
3550637 | import os
resultsDir = "./results/"
os.chdir("..")
for filename in os.listdir(resultsDir):
if ".out" in filename:
print(filename)
falsePositives = 0
falseNegatives = 0
trueNegatives = 0
truePositives = 0
tokens = filename.split(".")
labelFileName = tokens[0... | StarcoderdataPython |
8040811 | <gh_stars>0
from ..lib import OpenIncludedFile
import threading
import time
import sys
import os
import webview # pywebview
class WindowManager:
api = None
windows = None
def __init__(self, api):
self.windows = {}
self.api = api
def LaunchWindow(self, window_id, window_title, html_pa... | StarcoderdataPython |
5063612 | <reponame>invenio-toaster/invenio-pidrelations
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Minimal Flask application example.
... | StarcoderdataPython |
4951604 | <gh_stars>0
from model.contact import Contact
from model.group import Group
from fixture.orm import ORMFixture
from random import random
orm = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="")
def test_del_contact_from_group(app, db):
# добавляем группу и контакт, если их нет
if len(... | StarcoderdataPython |
3372414 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import modules.update_data
import modules.update_domaine
| StarcoderdataPython |
237565 | # Smart Instant Pot Evaluation Script
# This will process a CSV file with input images and their expected digit
# detection. Each image will be processed by the detection code and the actual
# result compared to the expected to generate statistics on how well the
# algorithm is working.
import argparse
import csv
impo... | StarcoderdataPython |
8080848 | <filename>tests/unit/utils/test_request_handler.py
# Standard lib imports
from http import client
import unittest
# Third party imports
import requests_mock
# Project level imports
from pywebhooks.utils.request_handler import RequestHandler
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(W... | StarcoderdataPython |
9686513 | print('-=' * 10, '10 termos de uma PA', '-=' * 10)
p = int(input('Primeiro termo: '))
r = int(input('Razão: '))
d = p + (10 - 1) * r
for n in range(p, d + r, r):
print(n, end=' ')
| StarcoderdataPython |
6654345 | <reponame>timclipsham/lmdirect
"""lmdirect connection class."""
import asyncio
import logging
from datetime import datetime, timedelta
from functools import partial
from authlib.integrations.base_client.errors import OAuthError
from authlib.integrations.httpx_client import AsyncOAuth2Client
from .aescipher import AES... | StarcoderdataPython |
3449069 | """
Hello World example
"""
import quasargui
from quasargui import *
def run_program():
layout.notify('Hello, {name}!'.format(
name=input_name.value
))
input_name = QInput(
# # uncomment these lines if you want to display notification message on change:
# value='',
# events={'change': r... | StarcoderdataPython |
34413 | # coding=utf-8
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlVerlichtingstoestelModelnaam(KeuzelijstField):
"""De modelnaam van het verlich... | StarcoderdataPython |
129805 | <gh_stars>0
from turtle import *
from random import randrange
from freegames import square, vector
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
def change(x, y):
"Change snake direction."
aim.x = x
aim.y = y
def inside(head):
"Return True if head inside boundarie... | StarcoderdataPython |
1743844 | #!/usr/bin/env python2
import re
import pprint
import subprocess
descs = {
"double": "Double",
"galvanic_mock": "Galvanic-mock",
"mock_derive": "Mock_Derive",
"mock_it": "Mock-it",
"mockall": "Mockall",
"mockers": "Mockers",
"mockiato": "Mockiato",
"mocktopus": "Mocktopus",
"pseudo... | StarcoderdataPython |
6525502 | <reponame>Pennsieve/timeseries-processor<gh_stars>0
# -*- coding: utf-8 -*-
"""
Modified:
<NAME> (20180423)
Created on Mon Jan 2 12:49:21 2017
setup.py file for pymef3 library
Ing.,Mgr. (MSc.) <NAME>
Biomedical engineering
International Clinical Research Center
St. Anne's University Hospital in Brno
Czech Republic... | StarcoderdataPython |
8014384 | <reponame>NazaninBayati/SCA<gh_stars>0
import understand
import sys
file_list=[]
final_list=[]
file_dependency=[]
file_dependentby=[]
cls_CallPairs=[]
CallPairs=[]
def included_files(db):
for file in sorted(db.ents("File")):
file_dependency.append(list(file.depends()))
def used_by_file(db):
for file ... | StarcoderdataPython |
1864098 | import itertools
import logging
import os
from typing import Collection, List
import click
from exposurescrawler.dbt.exposure import DbtExposure
from exposurescrawler.dbt.manifest import DbtManifest
from exposurescrawler.tableau.graphql_client import (
retrieve_custom_sql,
retrieve_native_sql,
)
from exposure... | StarcoderdataPython |
60716 | TARGET_URL = '/{tail:.*}'
EXCLUDED_HEADERS = {
# 'Accept-CH',
# 'Accept-CH-Lifetime',
# 'Cache-Control',
# 'Content-Encoding',
# 'Content-Security-Policy',
# 'Content-Type',
# 'Date',
# 'Expires',
# 'Last-Modified',
# 'P3P',
# 'Set-Cookie',
'Transfer-Encoding',
'X-Tar... | StarcoderdataPython |
4929907 | <filename>students/k3343/practical_works/Kozyreva_Alena/simple_django_web_project/django_project_kozyreva/project_first_app/migrations/0003_delete_geeksmodel.py
# Generated by Django 3.0.5 on 2020-04-15 16:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('proj... | StarcoderdataPython |
9747679 | <filename>src_assignemnt_2/src2.py
import math
def f():
total = 0
for x in range(1000000):
total += math.sin(x)
return total
print(f())
| StarcoderdataPython |
1952155 | def inside_or_outside(number, lower, upper):
if number >= lower or number < upper:
print("Inside")
else:
print("Outside")
| StarcoderdataPython |
3545124 | Import("env")
import gzip
import os
import sys
'''
try:
from css_html_js_minify import process_single_html_file, process_single_js_file, process_single_css_file, html_minify, js_minify, css_minify
except ImportError:
env.Execute("$PYTHONEXE -m pip install -vvv css_html_js_minify")
from css_html_js_minify imp... | StarcoderdataPython |
11233611 | <reponame>RafayelGardishyan/Memorears
from django.db import models
# Create your models here.
class Theme(models.Model):
name = models.CharField(max_length=255)
description = models.TextField(max_length=1000)
class Image(models.Model):
image = models.ImageField(upload_to="images")
theme = models.Fore... | StarcoderdataPython |
1828055 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 19 2018
@author: kfinc
"""
import pandas as pd
import numpy as np
from sklearn import preprocessing
def motion_24_friston(dataframe):
"""Simple function that calculates 24 motion parameters from pandas dataframe.
Parameters
----------
dataf... | StarcoderdataPython |
3568590 | from .run import run_pipeline
from .data import get_pricing | StarcoderdataPython |
6700321 | class Logger:
def __init__(self):
pass
def log(self, msg):
pass
| StarcoderdataPython |
11317549 | <reponame>RDFLib/PyRDFa
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from xml.dom.minidom import parse, parseString
from datetime import date
def one_entry(term) :
return "\t'%s'\t\t\t: 'http://www.w3.org/1999/xhtml/vocab#%s'," % (term,term)
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeTyp... | StarcoderdataPython |
5091655 | class PhysicalCoordinate(object):
def __init__(self, header):
phys_coord = ""
# check if physical coordinate is defined. FIXME!
for C in ["P", "L"]:
try:
if (header["WCSTY1" + C].strip() == "PHYSICAL") \
and (header["WCSTY2" + C].strip() =... | StarcoderdataPython |
8021302 | <gh_stars>1-10
'''
Core types for the connectivity model of an articulated mechanism.
'''
import logging, enum
import networkx as nx
import io
import kgprim.core as gr
class Joint:
'''
A placeholder for a joint of a mechanism.
A joint only has a name and a kind, the latter being one of the values
de... | StarcoderdataPython |
6610157 |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
"""
Some notations:
d = number of features including W_0
n = number of observations
"""
def prepare_X(X:np.ndarray, degree:int = 1)-> np.ndarray:
'''
Expands X as per degrees and appends a column of ones in ... | StarcoderdataPython |
9638303 | """
You have to write the perc_train function that trains the feature weights using the perceptron algorithm for the CoNLL 2000 chunking task.
Each element of train_data is a (labeled_list, feat_list) pair.
Inside the perceptron training loop:
- Call perc_test to get the tagging based on the current feat_vec a... | StarcoderdataPython |
3486890 | import cv2
import json
from tqdm import tqdm
import pandas as pd
from .bb_polygon import *
def draw_arrow(image, start_point, end_point, color):
start_point = tuple(start_point)
end_point = tuple(end_point)
image = cv2.line(image, start_point, end_point, color, 3)
image = cv2.circle(image, end_point, 8... | StarcoderdataPython |
11322754 | import numpy as np
from theano import gof, tensor
class Minimal(gof.Op):
# TODO : need description for class
# if the Op has any attributes, consider using them in the eq function.
# If two Apply nodes have the same inputs and the ops compare equal...
# then they will be MERGED so they had better ha... | StarcoderdataPython |
3479987 | import asyncio
import functools
import types
import typing as t
from contextlib import suppress
from discord import Member, NotFound
from discord.ext import commands
from discord.ext.commands import Cog, Context
from bot.constants import Channels, DEBUG_MODE, RedirectOutput
from bot.log import get_logger
from bot.uti... | StarcoderdataPython |
11285449 | # coding=utf-8
import argparse
import os
import tensorflow as tf
import tqdm
from feature_extraction.extract_model import ExtractModel
from feature_extraction.data_set import get_testing_set
from model_loader import load_model, save_model
from data_set_args import get_rab_set_args, get_ked_set_args,\
get_bdl_set_... | StarcoderdataPython |
8193434 | <reponame>AronGreen/bpr-uml-shared
from dataclasses import dataclass
from typing import Optional
from .mongo_document_base import MongoDocumentBase
@dataclass
class SomeItem(MongoDocumentBase):
"""
Dummy class for testing.
Represents nothing in the domain.
"""
number: int
text: str
users: ... | StarcoderdataPython |
6416089 | <gh_stars>0
import pytest
from glados import GladosPlugin, RouteType, PluginImporter, BotImporter, GladosBot
from glados.errors import GladosPathExistsError
import logging
from pathlib import Path
import os
PC_BASE_PATH = Path("tests", "plugins_config")
PC1 = Path(PC_BASE_PATH, "TestPlugin1.yaml")
PC2 = Path(PC_BASE_... | StarcoderdataPython |
11284075 | <filename>tests/test_utils_dataset.py
"""Test utils_dataset."""
import tempfile
from pathlib import Path
from dash_charts import utils_dataset
def test_db_connect():
"""Test DBConnect."""
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_dir = Path(tmp_dir)
database = utils_dataset.DBConnec... | StarcoderdataPython |
1827950 | <filename>python-2-apps/fn_proofpoint_block_list/fn_proofpoint_block_list/components/proofpoint_add_to_block_group.py<gh_stars>0
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
"""Function implementation"""
import logging
from resilient_circuits import ResilientComponent, function, handle... | StarcoderdataPython |
1668946 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 19:27:35 2019
@author: debasish
"""
def qrs_detection(ecg,Fs):
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
#=============================================================... | StarcoderdataPython |
6688002 | """
A representation of a ``while`` loop.
"""
from regression_tests.parsers.c_parser.exprs.expression import Expression
from regression_tests.parsers.c_parser.stmts.loop import Loop
from regression_tests.utils import memoize
class WhileLoop(Loop):
"""A representation of a ``while`` loop."""
def is_while... | StarcoderdataPython |
8046089 | #!/usr/bin/env python
import mirheo as mir
dt = 0.001
ranks = (1, 1, 1)
domain = (8, 8, 8)
u = mir.Mirheo(ranks, domain, debug_level=3, log_filename='log')
pv = mir.ParticleVectors.ParticleVector('pv', mass = 1)
ic = mir.InitialConditions.Uniform(number_density=10)
u.registerParticleVector(pv, ic)
dpd = mir.Inte... | StarcoderdataPython |
1918242 | <reponame>mh-globus/globus-sdk-python
from .client import GroupsClient
from .errors import GroupsAPIError
__all__ = ("GroupsClient", "GroupsAPIError")
| StarcoderdataPython |
326574 | <reponame>randomchain/randbeacon<filename>extra_apps/verify.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from pprint import pprint
import click
import merkletools
import sloth
import msgpack
from randbeacon import utils
import ujson as json
SERIALIZED_FIELDS = ('COMMIT', 'PROOF')
def ver... | StarcoderdataPython |
6447576 | <reponame>KaranToor/MA450<filename>google-cloud-sdk/.install/.backup/lib/surface/compute/instance_groups/managed/set_autohealing.py
# Copyright 2015 Google 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.
# Y... | StarcoderdataPython |
1801321 | from django.http import HttpResponse
from django.shortcuts import render
from django.utils.encoding import smart_str
import os, sys, inspect, StringIO, shutil, time, json, base64
current_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
cardiff_path = os.path.join(os.path.dirname(current... | StarcoderdataPython |
9683136 | <gh_stars>0
from macala import MancalaGame
mg = MancalaGame()
while not mg.is_over:
print mg
print "it is player %s's turn" % mg.player_turn
mg.make_move(int(raw_input('> ')))
print mg
p0, p1 = mg.score
if p0 < p1:
print "player 1 wins!"
elif p1 < p0:
print "player 0 wins!"
else:
print "it's a tie!"
| StarcoderdataPython |
6468577 | <gh_stars>0
from django.apps import AppConfig
class DataimportConfig(AppConfig):
name = 'microimprocessing'
| StarcoderdataPython |
4869243 | <gh_stars>0
import os
import pydicom
print("Executando... Por favor aguarde.")
arq = open('dicom.xml', 'w')
texto = []
texto.append("<?xml version=\"1.0\"?>\n")
path = os.getcwd() + '\\Exames de imagem\\'
for r, d, f in os.walk(path):
for file in f:
if '.dcm' in file:
path = str(r) + "\\" + str(file)
tex... | StarcoderdataPython |
6411312 | import scipy, numpy as np
from tick.solver.base import SolverFirstOrderSto as SFOS
from tick.prox.base.prox import Prox as TPROX
from tick.base_model import ModelGeneralizedLinear as TMGL
class DummySolver(SFOS):
def _set_cpp_solver(self, dtype_or_object_with_dtype): return None
def set_epoch_size(self, v): pa... | StarcoderdataPython |
6556884 | import unittest
from typing import List
class Solution:
@staticmethod
def exist(board: List[List[str]], word: str) -> bool:
"""
Given an m x n grid of characters board and a string word, return true if word exists in the
grid.
The word can be constructed from letters of sequen... | StarcoderdataPython |
3529258 | from gevent import monkey
monkey.patch_all()
import discord
import os
from flask import Flask
from flask_compress import Compress
from gevent.pywsgi import WSGIServer
from threading import Thread
client = discord.Client()
def get_role(guild, name):
return discord.utils.get(guild.roles, name=name)
@client.event
a... | StarcoderdataPython |
4971199 | <filename>base/site-packages/jpush/push/__init__.py<gh_stars>100-1000
from .core import Push
from .audience import (
tag,
tag_and,
tag_not,
alias,
registration_id,
segment,
abtest
)
from .payload import (
android,
ios,
winphone,
platform,
cid,
notification,
mess... | StarcoderdataPython |
9705884 | from chess_game_practice.board import make_board, _make_board_empty
from chess_game_practice.pieces.pawn import Pawn
def test_create_pawn():
game_board = make_board()
pawn = Pawn('x', 'y', "b", game_board)
assert "pawn" == pawn.piece_type
assert game_board == pawn.board
assert "b" == pawn.color
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.