id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1643240
<reponame>angry-tony/cmdb-ralph<filename>src/ralph/attachments/forms.py from django import forms from ralph.admin.helpers import get_content_type_for_model from ralph.attachments.models import Attachment, AttachmentItem from ralph.lib.mixins.forms import RequestModelForm class ChangeAttachmentWidget(forms.ClearableF...
StarcoderdataPython
1769485
<reponame>JohnyTheCarrot/GearBot import discord from discord.ext import commands class AntiRaid: def __init__(self, bot): self.bot: commands.Bot = bot async def sound_the_alarm(self, guild): print("alarm triggered!") pass async def on_member_join(self, member: discord.Member): ...
StarcoderdataPython
1624599
<filename>restartservice.py from contextlib import closing import json import logging import time from datehelper import DateHelper from dockermon import DockerMon, DockermonError from sys import version_info from notifyable import Notifyable if version_info[:2] < (3, 0): from httplib import NO_CONTENT as HTTP_N...
StarcoderdataPython
110869
<gh_stars>0 print('=ˆ= ' * 8) print(' TAULA DE MULTIPLICACIÓ') print('=ˆ= ' * 8) num = int(input('introduïu un número per trobar\nla taula de multiplicació: ')) print(' ' * 7, '-' * 13) x = 1 for c in range(1, 11): print(' ' * 7, '{} x {:2} = {:3}'.format(num, x, num*x)) x += 1 print(' ' * 7, '-' * 13)
StarcoderdataPython
3267990
# (C) Copyright 2018-2021 Enthought, Inc., Austin, TX # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in LICENSE.txt and may be redistributed only under # the conditions described in the aforementioned license. The license # is also available online at...
StarcoderdataPython
3336401
# -*- coding: utf-8 -*- from __future__ import absolute_import, division import ndef import pytest import _test_record_base def pytest_generate_tests(metafunc): _test_record_base.generate_tests(metafunc) class TestUriRecord(_test_record_base._TestRecordBase): RECORD = ndef.uri.UriRecord ATTRIB = "iri,...
StarcoderdataPython
3351147
import datetime import enum import logging import chardet import tqdm import subprocess import re import sys import dataclasses from typing import List, Set, Tuple, Optional, Any from modification import Modification from javadoc_analyzer import has_java_javadoc_changed _commit_line = re.compile(r'^commit ([0-9a-f]{...
StarcoderdataPython
155786
#!/usr/bin/env python3 # Copyright 2019 <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 ...
StarcoderdataPython
1723447
# -*- coding: utf-8 -*- from rest_framework.serializers import ( ModelSerializer, Serializer, IntegerField, DurationField) from button.models import Clear class ClearSerializer(ModelSerializer): class Meta: model = Clear read_only_fields = ('id', 'user', 'date',) class MyStatsSerializer(Ser...
StarcoderdataPython
71977
<reponame>adabutch/account_tracker # Generated by Django 3.0.3 on 2020-02-13 19:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account_request', '0013_auto_20190603_1712'), ] operations = [ migrations.AlterField( model_n...
StarcoderdataPython
137457
""" Classes for visualizing echo data """ import numpy as np import matplotlib.colors as colors # import datetime as dt from matplotlib.dates import date2num from collections import defaultdict import echopype_model # Colormap: multi-frequency availability from Jech & Michaels 2006 MF_COLORS = np.array([[0,0,0],\ ...
StarcoderdataPython
161203
<reponame>mavabene/ROAR from pydantic import BaseModel, Field from ROAR.control_module.controller import Controller from ROAR.utilities_module.vehicle_models import VehicleControl, Vehicle from ROAR.utilities_module.data_structures_models import Transform, Location from collections import deque import numpy as np imp...
StarcoderdataPython
3288919
<gh_stars>10-100 """Define Snow Category Item.""" import logging class SnowCatalogItem(object): """ServiceNow Category Item.""" def __init__(self, name, description, conf): """Initialize.""" self.name = name # terraform catalog sys_id self.catalog = conf.get("SERVICENOW", "TF...
StarcoderdataPython
1742212
import FWCore.ParameterSet.Config as cms EcalTrivialConditionRetriever = cms.ESSource("EcalTrivialConditionRetriever", TotLumi = cms.untracked.double(0.0), InstLumi = cms.untracked.double(0.0), producedEcalChannelStatus = cms.untracked.bool(True), producedEcalDQMTowerStatus = cms.untracked.bool(True), ...
StarcoderdataPython
1778055
<gh_stars>0 """ Sage Intacct charge card accounts """ from typing import Dict from .api_base import ApiBase class ChargeCardAccounts(ApiBase): """Class for Charge Card Accounts APIs.""" def __init__(self): super().__init__(dimension='CREDITCARD')
StarcoderdataPython
6838
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.mail import EmailMessage from django.conf import settings from django.template.loader imp...
StarcoderdataPython
1765280
<reponame>sepidehpouyan/SCF-MSP430 from scfmsp.controlflowanalysis.AbstractInstruction import AbstractInstruction from scfmsp.controlflowanalysis.ExecutionPoint import ExecutionPoint class AbstractInstructionControlFlow(AbstractInstruction): def __init__(self, function): super(AbstractInstructionCon...
StarcoderdataPython
1793825
import json import os import sys from colorama import Fore, Back, Style class ConfigFieldMissing(Exception): pass class Config(dict): def checkField( self, name, default=None, hasDefault=False, valuesList=None): if default is not None: hasDefault = True if name in self: ...
StarcoderdataPython
114438
@(lambda: [lambda x: x][0])() def foo(): <caret>
StarcoderdataPython
142083
<gh_stars>0 from .asset import Asset, AssetCurrency from .assetPricing import AssetPricing, AssetPricingQuotes, AssetPricingParametrized from .assetOperation import AssetOperation, AssetOperationType from .quote import Quote, QuoteCurrencyPair, QuoteHistoryItem from .types import PyObjectId
StarcoderdataPython
3223284
<reponame>and3rson/pyrant<gh_stars>0 #!/usr/bin/env python2 from pyrant import Client import json pyrant = Client() def test_get_rants(): # Retrieve rants from feed for rant in pyrant.get_rants(): print '*** @{}:'.format(rant.user_username) print rant.text, rant.id def test_get_rant(): ...
StarcoderdataPython
1651444
arr=[] for i in range(10): arr.append(int(input())) for j in range(10): arr[j]=arr[j]%42 arr=set(arr) print(len(arr))
StarcoderdataPython
1625336
<gh_stars>0 import numpy as np import random from operator import attrgetter from math import exp class Coin: def __init__(self, p, flip_count): self.p_head = p self.p_head_estimate = self.flip_repeatedly(flip_count) def flip(self): if random.uniform(0,1) < self.p_head: return ...
StarcoderdataPython
1725085
''' let s_k be the number of 1's when writing the numbers from 0 to k in binary. For example, writing 0 to 5 in binary, we have 0, 1, 10, 11, 100, 101. There are seven 1's, so s_5 = 7 The sequence S = {s_k : k >= 0} starts {0, 1, 2, 4, 5, 7, 9, 12, ...}. A game is played by two players. Before the game starts, a numb...
StarcoderdataPython
1617596
<reponame>nfitzen/advent-of-code-2020<filename>13/star2.py #!/usr/bin/env python3 # SPDX-FileCopyrightText: 2020 <NAME> <https://github.com/nfitzen> # # SPDX-License-Identifier: CC0-1.0 from math import lcm import itertools with open('input.txt') as f: data = f.readlines() firstId = int(data[1].split(',')[0]) i...
StarcoderdataPython
3322095
# -*- coding: utf-8 -*- import sys, os # -- General configuration ----------------------------------------------------- # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Galah' copyright = u'2012, <NAME>...
StarcoderdataPython
1629008
<filename>yelp/obj/business_response.py # -*- coding: UTF-8 -*- from yelp.obj.business import Business from yelp.obj.response_object import ResponseObject class BusinessResponse(ResponseObject): def __init__(self, response): super(BusinessResponse, self).__init__(response) self._parse_main_respo...
StarcoderdataPython
1698486
<filename>cogs/kindness.py import io import json import random import aiohttp import discord import giphypop from discord.ext import commands from .utils.dataIO import dataIO import os, os.path import re class Kindness(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() a...
StarcoderdataPython
82504
<gh_stars>0 """ Классы для работы с настройками проекта. Настройки берутся из файла """ import json import os import urllib.parse as urlparse from abc import ABC # Абстрактный класс по работе с настройками class Settings(ABC): __FILE_NAME = 'settings.json' def __read_file(self) -> json: f = open(self...
StarcoderdataPython
1755357
<filename>pydatastructures/list.py print("list")
StarcoderdataPython
108442
import os import json from numbers import Number from collections import Iterable, Mapping from operator import itemgetter from .config import set_class_path, JavaSettingsConstructorParams set_class_path() from jnius import autoclass, MetaJavaClass # Java DataTypes jMap = autoclass('java.util.HashMap') jArrayList = ...
StarcoderdataPython
1707766
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the tar path specification implementation.""" import unittest from dfvfs.path import tar_path_spec from tests.path import test_lib class TarPathSpecTest(test_lib.PathSpecTestCase): """Tests for the tar path specification implementation.""" def testInitiali...
StarcoderdataPython
1673820
from .AnimeInterp import AnimeInterp __all__ = [ 'AnimeInterp' ]
StarcoderdataPython
119655
#!/usr/bin/env python import itertools import os import signal import socket import subprocess import sys import uuid from contextlib import contextmanager from functools import partial from threading import Thread import click from dask.distributed import Client, as_completed def timed_wait_proc(proc, timeout): ...
StarcoderdataPython
45047
<reponame>JCab09/StickyDJ-Bot<gh_stars>0 #!/usr/bin/env python3 """ This class uses the yaml-parser in order to create the apropriate config-dictionary for the client who requested it Author: <NAME> """ from src.util.parser.yaml_parser import yaml_parser import string def getConfig(filepath, type = '.yaml', context...
StarcoderdataPython
108963
<reponame>Scobber/yeasterAPI from setuptools import setup, find_packages import pathlib here = pathlib.Path(__file__).parent.resolve() long_description = (here / 'README.md').read_text(encoding='utf-8') setup( name='yeastarAPI', version='0.1.5', # Required description='yeastar wireless terminal api clien...
StarcoderdataPython
3380520
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """The page cycler measurement. This measurement registers a window load handler in which is forces a layout and then records the value of performance.n...
StarcoderdataPython
4816897
# Remove the temp directory and then create a fresh one from __future__ import print_function import os import sys import shutil from subprocess import Popen, PIPE # exclude files that take time on locanachine exclude = ["flopy_swi2_ex2.py", "flopy_swi2_ex5.py"] if "CI" in os.environ: exclude = [] else: for ar...
StarcoderdataPython
1797050
<gh_stars>1-10 """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you ma...
StarcoderdataPython
139217
<reponame>Paul11100/LeetCode class Solution: # Accumulator List (Accepted), O(n) time and space def waysToMakeFair(self, nums: List[int]) -> int: acc = [] is_even = True n = len(nums) for i in range(n): even, odd = acc[i-1] if i > 0 else (0, 0) if is_even:...
StarcoderdataPython
34545
<filename>abc/abc107/abc107b.py from sys import stdout H, W = map(int, input().split()) a = [input() for _ in range(H)] h = [all(c == '.' for c in a[i]) for i in range(H)] w = [True] * W for i in range(H): for j in range(W): w[j] = w[j] and a[i][j] == '.' for i in range(H): if h[i]: continue...
StarcoderdataPython
3212672
<reponame>civicboom/civicboom from civicboom.tests import * from civicboom.model.meta import Session from civicboom.model import Message, Member #import json class TestMessagesController(TestController): def test_conversation_with(self): # Create a mini conversation self.log_in_as('unittest')...
StarcoderdataPython
3228791
import os import PySimpleGUI as sg from utils.gui import inference_window, training_window layout = [ [sg.Button('Inference', key='inference'), sg.Button('Training', key='training')], [sg.Cancel('Quit', key='cancel')], ] window = sg.Window('Bi-Vulma', layout, resizable=True) while True: event, values = window.re...
StarcoderdataPython
3353725
<reponame>k2bd/firebased from dataclasses import dataclass from datetime import datetime, timedelta from typing import List, Optional from dateparser import parse as parse_datetime @dataclass class _Base: def __post_init__(self): pass @dataclass class _WithUserBasic(_Base): #: ID token id_token...
StarcoderdataPython
3213568
<reponame>mahimadubey/leetcode-python class Solution: # @return a list of lists of string def solveNQueens(self, n): self.n = n res = [] columns = [-1 for i in range(n)] self.solve(columns, 0, res) return res def make_string_list(self, columns): sol = [] # O...
StarcoderdataPython
125385
#!/usr/bin/env python # example gtkcombobox.py import pygtk pygtk.require('2.0') import gtk import gobject class ComboBox: def delete_event(self, widget, event, data=None): gtk.main_quit() return False def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.win...
StarcoderdataPython
1782573
<gh_stars>0 #! /usr/bin/env python # vim: set fileencoding=utf-8: set encoding=utf-8: """ Proposed solution for calculating root mean square of a set of values. """ #We need to import the `math` package in order to use the `sqrt` function it #provides for doing square roots. import math def rms(values): ...
StarcoderdataPython
49914
class TrieNode: def __init__(self, c=None, end=False): self.c = c self.children = {} self.end = end class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode('') def insert(self, word: str) -> None: ...
StarcoderdataPython
152042
import json import logging import os import sys from typing import Any, Iterator, Optional import boto3 from botocore.exceptions import ClientError from chalice import Chalice app = Chalice(app_name="swarm-lifecycle-event-handler") LOGGER = logging.getLogger(__name__) LOGGER.setLevel(os.getenv("GRAPL_LOG_LEVEL", "ER...
StarcoderdataPython
3289468
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
StarcoderdataPython
1747947
<reponame>Kayuii/trezor-crypto<filename>python/trezorlib/btc.py<gh_stars>0 # This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 ...
StarcoderdataPython
117432
<filename>tsne_precompute/2_convert_to_bin_for_r.py from os import path import struct import numpy from config import Config from sensorimotor_norms.config.config import Config as SMConfig; SMConfig(use_config_overrides_from_file=Config.path) from tsne import valid_distance_names, SensorimotorTSNE def convert_file(...
StarcoderdataPython
1647287
from __future__ import division total_count = len(orgs_id) current_count = 0 corrected_count = 0 print("{0:.0f}%".format(current_count/total_count * 100))
StarcoderdataPython
3390701
#!/usr/bin/env python3 # Write a program that computes the GC fraction of a DNA sequence in a window # Window size is 11 nt # Step size is 5 nt # Output with 4 significant figures using whichever method you prefer # Use nested loops seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG' w = 11 s = 5 for n...
StarcoderdataPython
3384528
from .waba_service import WabaService
StarcoderdataPython
3264192
import FWCore.ParameterSet.Config as cms # # Hcal fake calibrations # # # please note: in the future, it should load Hcal_FakeConditions.cfi from this same directory # for 130 is was decided (by DPG) to stick to the old config, hence I load # #include "CalibCalorimetry/HcalPlugins/data/Hcal_FakeConditions.cfi" from Ca...
StarcoderdataPython
1615813
import dgl from . import register_model, BaseModel import torch.nn as nn import numpy as np import dgl.nn.pytorch as dglnn import torch import torch.nn.functional as F @register_model('DMGI') class DMGI(BaseModel): r""" Description ----------- **Title:** Unsupervised Attributed Multiplex Network E...
StarcoderdataPython
76923
<reponame>what-digital/aldryn-people # -*- coding: utf-8 -*- from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('aldryn_people', '0015_m2m_remove_null'...
StarcoderdataPython
3309087
class Inventory(object): def __init__(self, items): self.items = items def add(self,item): if self.items.haskey(item): self.items[item] += 1 else: self.items[item] = 1 def remove(self, item): if self.items.haskey(item): if self.items[ite...
StarcoderdataPython
1622075
from queue import LifoQueue if __name__ == '__main__': stack = LifoQueue() stack.put('one') stack.put('two') stack.put('three') stack.put('four') stack.put('five') stack.put('six') while not stack.empty(): print(stack.get())
StarcoderdataPython
6299
<reponame>hansthienpondt/ansible-networking-collections # (c) 2020 Nokia # # Licensed under the BSD 3 Clause license # SPDX-License-Identifier: BSD-3-Clause # from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ --- author: - "<NAME> (@HansThienpondt)" - "<NA...
StarcoderdataPython
86836
"""CoinGecko view""" __docformat__ = "numpy" import logging import os from pandas.plotting import register_matplotlib_converters from gamestonk_terminal.cryptocurrency.dataframe_helpers import ( lambda_very_long_number_formatter, ) from gamestonk_terminal.cryptocurrency.discovery import pycoingecko_model from ga...
StarcoderdataPython
4841296
import os import sys import argparse import glob import pandas as pd def get_arguments(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="", epilog=""" Convert behavioural data from cimaq to bids format Input: Folder ...
StarcoderdataPython
3209061
# ============================================================================== # Copyright 2019 - <NAME> # # NOTICE: 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, ...
StarcoderdataPython
12877
import os import time import argparse import torchvision import torch import torch.nn as nn from util import AverageMeter, TwoAugUnsupervisedDataset from encoder import SmallAlexNet from align_uniform import align_loss, uniform_loss import json def parse_option(): parser = argparse.ArgumentParser('STL-10 Repres...
StarcoderdataPython
20355
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class MybankCreditSceneprodCommonQueryModel(object): def __init__(self): self._app_seq_no = None self._ext_param = None self._operation_type = None self._org_code = None...
StarcoderdataPython
1738993
# -*- coding: utf-8 -*- """ idfy_rest_client.models.identification_response This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ import idfy_rest_client.models.error import idfy_rest_client.models.environment_info class IdentificationResponse(object): "...
StarcoderdataPython
37476
#!/usr/bin/env python3 """ Easy to use Websocket Server. Source: https://github.com/rharder/handy June 2018 - Updated for aiohttp v3.3 August 2018 - Updated for Python 3.7, made WebServer support multiple routes on one port """ import asyncio import logging import weakref from functools import partial from typing imp...
StarcoderdataPython
39639
<reponame>idiotic/idiotic import logging from urllib.parse import urlparse, urlunparse from idiotic import block from idiotic.util.resources import http import aiohttp import asyncio import json import types log = logging.getLogger(__name__) class HTTP(block.Block): def __init__(self, name, url, method="GET",...
StarcoderdataPython
1696022
# This will import the SWIG bindings created and installed by the bindings directory, to create # a seamless protocols package integrating C++ and python code from protocols import * from MultipleTryProtocol import MultipleTryProtocol
StarcoderdataPython
154738
#<NAME> #october 6, 20202 import pysam import pandas as pd import numpy as np def get_sample_counts(bam_file, reference): bamfile_obj = pysam.AlignmentFile(bam_file,'rb') ref = open(reference + "/chrName.txt",'r') curr_file_counts = [] ref_list = [] for seq in ref: seq = seq.strip() curr_seq_reads = bamf...
StarcoderdataPython
73262
<reponame>PavelSheremetev/libelium_sensor_collector import select import socket SERVER_ADDRESS = ('172.16.58.3', 8888) # Говорит о том, сколько дескрипторов единовременно могут быть открыты MAX_CONNECTIONS = 10 # Откуда и куда записывать информацию INPUTS = list() OUTPUTS = list() def get_non_blocking_server_sock...
StarcoderdataPython
1645786
<reponame>MiM0ulay/code-katas """Function to return list from string.""" def string_to_array(string): """Return a list from input string.""" if string == "": return [""] return string.split()
StarcoderdataPython
3240929
<filename>JianshuResearchTools/objects.py from datetime import datetime from typing import Dict, List from . import article, collection, island, notebook, user from .assert_funcs import (AssertArticleUrl, AssertCollectionUrl, AssertIslandUrl, AssertNotebookUrl, AssertUserUrl) from .convert i...
StarcoderdataPython
4801290
from musicscore.dtd.dtd import Sequence, Choice, GroupReference, Element from musicscore.musicxml.attributes.attribute_abstract import AttributeAbstract from musicscore.musicxml.attributes.optional_unique_id import OptionalUniqueId from musicscore.musicxml.attributes.printobject import PrintObject from musicscore.music...
StarcoderdataPython
1787260
from __future__ import division import parent from parent import * class HelixComplex(ParentComplex): """Helix association or disocciation reaction""" def __init__(self , myPickles, dangleleft, dangleright, theta, zip, strand1, strand2,T, concentration, sodium, magnesium, dataset_name, docID, name ): ParentComple...
StarcoderdataPython
95665
<reponame>lilloraffa/covid19-model import math import numpy as np from .model import * class Param: def __init__(self, par_name, par_min = -1*math.inf, par_max = math.inf): self.par_name = par_name self.par_min = par_min self.par_max = par_max class GridParam: def __init__(self): ...
StarcoderdataPython
1741549
class RemoteOperationExecutionException(Exception): pass
StarcoderdataPython
3327773
<reponame>abourget/formalchemy-abourget<filename>pylonsapp/pylonsapp/model/__init__.py """The application's model objects""" import sqlalchemy as sa from sqlalchemy import orm from pylonsapp.model import meta def init_model(engine): """Call me before using any of the tables or classes in the model""" ## Refle...
StarcoderdataPython
1674860
import bpy class MESH_UL_mylist(bpy.types.UIList): # Constants (flags) # Be careful not to shadow FILTER_ITEM (i.e. UIList().bitflag_filter_item)! # E.g. VGROUP_EMPTY = 1 << 0 # Custom properties, saved with .blend file. E.g. # use_filter_empty = bpy.props.BoolProperty(name="Filter Empty", defaul...
StarcoderdataPython
3302383
#!/usr/bin/python3 #Code written by # _ _ __ # ___ | |_ _ __ / | / _| ___ # / __|| __|| '__|| || |_ / _ \ # \__ \| |_ | | | || _|| __/ # |___/ \__||_| |_||_| \___| # # Простая реализациия элементарных клеточных автоматов с применением ООП. # Использование: создаете экземлпяр класса Wolfr...
StarcoderdataPython
3287171
# -*- coding: utf-8 -*- # # Copyright 2019 <NAME>. 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://www.apache.org/licenses/LICENSE-2.0 # # or in the "li...
StarcoderdataPython
1697967
#!/usr/bin/python3 # <NAME> @2013 # steinkirch at gmail ''' using sets ''' def intersection_two_arrays_sets(seq1, seq2): ''' find the intersection of two arrays using set proprieties ''' set1 = set(seq1) set2 = set(seq2) return set1.intersection(set2) #same as list(set1 & set2 ''' using m...
StarcoderdataPython
3321820
from sys import stderr class Best: def __init__(self, phase, metric, file=stderr): super().__init__() self.phase = phase self.metric = metric self.file = file self.best = None self.state_dict = None def step(self, epoch, model): loss = epoch[self.phase][self.metric][-1] if self.be...
StarcoderdataPython
153099
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class TuitionQueryOrder(object): def __init__(self): self._alipay_payment_id = None self._isv_payment_id = None @property def alipay_payment_id(self): return self._alip...
StarcoderdataPython
3266660
<gh_stars>1-10 from decimal import Decimal as D import datetime from django.conf import settings from django.utils import unittest from django.core.exceptions import ValidationError from oscar.apps.product.models import Item, ItemClass from oscar.apps.partner.models import Partner, StockRecord from oscar.test.helpers...
StarcoderdataPython
1746604
<reponame>EnjoyLifeFund/py36pkgs # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) Au...
StarcoderdataPython
1770268
""" cl_sii "extras" / Django REST Framework (DRF) fields. (for serializers) """ try: import rest_framework except ImportError as exc: # pragma: no cover raise ImportError("Package 'djangorestframework' is required to use this module.") from exc import rest_framework.fields from cl_sii.rut import Rut clas...
StarcoderdataPython
146495
<filename>app.py<gh_stars>0 import Services import Repositories import config from flask_restx import Resource, Api from flask import Flask app = Flask(__name__) api = Api(app) @api.route('/get_word_count/<int:threshold>') class MainClass(Resource): def get(self, threshold): scanner = Services.DirectoryS...
StarcoderdataPython
156511
<filename>tests/optimise.py import sys import os import numpy as np def run_cci(year, stock, window, up, down): import test_cci return test_cci.test(year, stock, window, up, down, get_plots=False, verbose=False) def run_sma(year, stock, window, up, down): import test_sma return test_sma.test(year, stock, window, ...
StarcoderdataPython
3242472
# Generated by Django 3.1.12 on 2021-07-13 13:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('action_plans', '0008_actionplan_status'), ] operations = [ migrations.AddField( model_name='actionplan', name='stra...
StarcoderdataPython
1770004
<reponame>patelgaurank/SocialSponsorDjangoAPI from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView from django.views import View # from django.contrib.auth.models import User, Group from django.views.decorators.csrf import csrf_exempt from django.http import...
StarcoderdataPython
4808648
<reponame>3amon/twitter-robofact import json, requests, html2text, re, nltk.data, time sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') def MakeTweet(text): sents = sent_detector.tokenize(text.strip().replace('\n', ' ')) result = '' for sent in sents: newres = result + sent if len(newres) > 14...
StarcoderdataPython
3319224
import numpy as np import pandas as pd FEATURES = [ 'x', 'x_diff_1', 'x_diff_2','x_diff_3','x_diff_4',#'x_diff_5','x_diff_6',#'time_diff', 'norm_diff_1', 'norm_diff_2','norm_diff_3','norm_diff_4', 'mean_2','mean_4','mean_6',# 'mean_20', 'mean_50', 'std_2','st...
StarcoderdataPython
1646340
# The MIT License (MIT) # Copyright (c) 2021 by Brockmann Consult GmbH and contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the...
StarcoderdataPython
30305
"""This module contains exceptions defined for Rhasspy Desktop Satellite.""" class RDSatelliteServerError(Exception): """Base class for exceptions raised by Rhasspy Desktop Satellite code. By catching this exception type, you catch all exceptions that are defined by the Hermes Audio Server code.""" cla...
StarcoderdataPython
147237
<reponame>Maxsparrow/cirrus<gh_stars>10-100 #!/usr/bin/env python """ _deploy_plugins_ Plugin helpers to talk to various deployment platforms, Plugins should subclass the Deployer class, override the build_parser to handle whatever CLI args they need and also deploy to do the actual implementation. Drop plugins in th...
StarcoderdataPython
175107
<gh_stars>100-1000 import numpy as np from torch.utils.data import Dataset from .seg import MaskSemSeg from .filter import TargetFilter from .sparse import SparseSeg from .util import Wrapper class ConditionalInstSeg(Wrapper, Dataset): """ Construct inputs (support image sparse annotations, query image) ...
StarcoderdataPython
3237128
<gh_stars>0 # Copyright 2020 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 appl...
StarcoderdataPython
19888
<reponame>yzjba/FATE<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License ...
StarcoderdataPython