id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11205931 | __author__ = '<NAME>'
__license__ = 'MIT'
__version__ = '0.1'
__email__ = 'mail 64 cacodaemon 46 de'
from .OnSelectionModifiedListener import OnSelectionModifiedListener
from .WindowHelper import WindowHelper
from .Utils import Utils | StarcoderdataPython |
8075138 | <filename>exercises/networking_v2/roles/ansible-network.network-engine/lib/network_engine/plugins/__init__.py
# (c) 2018, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# You should have received a copy of the GNU General Public License
# along wit... | StarcoderdataPython |
6595979 | """
--- Day 19: Monster Messages ---
https://adventofcode.com/2020/day/19
"""
from aocd import data
import lark
def solve(rules, messages):
rules = rules.translate(str.maketrans("0123456789", "abcdefghij"))
parser = lark.Lark(rules, start="a")
result = 0
for message in messages.splitlines():
t... | StarcoderdataPython |
9742831 | <gh_stars>1-10
import argparse
import itertools
import numpy as np
from collections import defaultdict
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Calculate scores for candidate cooccurrences using the results of an SVD decomposition')
parser.add_argument('--svdU',required=True,type=str,... | StarcoderdataPython |
5119243 | from helper import *
try:
from flask import Flask
except ImportError as __ex:
print("Install Flask. Exception:", str(__ex))
app = Flask(__name__)
@app.route("/")
def mainpage():
return readFiletoMemory("show.html")
<EMAIL>("/0.png")
#def getimg0():
# return captureScreen()
<EMAIL>("/1.png")
#def ge... | StarcoderdataPython |
3257045 | <gh_stars>10-100
"""
Tests for the :mod:`regression_tests.tools.decompiler_test_settings` module.
"""
import unittest
from regression_tests.test_settings import TestSettings
from regression_tests.tools.decompiler_arguments import DecompilerArguments
from regression_tests.tools.decompiler_runner import DecompilerR... | StarcoderdataPython |
6623172 | import numpy as np
import sklearn as sk
import sklearn.model_selection
from rfc_worker import RFCWorker
from hb_optimizer import HBOptimizer
from metrics import compute_metrics
from koi_dataset import load_koi_dataset
# Set the LOCALHOST, PROJECT_NAME constants
LOCALHOST = '127.0.0.1'
PROJECT_NAME = 'exoplanet-detecti... | StarcoderdataPython |
6437625 | from collections import Counter
def main():
n, k = map(
int,
input().split(),
)
*c, = map(
int,
input().split(),
)
cnt = Counter(c[:k])
mx = len(cnt)
for i in range(k, n):
cnt[c[i]] += 1
x = c[i - k]
cnt[x] -= 1
if cnt[x] == 0: cnt.pop(x)
mx = max(mx, len(cnt))
prin... | StarcoderdataPython |
11331458 | <reponame>ajpmaclean/vtk-examples<gh_stars>10-100
#!/usr/bin/env python
import os
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonTrans... | StarcoderdataPython |
9609949 | <reponame>sndnyang/vat_chainer<gh_stars>0
import numpy as np
from chainer import Variable, cuda
import chainer.functions as cfunc
from dllib.chainer_functions.utils import distance, entropy
from .vat import at_loss, vat_loss
# baseline
XI = 1e-6
def loss_labeled(forward, x, t, args):
y = forward(x, update_batch... | StarcoderdataPython |
8045371 | <reponame>ale-ben/AnimeUnityEngine
from AnimeUnityEngine import logging_aux, common_classes
import json
@logging_aux.logger_wraps()
def get_formatted_search_results(res_obj):
# Per comodità se non è un array lo trasformo in array
if not isinstance(res_obj, type([])):
res_obj = [res_obj]
anime_arr ... | StarcoderdataPython |
1893791 | import web
import energyServer
import datetime
import calendar
import json
urls = ("/", "personalFootprint"
)
class personalFootprint:
def GET(self):
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
start = calendar.timegm(datetime.datetime(2019, 5, 9, 0)... | StarcoderdataPython |
6569715 | <filename>smart/core.py
# -*- coding utf-8 -*-#
# ------------------------------------------------------------------
# Name: core
# Author: liangbaikai
# Date: 2020/12/22
# Desc: there is a python file description
# ------------------------------------------------------------------
import asyncio
impo... | StarcoderdataPython |
1686 | """
Setup DB with example data for tests
"""
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User, Group
from django.core.management.base import BaseCommand
from api import models
class Command(BaseCommand):
help = 'Setup DB with example data for tests'
... | StarcoderdataPython |
6656222 | from enum import Enum
import stringcase
from faker import Faker
from faker_extensions.abstract_providers import WeightedProvider
# https://www.pfma.org.uk/pet-population-2017
class Pets(Enum):
INDOOR_FISH = 1
OUTDOOR_FISH = 2
DOG = 3
CAT = 4
RABBIT = 5
INDOOR_BIRD = 6
REPTILE = 7
DOM... | StarcoderdataPython |
1822265 | <reponame>LocalGround/localground<gh_stars>1-10
from rest_framework import generics
from localground.apps.site.api import serializers, filters
from localground.apps.site.api.views.abstract_views import \
QueryableListCreateAPIView
from localground.apps.site import models
from localground.apps.site.api.permissions i... | StarcoderdataPython |
200126 | # -*- coding: UTF-8 -*-
import unittest
import mock
from taskcat._client_factory import Boto3Cache
class TestBoto3Cache(unittest.TestCase):
@mock.patch("taskcat._client_factory.boto3", autospec=True)
def test_stable_concurrency(self, mock_boto3):
# Sometimes boto fails with KeyErrors under high conc... | StarcoderdataPython |
3210481 | from regresspy.regression import Regression
from regresspy.loss import mae,sse,mse,rmse | StarcoderdataPython |
1770386 | # External Dependencies
import gatt
import queue
import time
import threading
# Internal Dependencies
from pyroot import RootPhy
class RootGATT(RootPhy):
root_identifier_uuid = '48c5d828-ac2a-442d-97a3-0c9822b04979'
def __init__(self, name = None, dev = 'hci0', wait_for_connect = True):
"""Sets up Bl... | StarcoderdataPython |
11338498 | <filename>extractEncodedWord.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import codecs
import os
import re
import sys
# Read and process MS Word documents, converting font encoding into
# Unicode characters.
# https://openpyxl.readthedocs.io/en/default/tutorial.html
... | StarcoderdataPython |
9717583 | import copy
import json
import os
import unittest
from unittest import TestCase
import requests
from mock import MagicMock, Mock, patch
import ingest.exporter.ingestexportservice as ingestexportservice
from ingest.api.dssapi import DssApi
from ingest.api.ingestapi import IngestApi
from ingest.exporter.staging import ... | StarcoderdataPython |
4897913 | <reponame>parampavar/localstack
import io
import logging
import os
import tarfile
import zipfile
from subprocess import Popen
from typing import Optional, Union
from .run import run
from .strings import truncate
LOG = logging.getLogger(__name__)
def is_zip_file(content):
stream = io.BytesIO(content)
return ... | StarcoderdataPython |
328074 | from netifaces import AF_INET, AF_INET6
import netifaces as ni
ip_version = "IPv4"
default_interface = None
default_ip_address_4 = None
default_ip_address_6 = None
# Find the first default interface with an IPv4 and an IPv6 address
interfaces = ni.interfaces()
for interface in interfaces:
if interface.startswith... | StarcoderdataPython |
8029928 | <filename>voiceplay/datasources/lastfm.py<gh_stars>1-10
#-*- coding: utf-8 -*-
""" Last.FM API module with retries and caching """
import datetime
import json
import logging
import random
random.seed()
import sys
import time
from copy import deepcopy
# works after installing `future` package
from queue import Queue ... | StarcoderdataPython |
6572369 | import tuio
import threading
from tuio.objects import Tuio2DCursor
from tuio.objects import Tuio2DObject
class _TuioCallbackListener(tuio.observer.AbstractListener):
"""
Private Helper Class to react on Tuio Events we get from pytuio
Sorry, this is very hackish to get things done...
notify is c... | StarcoderdataPython |
4925738 | <reponame>youaresherlock/PythonPractice
#!usr/bin/python
# -*- coding:utf8 -*-
class Student:
def __init__(self, name):
self.name = name
def __contains__(self, item):
return item.name in self.name
s1 = Student('clarence')
s2 = Student('cla')
print(s2 in s1) # True | StarcoderdataPython |
5066128 | from sklearn.base import TransformerMixin
import pandas as pd
import numpy as np
class DataFrameImputer(TransformerMixin):
def __init__(self):
"""Impute missing values.
Columns of dtype object are imputed with the most frequent value
in column.
Columns of other types are imputed... | StarcoderdataPython |
66877 | <filename>khel_wgs_sc2/workflow/ui.py<gh_stars>0
import time
import datetime
from tkinter import filedialog
from tkinter import *
import re
def progressBar(iterable, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@para... | StarcoderdataPython |
1764629 | import numpy as np
import probtorch
import torch
from torchvision.utils import make_grid
from base import BaseTrainer
from utils import inf_loop, MetricTracker
class Trainer(BaseTrainer):
"""
Trainer class
"""
def __init__(self, model, criterion, metric_ftns, optimizer, config, data_loader,
... | StarcoderdataPython |
3529379 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from sys import argv
from desert import Desert
from desert import box
from desert import bzspl
from desert import circle
from desert import stroke
from desert.color import rgb
from desert.color import white
from desert.color import black
from desert.helpers import filenam... | StarcoderdataPython |
1918474 | """
Saves the command line to a file.
The command then may be repeated and should produce the same output.
"""
from gna.ui import basecmd
import pipes
from packages.env.lib.cwd import update_namespace_cwd
from sys import argv
class cmd(basecmd):
@classmethod
def initparser(cls, parser, env):
parser.a... | StarcoderdataPython |
5101635 | import numpy as np
from sificc_lib import utils
class DataModelQlty():
'''Data model for the features and targets to train SiFi-CC Quality
Neural Network. The training data should be generated seperately
from a trained SiFi-CC Neural Network.
Features R_n*(9*clusters_limit) format: {
clu... | StarcoderdataPython |
5001964 | <filename>pygrank/measures/__init__.py
from pygrank.measures.unsupervised import *
from pygrank.measures.supervised import *
from pygrank.measures.combination import *
from pygrank.measures.multigroup import *
from pygrank.measures.utils import *
| StarcoderdataPython |
11300964 | '''
Test NetDev()
'''
from lnxproc import netdev
from .basetestcase import BaseTestCase
class TestNetDev(BaseTestCase):
'''
Test NetDev class
'''
key = 'NetDev'
module = netdev
def test_netdev(self):
'''
Test normal instantiation
'''
self.generic_test()
| StarcoderdataPython |
1854973 | <reponame>AryaGuo/cadical<filename>synthesis/config.py
class Config:
def __init__(self):
# file paths
self.output_root = '../result'
self.meta_file = '../grammars/bnf.bnf'
self.grammar_file = '../grammars/expr.bnf'
# GP params
self.pop_size = 30
self.depth_li... | StarcoderdataPython |
11275688 | # from mypackage.mypackage import *
| StarcoderdataPython |
6642504 | <gh_stars>1-10
#!/usr/bin/env python3
# Read input
dfs = [int(line) for line in open('01_input.txt', 'r')]
# Part 1
print(f"Part 1: {sum(dfs)}")
# Part 2
f = 0
seen = {f}
found = False
while not found:
for df in dfs:
f += df
if f in seen:
print(f"Part 2: {f}")
found = ... | StarcoderdataPython |
8026608 | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
import csv
import sys
font = {'size': 35}
matplotlib.rc('font', **font)
def cmToInches(cm):
return cm / 2.54
def plot_position_over_time():
csv_data_file = sys.argv[2]
timestamps = []
x_positions = [... | StarcoderdataPython |
3412375 | import datetime
import uuid
import ckan.model as model
from sqlalchemy import Column, MetaData, or_, types
from sqlalchemy.ext.declarative import declarative_base
log = __import__('logging').getLogger(__name__)
Base = declarative_base()
metadata = MetaData()
def make_uuid():
return str(uuid.uuid4())
class Rec... | StarcoderdataPython |
140345 | # Copyright (c) 2021 <NAME>. All rights reserved.
# This code is licensed under Apache 2.0 with Commons Clause license (see LICENSE.md for details)
"""Base class for working with records.
vectorbt works with two different representations of data: matrices and records.
A matrix, in this context, is just an array of o... | StarcoderdataPython |
9600487 | from signal import signal, SIGTERM
from threading import Lock
from readerwriterlock import rwlock
class StrictIndex:
def __init__(self, capacity: int = int(1e5), segmentation_size: int = 25) -> None:
self.lock = rwlock.RWLockFair()
def write(self, batch):
pass
def read(self, bat_size):
... | StarcoderdataPython |
1820953 | <gh_stars>10-100
from polyphony import testbench
def while08(n):
x = 1
y = 2
while True:
#z = y
y = x
x = 5
n -= 1
if n < 0:
break
print(x, y)
return x + y
@testbench
def test():
assert 6 == while08(0)
assert 10 == while08(1)
test()
| StarcoderdataPython |
3492418 | <gh_stars>0
import math
import svgwrite
from pyplot import Point, ShapeFiller
def draw_big_a(d):
paper_centre = Point(102.5, 148)
fontsize = 96*8*0.5
family="Arial"
text = "ﷺ"
ext = d.text_bound(text, fontsize=fontsize, family=family)
text_place = Point(paper_centre.x - ext.width/2, paper_ce... | StarcoderdataPython |
8187149 | <gh_stars>10-100
import torch
def _Add_DifferentChannels(tensorA,tensorB):
_,ac,_,_ = tensorA.shape
_,bc,_,_ = tensorB.shape
if ac == bc:
return tensorA+tensorB
partiralchannels,shorttensor,longtensor = ac,tensorA,tensorB
if bc<ac:
partiralchannels,shorttensor,longten... | StarcoderdataPython |
1617528 | <reponame>yogeshwari-vs/2D-Paramotoring-Pygame
import sys
import multiprocessing
from level_1 import main_level_1
from level_2 import main_level_2
from level_3 import main_level_3
def main():
"""
Runs all 3 levels of the game
"""
volume_button_on_status = main_level_1.main()
main_level... | StarcoderdataPython |
8080476 | <filename>Square/Sqthing.py<gh_stars>0
#!/usr/bin/env python3
from ev3dev.ev3 import *
from time import *
m1 = Motor('outA')
m2 = Motor('outB')
sp = 1000
ts = 250
timeforward = 1.7 #1.7
def moveForward(t):
m1.run_forever(speed_sp = sp)
m2.run_forever(speed_sp = sp)
sleep(t)
def turnRight(t):
m1.run_forever(spee... | StarcoderdataPython |
111324 | <filename>vivareal/vivareal/spiders/vivareal.py
import scrapy,yaml,json
from vivareal.vivareal.items import Anuncio
class vivarealSpider(scrapy.Spider):
name = "vivareal"
allowed_domains = ["glue-api.vivareal.com"]
DOWNLOAD_DELAY = 0.50
def __init__ (self, directory='',params='',*args):
super(vivar... | StarcoderdataPython |
6484252 | # -*- coding: utf-8 -*-
"""
revision.cli
~~~~~~~~~~~~
:copyright: (c) 2018 by SENSY Inc.
:license: MIT, see LICENSE for more details.
"""
from __future__ import absolute_import
import json
import os
import sys
import click
from revision.config import (
DEFAULT_CONFIG_PATH,
DEFAULT_CONFIG_TM... | StarcoderdataPython |
9732369 | from django.contrib.auth import get_user_model
from django.test import TestCase
from rest_framework_jwt.session.session import SessionStore
from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handle... | StarcoderdataPython |
209391 | #!/usr/bin/python3
import threading
import time
import json
import random
from websocket import create_connection
# Ideally fetch the canvas once first and get these
edge = 512
pixels = edge * edge
connections = []
users = 50
target_url = "ws://localhost:3001/ws"
for _ in range(users):
try:
ws = create_connection... | StarcoderdataPython |
1637658 | from discord.ext import commands
import aiohttp, discord, os, traceback, aiosqlite
class SeaWake(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def start(self, *args, **kwargs):
self.session = aiohttp.ClientSession()
self.sus_users = await aiosqlite.connect... | StarcoderdataPython |
6567361 | <reponame>lisa-1010/dkt
# path_names.py
# @author: <NAME>
# @created: Oct 1 2016
#
#===============================================================================
# DESCRIPTION:
#
# Exports path names for files and directories, so paths are consistent across
# modules.
#
#==============================================... | StarcoderdataPython |
236962 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import panflute as pf
is_in_block = None
def inlatex(text: str) -> pf.RawInline:
return pf.RawInline(text=text, format='latex')
def action(elem, doc):
global is_in_block
if isinstance(elem, pf.Header):
ret = list()
if is_in_block... | StarcoderdataPython |
3225283 | # -*- coding: utf-8 -*-
"""Implementation of ProjE."""
from typing import Optional
import numpy
import torch
import torch.autograd
from torch import nn
from ..base import EntityRelationEmbeddingModel
from ...losses import Loss
from ...nn.init import xavier_uniform_
from ...regularizers import Regularizer
from ...tr... | StarcoderdataPython |
1808530 | <reponame>DanielCamachoFonseca/Flask-app-demo<filename>Backend-Frontend/main.py
#Este modulo se encarga de correr la aplicacion, importa el modulo o instancia App
from src.app import app
HOST='localhost'
PORT=4000
DEBUG=True
if(__name__ == '__main__'):
app.run(HOST, PORT, DEBUG) | StarcoderdataPython |
6641255 | <reponame>oolorg/opencenter<filename>tests/test_solver.py<gh_stars>0
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# OpenCenter(TM) is Copyright 2013 by Rackspace US, Inc.
##############################################################################
#
# OpenCenter is licensed under the Apache License, Vers... | StarcoderdataPython |
394480 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Provides all derived/non-derived inputs of to be used later in performance calculations """
from utils import Attribute
__author__ = '<NAME>'
__all__ = ['Constants', 'Attribute']
# working_dir = os.path.dirname(os.path.realpath(__file__))
# TODO consider making use... | StarcoderdataPython |
3277105 | <reponame>XSoyOscar/Algorithms<gh_stars>100-1000
# https://leetcode.com/problems/binary-search/
class Solution:
def search(self, nums, target):
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] < target:
l = mid
elif nums[mid]... | StarcoderdataPython |
3244825 | '''Utility functions for performing fast SVD.'''
import scipy.linalg as linalg
import numpy as np
from EigenPro import utils
def nystrom_kernel_svd(samples, kernel_fn, top_q):
"""Compute top eigensystem of kernel matrix using Nystrom method.
Arguments:
samples: data matrix of shape (n_sample, n_feat... | StarcoderdataPython |
1862995 | sentences1 = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
sentences2 = ["please wait", "continue to fight", "continue to win"]
sentences3 = ["w jrpihe zsyqn l dxchifbxlasaehj", "nmmfrwyl jscqyxk a xfibiooix xolyqfdspkliyejsnksfewbjom",
"xnleojowaxwpyogyrayfgyuzhgtdzr... | StarcoderdataPython |
352967 | <filename>code/data.py
# Converting Exploring data into a script.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.coordinates import SkyCoord
import astropy.units as u
import astropy.coordinates as coord
from dustmaps.bayestar import BayestarQuery
from ... | StarcoderdataPython |
5175523 | from PYB11Generator import *
#-------------------------------------------------------------------------------
# GeometryRegistrar
#-------------------------------------------------------------------------------
@PYB11singleton
class GeometryRegistrar:
# The instance attribute. We expose this as a property of the... | StarcoderdataPython |
291184 | <filename>WeatherCrawler/HausruckWatherProvider.py
#!usr/bin/env python
# -*-coding:utf-8 -*-
from bs4 import BeautifulSoup
from html.parser import HTMLParser
import urllib3
import re
import time
import datetime
import locale
from WeatherData import WeatherData
import subprocess
class HausruckWatherPro... | StarcoderdataPython |
1687097 | # TO DO: implement difficulties and text box
# TO DO: resize sprites using pygame.sprite
# TO DO: implement menu
# TO DO: sound effects
import pygame, sys, os
from pygame.locals import * # @UnusedWildImport
import minesweeper
os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'
# fonts
pygame.font.init()
smallFont = pygame... | StarcoderdataPython |
3483340 | import logging
import os
import sys
import aiohttp
from discord.ext.commands import Bot
from plugins.plugin_manager import PluginManager
TOKEN = os.environ.get('MEIORDEL_TOKEN')
MEI_CHANNEL = os.environ.get("MEIORDEL_CHANNEL")
MEI_VOICE_CHANNEL = os.environ.get("MEIORDEL_VOICE_CHANNEL")
COMMAND_PREFIX = "m!"
DESCRI... | StarcoderdataPython |
6597436 | from tests.system.action.base import BaseActionTestCase
class UserDeleteTemporaryActionTest(BaseActionTestCase):
def test_delete_correct(self) -> None:
self.create_model("meeting/1", {"temporary_user_ids": [111]})
self.create_model(
"user/111", {"username": "username_srtgb123", "meetin... | StarcoderdataPython |
12840379 | <filename>test.py
import _logging as logging
logger = logging.logging()
logger.DEBUG('TEST')
logger.ERROR('TEST')
logger.INFO('TEST')
logger.WARNING('TEST') | StarcoderdataPython |
5163360 | import sys
from datetime import datetime
from string import ascii_letters, digits
from random import choice
class MockOPSigninResponse:
TOKEN_LEN = 43
ERROR_STATUS = 1
SUCCESS_STATUS = 0
ERROR_TEMPLATE = "[ERROR] {} Authentication: DB: 401: Unauthorized\n"
SUCCESS_TEMPLATE = (
"export OP_S... | StarcoderdataPython |
1635053 | # -*- coding: utf-8 -*-
#The MIT License (MIT)
#
#Copyright (c) 2015,2018 <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 limitation the rights
#... | StarcoderdataPython |
13011 | <gh_stars>1-10
#!/usr/bin/env python
'''
This program is free software; you can redistribute it and/or modify
it under the terms of the Revised BSD License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILIT... | StarcoderdataPython |
3550826 | <filename>packages/vaex-server/vaex/server/_version.py
__version_tuple__ = (0, 4, 0, 'dev.0')
__version__ = '0.4.0-dev.0'
| StarcoderdataPython |
3244706 | from django.db.models import Prefetch
from django.shortcuts import get_object_or_404
from rest_framework.generics import RetrieveAPIView, CreateAPIView, ListAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from chat.models import Chat, Message, Profile
from .serializers i... | StarcoderdataPython |
11344067 | """This module contains the electric results class ."""
from ansys.dpf.post.common import _AvailableKeywords
from ansys.dpf.post.scalar import Scalar
from ansys.dpf.post.vector import Vector
class ElectricField(Vector):
"""Defines the temperature object for thermal/electric analysis, that is a scalar object."""
... | StarcoderdataPython |
4869804 | <reponame>crowmurk/mallenom<filename>mallenom/workcal/views.py
import datetime
from django.forms.models import model_to_dict
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse_lazy
from django.views.generic import (
CreateView,
DetailView... | StarcoderdataPython |
8079606 | <filename>certstream_analytics/transformers/base.py
"""
Transform the certificate data from certstream before passing it to the
processing pipeline.
"""
from abc import ABCMeta, abstractmethod
# pylint: disable=no-init,too-few-public-methods
class Transformer:
"""
Define the template of all transformer class.... | StarcoderdataPython |
1946367 | <filename>src/gpyts/syncGpyts/__init__.py
#!/usr/bin/python3
#MIT License
#Copyright (c) 2021 Ripe
import requests, random, json, time, os, io, re
from .. import config, errors
from typing import Union, List
from .. types import Translation, TextToSpeech
class Gpyts():
"""Gpyts is a library for Google translation a... | StarcoderdataPython |
284067 | <filename>KongFuPanda/Classification/KNN/KNN.py
from numpy import *
import operator
class knn:
# KNN-计算,归并,排序
'''
inX:输入向量
dataSet:训练数据集
labels:标签
k:k值
'''
def classify(self, inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX, (dataSetSiz... | StarcoderdataPython |
9697041 | <filename>utils/algo_utils.py
"""Common functions for the algorithms.
"""
__author__ = "<NAME>"
__version__ = "1.0"
from crack.utils.structures import merge_dicts
def init_algos_stats():
records = {
"time": 0,
"operations": 0,
"per_algo": [],
"keys": {},
"levels": [0]
... | StarcoderdataPython |
1969985 | from .doc_cache import DocCache
| StarcoderdataPython |
1837092 | import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
#The Data
#kdd = pd.read_csv('kddcup99_csv', names=kdd_cols)
#kdd_t = pd.read_csv('KDDTest+.txt', names=kdd_cols)
kdd = pd.read_csv('kddcup99_csv.csv')
kdd.head()
#kdd_cols = [kdd.columns[0]] + sorted(list(set(kdd.pr... | StarcoderdataPython |
3277082 | # -*- coding:utf-8 -*-
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractUser, PermissionsMixin
from django.db.models import Model
from django.db.models.fields import (
BigIntegerField, BooleanField, EmailField, BigAutoField, DateTimeField,
CharField, Gener... | StarcoderdataPython |
5115827 | #
# Class for constant active material
#
import pybamm
from .base_active_material import BaseModel
class Constant(BaseModel):
"""Submodel for constant active material
Parameters
----------
param : parameter class
The parameters to use for this submodel
domain : str
The domain of ... | StarcoderdataPython |
11349265 | """Test that names are kept unique in data."""
# --- import -------------------------------------------------------------------------------------
import pytest
import numpy as np
import WrightTools as wt
# --- test ---------------------------------------------------------------------------------------
@pytest... | StarcoderdataPython |
11299868 | # -*- coding: utf-8 -*-
"""Master Controller Service.
This version polls REDIS Events rather than the database directly.
"""
import argparse
import random
import time
from typing import List
import urllib
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
from sip_config_db._events.event import E... | StarcoderdataPython |
6607766 | <reponame>JackKelly/slicedpy
from __future__ import print_function, division
from pda.channel import Channel
from slicedpy.appliance import Appliance
import matplotlib.pyplot as plt
from os import path
DATA_DIR = '/data/mine/domesticPowerData/BellendenRd/wattsUp'
def train_appliance(label, sig_data_filenames):
""... | StarcoderdataPython |
5187242 | # -*- coding: utf-8 -*-
"""生成初始的 kMandarin_8105.txt"""
from merge_unihan import parse_pinyins, code_to_hanzi
def parse_china_x():
with open('tools/china-8105-06062014.txt') as fp:
for line in fp:
line = line.strip()
if line.startswith('#') or not line:
continue
... | StarcoderdataPython |
6692802 | from django.contrib.contenttypes.models import ContentType
from django.core import serializers
from django.db import IntegrityError
import json
from Poem.api.internal_views.utils import one_value_inline, two_value_inline, \
inline_metric_for_db
from Poem.api.views import NotFound
from Poem.helpers.history_helpers... | StarcoderdataPython |
6409283 | <filename>main.py
import sys, random
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
quit = False
range = 15
while not quit:
random_number = random.randint(1,range)
count = 1
number = -1
while number != random_number:
number = input("Go ahead and guess a number b... | StarcoderdataPython |
5129249 | <reponame>paysonwallach/envplus<filename>venn/commands/edit.py<gh_stars>1-10
#
# Venn
#
# Copyright (c) 2019 <NAME>
#
# Released under the terms of the Hippocratic License
# (https://firstdonoharm.dev/version/1/1/license.html)
#
import os
import cleo
import venn.env
from venn import command
class EditCommand(comm... | StarcoderdataPython |
8018659 | <reponame>pytask-dev/pytask-parallel
"""Configure pytask."""
import os
from _pytask.config import hookimpl
from _pytask.shared import get_first_non_none_value
from pytask_parallel.backends import PARALLEL_BACKENDS_DEFAULT
from pytask_parallel.callbacks import delay_callback
from pytask_parallel.callbacks import n_work... | StarcoderdataPython |
13354 | #!/usr/bin/env python
# filename: pair.py
#
# Copyright (c) 2015 <NAME>
# License: The MIT license (http://opensource.org/licenses/MIT)
#
# 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 witho... | StarcoderdataPython |
3265166 | import unittest
import sys
sys.path.append('CS_DOWNLOADER\cs_downloader\downloader')
import daterange_processor as drp
| StarcoderdataPython |
1691357 | from .flatten_params_wrapper import FlatParameter
from .fully_sharded_data_parallel import FullyShardedDataParallel
from .fully_sharded_data_parallel import (
CPUOffload,
BackwardPrefetch,
ShardingStrategy,
MixedPrecision,
FullStateDictConfig,
LocalStateDictConfig,
)
from .fully_sharded_data_par... | StarcoderdataPython |
3267127 | <reponame>lclarko/GDX-Analytics
# See https://github.com/snowplow/snowplow/wiki/Python-Tracker
# and https://github.com/snowplow-proservices/ca.bc.gov-schema-registry
import time
import random
from snowplow_tracker import Subject, Tracker, AsyncEmitter
from snowplow_tracker import SelfDescribingJson
# Set up co... | StarcoderdataPython |
11313840 | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not
# use this file except in compliance with the License. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acco... | StarcoderdataPython |
343972 | <gh_stars>1-10
"""
This module contains methods that model the properties of galaxy cluster
populations.
"""
| StarcoderdataPython |
6561222 | import os
import json
import unittest
from mock import Mock
from dmcontent.content_loader import ContentLoader
from werkzeug.datastructures import MultiDict
from app.presenters.search_presenters import filters_for_lot, set_filter_states
content_loader = ContentLoader('tests/fixtures/content')
content_loader.load_man... | StarcoderdataPython |
307598 | <filename>idea_fare/urls.py<gh_stars>0
import debug_toolbar
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import include, path
from users import views as user_views
from utils.decorators ... | StarcoderdataPython |
6664077 | from django.conf import settings
def get_disabled_features():
"""
Load the disabled features from the settings file
"""
return settings.FEATUREFLAGS_DISABLE | StarcoderdataPython |
6476449 | <gh_stars>1-10
from tkinter import ttk, PhotoImage
from Components.CustomEntry import CustomEntry
from os.path import basename, join
from threading import Thread
class MainPage(ttk.Frame):
def __init__(self: object, parent: object, props: dict) -> ttk.Frame:
super().__init__(parent)
# variables
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.