id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9755246 | <gh_stars>10-100
# @author <NAME>
#
# Copyright (C) 2010 by <NAME>
# Copyright (C) 2011 by <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without li... | StarcoderdataPython |
3591898 | from __future__ import annotations
import pytest
import torch
from torch.utils.data import TensorDataset
from ranzen.torch import prop_random_split
@pytest.fixture(scope="module")
def dummy_ds() -> TensorDataset: # type: ignore[no-any-unimported]
return TensorDataset(torch.randn(100))
@pytest.mark.parametriz... | StarcoderdataPython |
11279068 | <reponame>extroot/yandexLyceumPlus<gh_stars>1-10
from catalog.forms import StarForm
from catalog.models import Category, Item
from django.db.models import Avg, Count
from django.shortcuts import get_object_or_404, redirect, render
from django.views import View
from rating.models import Rating
class ItemListView(Vie... | StarcoderdataPython |
1821957 | <reponame>KnowledgeLinks/rdfframework<filename>rdfframework/datamanager/defmanager.py
import os
import logging
import requests
import urllib
import datetime
import pdb
from dateutil.parser import parse as date_parse
from rdfframework.connections import ConnManager
from rdfframework.datatypes import RdfNsManager
from ... | StarcoderdataPython |
1600981 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 claviering <<EMAIL>>
#
# Distributed under terms of the WTFPL license.
def reduceNum(n):
print '{} = '.format(n),
if not isinstance(n, int) or n <= 0:
print 'input a number'
exit(0)
elif n in [1]:
p... | StarcoderdataPython |
188863 | import socket
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
msgFromServer = "Hello UDP Client"
bytesToSend = msgFromServer.encode()
# Create a datagram socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Bind to address and ip
UDPServerSocket.bind((localIP, loc... | StarcoderdataPython |
11329538 | <filename>rackio_AI/_temporal.py
from easy_deco.del_temp_attr import del_temp_attr, set_to_methods
@set_to_methods(del_temp_attr)
class TemporalMeta:
"""
The Singleton class can be implemented in different ways in Python. Some
possible methods include: base class, decorator, metaclass. We will use the
... | StarcoderdataPython |
11321966 | # testing/assertsql.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
import collections
import contextlib
import re
from .. import event
from ..en... | StarcoderdataPython |
6540565 | <reponame>Natsurii/nicabot-monkee
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Nekozilla 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 ver... | StarcoderdataPython |
5142245 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error #均方误差
from sklearn.metrics import mean_absolute_error #平方绝对误差
from sklearn.metrics... | StarcoderdataPython |
3232072 | from __future__ import print_function
import unittest
from test.test_functions import Example
from typing import Any, List, Optional
from ddt import data, ddt, unpack
from aft import fuzzer
@ddt
class TestFuzzer(unittest.TestCase):
@data(
("add_one", [1], 2, "Test getting a single function"),
(... | StarcoderdataPython |
3392011 | import torch
import torch.nn as nn
import numpy as np
import os
from sklearn.cluster import KMeans
from sklearn.neighbors import KernelDensity
from sklearn.preprocessing import MinMaxScaler
from tqdm import tqdm
from model.model import EncoderRNN, Transformation
from utils.preprocess import MyDataset, get_sliding_data... | StarcoderdataPython |
12818390 | # Copyright (c) 2014, 2015 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | StarcoderdataPython |
392118 | # SPDX-License-Identifier: Apache-2.0
"""
An example console application that uses the subarulink package.
For more details about this api, please refer to the documentation at
https://github.com/G-Two/subarulink
"""
| StarcoderdataPython |
6413877 | # ===================================================================
#
# Copyright (c) 2021, Legrandin <<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:
#
# 1. Redistributions ... | StarcoderdataPython |
8044902 | """
First pass at data centered class.
Ideally a single class instance can handle loading of the entire dataset.
TODO
- Add cache mechanism for quick storage/loading rather than going to synap
- Think of a way to get current feature cols and drug cols from
a subset data, add functionality
"""
import pandas ... | StarcoderdataPython |
9769294 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-20 13:00
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('entertainment_tonight', '0017_auto_20170420_1037'),
]
operations = [
migrations.Rem... | StarcoderdataPython |
9788625 | <reponame>d--j/salt<gh_stars>1-10
# -*- coding: utf-8 -*-
'''
tests.integration.shell.syndic
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:codeauthor: :email:`<NAME> (<EMAIL>)`
:copyright: © 2012-2013 by the SaltStack Team, see AUTHORS for more details
:license: Apache 2.0, see LICENSE for more details.
'''
# I... | StarcoderdataPython |
5019628 | from flask import Flask
app = Flask(__name__)
@app.route('/')
def home_page():
return 'Hello World! <a href="/todo/">Todos</a>'
@app.route('/todo/')
def list_todos():
return 'Todo List <a href="/todo/1">First Todo</a>'
@app.route('/todo/<todo_id>')
def show_todo(todo_id):
return 'ToDo {todo_id}'.form... | StarcoderdataPython |
5174793 | <gh_stars>0
l=2**31
class Solution:
def reverse(s,x):r=(-1)**(x<0)*int(str(abs(x))[::-1]);return r if -l<r<l-1else 0
| StarcoderdataPython |
292175 | <gh_stars>10-100
"""Miscellaneous functions"""
import numpy as np
from numba import jit
from warnings import warn
@jit
def softmax(arr):
"""Scale-robust softmax choice rule."""
arr = np.exp(arr - np.max(arr))
return arr / arr.sum()
@jit
def pessimism(arr, w):
"""Pessimistic learning rule."""
retu... | StarcoderdataPython |
3285802 | <filename>contentcuration/contentcuration/tests/test_authentication.py<gh_stars>0
from __future__ import absolute_import
from .base import BaseTestCase
from contentcuration.utils.policies import check_policies
class AuthenticationTestCase(BaseTestCase):
def setUp(self):
super(AuthenticationTestCase, sel... | StarcoderdataPython |
3403759 | <filename>fastai/vision/learner.py<gh_stars>0
"`Learner` support for computer vision"
from ..torch_core import *
from ..basic_train import *
from ..data import *
from ..layers import *
__all__ = ['ConvLearner', 'create_body', 'create_head', 'num_features']
def create_body(model:Model, cut:Optional[int]=None, body_fn:... | StarcoderdataPython |
4876374 | ###############################################################################
##
## Copyright (C) 2018-2020, New York University.
## All rights reserved.
## Contact: <EMAIL>
##
## This file is part of MLDebugger.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted ... | StarcoderdataPython |
4836775 | <gh_stars>1-10
import pytest
import vtk
from pytestvtk.assert_vtk import assert_vtk
@pytest.fixture
def vtk_string_array1():
result = vtk.vtkStringArray()
result.SetNumberOfTuples(1)
result.SetNumberOfValues(2)
result.SetName('testing_string')
result.SetValue(0, 'Value 0')
result.SetValue(1, ... | StarcoderdataPython |
6563918 | <reponame>jekel/gino
from .api import Gino # NOQA
from .engine import GinoEngine, GinoConnection # NOQA
from .exceptions import * # NOQA
from .strategies import GinoStrategy # NOQA
def create_engine(*args, **kwargs):
from sqlalchemy import create_engine
kwargs.setdefault('strategy', 'gino')
return cr... | StarcoderdataPython |
4816461 | <reponame>memolp/U3M8DLoader
# -*- coding:utf-8 -*-
import u3m8
# cctv6
u3m8_data = u3m8.from_url("http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8")
if u3m8_data:
u3m8.download(u3m8_data.get_ts_urls(), root="http://ivi.bupt.edu.cn/hls/", comb=True)
| StarcoderdataPython |
11267109 | <gh_stars>10-100
'''
Tests for central dogma submodule of reaction module.
'''
from nose.tools import assert_equal, assert_raises
from coral import reaction, DNA, Peptide, RNA
def test_transcription():
test_dna = DNA('ATGATGGGCAGTGTCGAATTAAATCTGCGTGAGACAGAATTGTGTT' +
'TGGGACTACCAGGCGGTGATACAG... | StarcoderdataPython |
6487680 | <reponame>iamovrhere/lpthw<filename>py2/ex1.py
# Inline comment.
"""
Block comment. Albeit also used as documentation blocks, I believe.
"""
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "Well, maybe. I'm probably going to go off script."
print 'Yay! Printing.'
print "I'd much rather you '... | StarcoderdataPython |
5150388 | #!/usr/bin/env python
from pgmpy.utils.mathext import powerset
from pgmpy.base import UndirectedGraph
from pgmpy.models import BayesianModel
from pgmpy.estimators import StructureEstimator, HillClimbSearch, BDeuScore
from pgmpy.independencies import Independencies, IndependenceAssertion
from pgmpy.estimators.CITests im... | StarcoderdataPython |
214008 | <filename>zstats/statstests.py
import unittest
from zstats.stats import *
data0 = [1.0, 2.0, 3.0, 4.0, 5.0]
data2 = [1.0, 2.0, 2.0, 4.0, 5.0]
class TestStats(unittest.TestCase):
def test_zcount(self):
self.assertEqual(zcount(data2), 5)
def test_mean(self):
self.assertEqual(zmean(data0), 3)
... | StarcoderdataPython |
1868952 | """
Created on 25 Aug, 2014
@author: <NAME>
"""
class ContentType(object):
WEB_PAGE = 1
TEXT = 2
IMAGE = 3
LINK = 4
HTML = 5
JSON = 6
TEMPLATE = 9
VALUE_TO_NAME = dict((v,k) for k,v in locals().items() if not k.startswith('_'))
NAME_TO_VALUE = dict((value,key) for key,value in VALUE_TO_NAME.items())
cla... | StarcoderdataPython |
11300292 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import pandas as pd
#import nltk
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection imp... | StarcoderdataPython |
1852574 | # Copyright (c) 2015 <NAME> <<EMAIL>>
from setuptools import setup, find_packages
setup(name='mogul.locale',
version="0.1",
description="""mogul""",
# long_description=open('README.txt').read(),
author='<NAME>',
author_email='<EMAIL>',
url="http://www.sffjunkie.co.uk/python-mogul.html",
li... | StarcoderdataPython |
3561841 | <filename>architecture_tool_django/nodes/urls.py
from django.urls import path
from architecture_tool_django.nodes import views
app_name = "nodes"
urlpatterns = [
path("nodes/", views.NodeListView.as_view(), name="node.list"),
path("nodes/new/", views.newnode, name="node.new"),
path(
"nodes/<str:pk... | StarcoderdataPython |
45377 | class UnshortenerOld():
"""
Todo option selenium ?
"""
def __init__(self,
logger=None,
verbose=True,
maxItemCount=100000000,
maxDataSizeMo=10000,
dataDir=None,
seleniumBrowserCount=20,
... | StarcoderdataPython |
8122012 | <reponame>linuxbender/ai-programming-python
# imports
import argparse
import numpy as np
from PIL import Image
import torch
import json
import torch.nn.functional as F
from torchvision import transforms
from appHelper import gpuSupport, getModelClassifier, getModelSizeFromArch
# app logo
appLogo = """\
... | StarcoderdataPython |
1903426 | <reponame>thinkAmi-sandbox/python_zeep-sample<filename>wsdl_formatter/format_wsdl.py
import pathlib
read_file = pathlib.Path('./wsdl.txt')
with read_file.open(mode='r') as r:
f = r.read()
formatted = f.split(',')
write_file = pathlib.Path('./formatted.txt')
with write_file.open(mode='w') as w:
for f in form... | StarcoderdataPython |
22337 | import torch
import torch.nn.functional as F
from torch.optim import Adam
from torch.utils.data import DataLoader
import torchvision
from torchvision import transforms
from torchvision.models import resnet101
import pytorch_lightning as pl
from model.AEINet import ADDGenerator, MultilevelAttributesEncoder
from model... | StarcoderdataPython |
6635221 | <filename>mvlearn/embed/cca.py
"""Canonical Correlation Analysis"""
# Authors: <NAME>, <NAME>
# License: MIT
import numpy as np
import numbers
from scipy.stats import f, chi2
from sklearn.utils.validation import check_is_fitted
from .mcca import MCCA, _i_mcca, _mcca_gevp
from ..utils import check_Xs, param_as_list
... | StarcoderdataPython |
9695300 | <gh_stars>0
def convert_headers_to_environ(headers):
"""
Converts HTTP headers into WSGI environ variables.
"""
return {
'HTTP_' + key.replace('-', '_').upper(): value.strip()
for key, value in headers.items()
}
| StarcoderdataPython |
259672 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
This is a plugin for the Sublime Text Editor
https://www.sublimetext.com/
Replace all occurences of the currently selected text in the document with an incrementing number.
Some options are provided:
* Start with an offset
* Use fixed number of digits (fill up with lead... | StarcoderdataPython |
316882 | <reponame>hashnfv/hashnfv-daisy<filename>tests/unit/test_libvirt_utils.py
##############################################################################
# Copyright (c) 2017 ZTE Corp and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache Licen... | StarcoderdataPython |
11369475 | <filename>tests/test_population.py
import unittest
# import unittest2 as unittest
import os
from .local_mongo import has_local_mongo
from pychemia.population import LJCluster, RelaxStructures, OrbitalDFTU, NonCollinearMagMoms, RealFunction
def funx2(x):
return x ** 2
class PopulationTest(unittest.TestCase):
... | StarcoderdataPython |
11331163 | <filename>IMU/VTK-6.2.0/ThirdParty/Twisted/twisted/words/topfiles/setup.py
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
try:
from twisted.python import dist
except ImportError:
raise SystemExit("twisted.python.dist module not found. Make sure you "
"have ... | StarcoderdataPython |
9659303 | """Miscellaneous routines."""
from __future__ import annotations
import json
import logging
from typing import Any, Callable, Iterable, Mapping, Set, TypeVar, cast
import requests
from ghaudit.auth import AuthDriver
GITHUB_GRAPHQL_DEFAULT_ENDPOINT = "https://api.github.com/graphql"
# pylint: disable=too-few-publ... | StarcoderdataPython |
3232163 | import numpy as np
import torch
from .data import torch2np
from PIL import Image
def colorize(mask: torch.Tensor, palette: list):
"""
"""
_mask = torch2np(mask, squeeze=True)
_mask = Image.fromarray(_mask.astype(np.uint8)).convert('P')
_mask.putpalette(palette)
return np.array(_mask.convert(... | StarcoderdataPython |
1904156 | <filename>tests/test_clean.py
import pytest
from pyspark.sql import types as T
from delta_utils.clean import fix_invalid_column_names, flatten
def test_fix_invalid_col_names(spark):
spark.conf.set("spark.sql.caseSensitive", "true")
schema = T.StructType(
[
T.StructField("id", T.StringTyp... | StarcoderdataPython |
6532931 | <gh_stars>0
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A, B):
end = -1
count = 0
for i in range(len(A)):
if A[i] > end:
count += 1
end = B[i]
return count
| StarcoderdataPython |
324820 | <filename>various_responses/various_response_app.py<gh_stars>0
import pathlib
import json
from io import StringIO
import csv
from urllib.parse import quote
from werkzeug.exceptions import HTTPException
from werkzeug.routing import Map, Rule
from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import Shar... | StarcoderdataPython |
112157 | <filename>tests/test_formparsers.py
import os
from starlette.formparsers import UploadFile
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
class ForceMultipartDict(dict):
def __bool__(self):
return True
# FORCE_MULTIPART is... | StarcoderdataPython |
4859808 | """A system wide device which can be defined in the main config."""
import abc
import asyncio
from mpf.core.device import Device
class SystemWideDevice(Device, metaclass=abc.ABCMeta):
"""A system wide device which can be defined in the main config."""
__slots__ = []
@asyncio.coroutine
def device_a... | StarcoderdataPython |
1953983 | from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
from ckeditor_uploader.fields import RichTextUploadingField
class Staff(models.Model):
username = models.CharField(max_length=50,null=True)
user = models.OneToOneField(User,on_delete=models.CASCADE,n... | StarcoderdataPython |
3449515 | <reponame>PacktPublishing/Python-Machine-Learning-By-Example-Second-Edition
'''
Source codes for Python Machine Learning By Example 2nd Edition (Packt Publishing)
Chapter 3: Mining the 20 Newsgroups Dataset with Clustering and Topic Modeling Algorithms
Author: Yuxi (<NAME>
'''
from sklearn import datasets
iris = data... | StarcoderdataPython |
134693 | #!/usr/bin/env python
import sctp
import binascii
import sys, socket
import time, IPy
from itertools import repeat
#for local testing: sudo ncat --sctp -l -p 36422
#interface 3GPP S1-MME
#verify that the following modules are loaded
#sudo insmod /lib/modules/3.6.11-4.fc16.i686/kernel/lib/libcrc32c.ko
#sudo insmod /l... | StarcoderdataPython |
4952681 | <reponame>khilnani/badspider.py
#!/usr/bin/env python
import sys
import re
import os
import json
from distutils.dir_util import mkpath
import argparse
import urllib2
import requests
from urlparse import urlparse
from mimetypes import guess_extension
import time
"""
./spidey.py \
-d test \
-f 'www.google.com' \
-u... | StarcoderdataPython |
3551272 | import numpy as np
from scipy.ndimage import gaussian_filter
import torch
import torch.nn as nn
class ListModule(nn.Module):
def __init__(self, *args):
super(ListModule, self).__init__()
idx = 0
for module in args:
self.add_module(str(idx), module)
idx += 1
de... | StarcoderdataPython |
8014566 | import torch
import numpy as np
from matplotlib import gridspec
import matplotlib.pyplot as plt
from metrics import *
def plot_metrics(histories):
""" given a dictionary with info about specific metrics, plot them with matplotlib """
# define some lists that will be the concatenation of every metric ... | StarcoderdataPython |
1933223 | <filename>tests/components/tts/test_init.py<gh_stars>1-10
"""The tests for the TTS component."""
import pytest
import yarl
from homeassistant.components.demo.tts import DemoProvider
from homeassistant.components.media_player.const import (
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
DOMAIN as DOMAIN_MP... | StarcoderdataPython |
4881004 | import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
import seaborn as sns
#---------------------------------------------------------
fd_out='./out/a00_tumor_01_plt-case'
f_in='./out/a00_tumor_00_clean/data_case.csv'
#--------------------------------------------------------
Path(fd_out).mkdir(... | StarcoderdataPython |
11390933 | from celery import Celery
from textblob import TextBlob
app = Celery('tasks', backend='amqp', broker='amqp://guest@localhost//')
@app.task
def sentiment(row):
blob = TextBlob(row[3]) # tweet text
return row[0], blob.sentiment.polarity
| StarcoderdataPython |
4892464 | # -*- coding:utf-8 -*-
# UerMiniAPP的路由
from flask import request
from app import app
from . import database
import pymysql
import json
@app.route('/signIn', methods=['POST', 'GET'])
def signIn():
'''登陆'''
db, cursor = database.connect_mysql()
# 获取json数据
uid = request.args.get("UID")
upswd = requ... | StarcoderdataPython |
6654953 | # -*- coding: utf-8 -*-
"""
colMulti.py
Author: SMFSW
Copyright (c) 2016-2021 SMFSW
"""
from colorConv import *
from colorConvTemperature import TEMPtoYxy
from CIEobs import * # CIE parameters class
from colRGB import ColRGB
from colRGBW import ColRGBW
from colRGBDim import ColRGBDim
from colHSL import ColHS... | StarcoderdataPython |
5048065 | <gh_stars>0
import pytest
import numpy as np
import torch
import random
import gym
from gym.envs.registration import register, registry
from tests.fixtures.net.a2c import net
from prop.algorithms.a2c import Agent
@pytest.fixture
def agent(net):
env_id = 'TestEnv-v0'
if env_id not in [spec.id for spec in regis... | StarcoderdataPython |
5111884 | from django.db import models
class Author(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Illustrator(models.Model):
first_name = models.CharField(max_length=255)... | StarcoderdataPython |
9680558 | <reponame>Rapen/RapSocket
from RapSocket import RapSocket
socket = RapSocket()
socket.connect('http://localhost', 1234)
| StarcoderdataPython |
5007503 | # Generated by Django 4.0.3 on 2022-03-29 11:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0008_homepage_banners'),
]
operations = [
migrations.AddField(
model_name='homepage',
name='featured_article... | StarcoderdataPython |
4968390 | <filename>examples/avro/py/simulate_cc.py
# BEGIN_COPYRIGHT
#
# Copyright 2009-2018 CRS4.
#
# 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
#
# Un... | StarcoderdataPython |
5030628 | <reponame>natcap/opal
import os
import json
import hashlib
import logging
from types import UnicodeType
from types import DictType
import multiprocessing
import shutil
import random
import tempfile
import sys
import distutils.sysconfig
import zipfile
from osgeo import gdal
from osgeo import ogr
from natcap.invest.sdr ... | StarcoderdataPython |
6688341 | i = 0
while i < 10:
i = i + 1
if (i > 5):
break
print i
| StarcoderdataPython |
11206556 | <gh_stars>1-10
x = y = 1
print x
print y
print x + y
y = 3.8
x = 4.2
print x + y
x = 1/2
print 4**x
| StarcoderdataPython |
1986290 | <filename>visual/static_plot.py
"""This script creates a simple static plot of data from the DtssHost via a DtsClient."""
import sys
import os
from tempfile import NamedTemporaryFile
import logging
from shyft.time_series import DtsClient, UtcPeriod, Calendar, TsVector, utctime_now, TimeSeries
from bokeh.plotting impor... | StarcoderdataPython |
8174699 | from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_published = models.BooleanField(default=False)
title = models.CharField(max_length=100, unique=Tr... | StarcoderdataPython |
3246896 | def done_or_not(board): #board[i][j]
for row in range(0,len(board)):
if len(set(board[row]))!=9:
return 'Try again!'
temp=[]
for row in range(0,9):
for col in range(0,9):
temp.append(board[col][row])
if len(set(temp))!=9:
return 'Try again!'
... | StarcoderdataPython |
9681753 | from abc import ABC, abstractmethod
class ICriteriaPayload(ABC):
@abstractmethod
def getPagination(self) -> dict:
pass
@abstractmethod
def getFilter(self) -> dict:
pass
@abstractmethod
def getSort(self) -> dict:
pass
@abstractmethod
def getCurrentUrl(self) -... | StarcoderdataPython |
6672858 | <reponame>zduguid/slocum-nav
# micron_plotter.py
#
# Plotting utilities for Micron Sonar
# 2020-05-22 <EMAIL> initial implementation
import math
import datetime
import numpy as np
import utm
import pandas as pd
import seaborn as sns
import earthpy.plot as ep
import matplotlib.cm as cm
import matplotlib.p... | StarcoderdataPython |
4877862 | """
Construction site -- a place for incrementally complex modules that buildup to
something we actually want.
There's a package for it so we can have it available for demo/tutorial purposes later.
"""
| StarcoderdataPython |
254820 | import pygame
from enum import EnumMeta
class ControlType(EnumMeta):
KEYBOARD = "ControlType.KEYBOARD"
BUTTON = "ControlType.BUTTON"
HAT = "ControlType.HAT"
AXIS = "ControlType.AXIS"
class Control:
def __init__(self, control_type, number, value):
self.control_type = control_type
se... | StarcoderdataPython |
5151724 | # Copyright 2013 Devsim LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | StarcoderdataPython |
40700 | <gh_stars>0
def remove_duplicated_keep_order(value_in_tuple):
new_tuple = []
for i in value_in_tuple:
if not (i in new_tuple):
new_tuple.append(i)
return new_tuple
# return tuple(set(value_in_tuple))
| StarcoderdataPython |
8079437 | <gh_stars>0
from flask import jsonify, request, make_response
from flask_restful import Resource
from flask_expects_json import expects_json
from werkzeug.security import generate_password_hash, check_password_hash
from instance.config import app_config
import datetime
import jwt
from ..utils.user_validations import U... | StarcoderdataPython |
12863983 | from marshmallow import Schema, fields, validate
class ChangePasswordSchema(Schema):
id = fields.Number(attribute="id")
oldPassword = fields.String(attribute="old_password", validate=validate.Length(min=8, max=256), required=True)
password = fields.String(attribute="password", validate=validate.Length(min... | StarcoderdataPython |
6409802 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import NeuralLayer
class RevealDimension(NeuralLayer):
"""
Operation for revealing dimension.
After some dimension-unclear layers such as convolution, the dimension information will be lost.
Use this layer to redefine the input dimension.
"""
... | StarcoderdataPython |
11339392 | <filename>DataObjects/Architecture/ArchitectureClassification.py
# Copyright (c) 2021. <NAME>
# Copyright (c) 2021. University of Edinburgh
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met... | StarcoderdataPython |
327861 | <reponame>asidwell/parcellation_fragmenter
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 15:31:06 2016
@author: kristianeschenburg
"""
import networkx as nx
import numpy as np
class SurfaceAdjacency(object):
"""
Class to generate an adjacency list of a surface mesh representation
of the brain.
... | StarcoderdataPython |
12827847 | <reponame>ovs-code/HRNet-Human-Pose-Estimation
from . import config, core, models, utils
| StarcoderdataPython |
12832401 | <reponame>crschmidt/crapssim
from sim import TABLE_MIN
def place_6_8(player, point):
if not 'place-6' in player.current_bets:
player.bet('place-6', 18)
if not 'place-8' in player.current_bets:
player.bet('place-8', 18)
def place_inside(player, point):
for i in [6, 8]:
if not 'place... | StarcoderdataPython |
11340477 | <reponame>IDEHCO3/kanban-backend
import requests, os, sys
#se'rvidor = ''
#servidor = 'http://LUC00557347.ibge.gov.br/'
SERVER = 'http://LUC00557196:8000/'
#SERVER = "http://172.30.11.72:8000/"
class RequestTest():
def __init__(self, uri, expec_status_code, method='GET', default_server=SERVER):
self.method... | StarcoderdataPython |
9629612 | import random
import unittest
import uuid
from collections import defaultdict
from pathlib import Path
from typing import List
import numpy as np
from mapel.main.features.common import extract_selected_coordinates_from_experiment, extract_selected_distances, \
extract_calculated_distances, MockExperiment
from map... | StarcoderdataPython |
6401795 | from flyplanner import geom
class City:
def __init__(self, name: str, center: geom.Point):
self.name = name
self.center = center
class Cities:
def __init__(self, cities: set[City]):
self.cities = cities
| StarcoderdataPython |
68161 | # -*- coding: utf-8 -*-
import pytest
from mtpylon import long, int128
from mtpylon.messages import UnencryptedMessage, EncryptedMessage
from mtpylon.serialization import CallableFunc
from mtpylon.message_handler.strategies.utils import (
is_unencrypted_message,
is_rpc_call_message,
is_container_message,
... | StarcoderdataPython |
9618468 | import setuptools
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
requirements = []
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setuptools.setup(
name='chatzy.py',
version='0.0.1',
description='A chatzy interface in Python',
long_descr... | StarcoderdataPython |
11352170 | <filename>test/test_integration_text_to_speech_v1.py<gh_stars>1-10
import pytest
import unittest
import watson_developer_cloud
import os
@pytest.mark.skip("These are destructive, so run them manually")
class TestIntegrationTextToSpeechV1(unittest.TestCase):
def setUp(self):
self.text_to_speech = watson_de... | StarcoderdataPython |
6555097 | import os
import sys
import unittest
import numpy as np
sys.path.append(os.path.abspath("../src"))
import utility as ut
class TestUtility(unittest.TestCase):
def test_complex_matrix(self):
a = 5
b = 10
n = np.random.default_rng().integers(low = 1, high = 10)
self.assertEqual(ut.complex_matrix(n, a, b).shap... | StarcoderdataPython |
1883678 | from typing import List
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import automation
from esphome.components import mqtt
from esphome.const import (
CONF_ID,
CONF_ON_VALUE,
CONF_OPTION,
CONF_TRIGGER_ID,
CONF_MQTT_ID,
CONF_CYCLE,
CONF_MODE,
CONF_OPERA... | StarcoderdataPython |
6669297 | import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from image import SuspiciousImage
from base import BaseDetectorMachine, BaseFeatureExtractor, DrawFlags
class NoiseFeatureExtractor(BaseFeatureExtractor):
"""
Parameters
----------
size : int, (default=256)
Length of one side... | StarcoderdataPython |
1922847 | <gh_stars>0
from flask import Flask, render_template, request, abort
import logging
import os
import sched
import yaml
import sys
from datetime import datetime, timedelta
from asset_manager import Spreadsheet, AssetFolder, authenticate_gdrive
app = Flask(__name__)
# load configuration
with open('config.yaml', 'r') as... | StarcoderdataPython |
3222382 | type(Key.F4, KeyModifier.ALT)
exit(0) | StarcoderdataPython |
9789896 | #!/usr/bin/env python
"""
untangle
Converts xml to python objects.
The only method you need to call is parse()
Partially inspired by xml2obj
(http://code.activestate.com/recipes/149368-xml2obj/)
Author: <NAME> (http://0chris.com)
License: MIT License - http://www.opensource.org/licenses/mit-license.php
"""
... | StarcoderdataPython |
8059362 | <filename>sweetpea/core/__init__.py
"""This module provides the fundamental functionality needed for SweetPea to
actually *do* anything. Primarily, this involves handling data representation
and making calls to external utilities for solving logic problems via
SAT-solving.
Data Representation
===================
Swe... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.