id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
11390628
meals_3meals = { '1': ('16:30', '19:30'), '2': ('22:30', '00:30'), '3': ('4:30', '5:30') } meals_6meals = { '1': ('16:30', '18:00'), '2': ('20:00', '20:30'), '3': ('22:30', '00:00'), '4': ('2:00', '2:30'), '5': ('4:30', '6:00'), '6': ('8:00', '8:30') } meals_3meals_buffer = { '1...
StarcoderdataPython
5137654
<reponame>IlyaFaer/GitHub-Scraper<gh_stars>10-100 """Manual mocks of some Scraper classes.""" import github from sheet import Sheet from sheet_builder import SheetBuilder import spreadsheet import examples.fill_funcs_example SPREADSHEET_ID = "ss_id" class SheetBuilderMock(SheetBuilder): def _login_on_github(self...
StarcoderdataPython
9753782
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
StarcoderdataPython
5111474
<gh_stars>0 from utils import * def load_data(): data = [] if KEEP_IDX: cti = load_tkn_to_idx(sys.argv[1] + ".char_to_idx") wti = load_tkn_to_idx(sys.argv[1] + ".word_to_idx") tti = load_tkn_to_idx(sys.argv[1] + ".tag_to_idx") else: cti = {PAD: PAD_IDX, SOS: SOS_IDX, EOS: EO...
StarcoderdataPython
11358363
#import time, itertools, import string import os, os.path #import sys, shutil #import numpy from PyQt4.QtCore import * from PyQt4.QtGui import * #import operator import matplotlib #from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas #try: # from matplotlib.backends.backend_qt4agg impor...
StarcoderdataPython
3541443
'''Crie um programa que leia varios produtos pergunte se quer continuar o total de gasto na compra quantos produtos custam mais que 1000 o nome do produto mais barato''' contador =total = quant = preco_b =0 nome_b = '' while True: nome = str(input('Digite o nome do produto: ')) preco = float(input('Digite o va...
StarcoderdataPython
6454976
<reponame>geraltofrivia/mytorch """ This file contains training loops, available as function calls. ## USAGE Typically, a training loop will want a train, a predict and a eval function; alongwith other args and data which dictate what the loop should train on, and for how long. See the documen...
StarcoderdataPython
1956693
"""Tests for `{{ cookiecutter.pkg_name }}` package.""" {% if cookiecutter.command_line_interface|lower == 'y' -%} from typer.testing import CliRunner from {{ cookiecutter.pkg_name }} import cli {%- endif %} {%- if cookiecutter.command_line_interface|lower == 'y' %} class TestCLI: """Test the CLI.""" runne...
StarcoderdataPython
3277698
import itertools import numpy as np from challenge import Challenge class ChallengeSolution(Challenge): def __init__(self): # Initialise super super().__init__() # Define digit masks self.digits = np.asarray([ [True , True , True , False, True , True , True ], # 0 ...
StarcoderdataPython
11314035
description = 'setup for the astrium chopper' group = 'optional' devices = dict( chopper_dru_rpm = device('nicos.devices.generic.VirtualMotor', description = 'Chopper speed control', abslimits = (0, 20000), unit = 'rpm', fmtstr = '%.0f', maxage = 35, ), chopper_wate...
StarcoderdataPython
5169976
#!/usr/bin/env python3 """ Calculating gcd of given numbers """ from sys import argv from divide import divide from errorhandler import inputerror, zerodiv def gcd(a,b): try: [q, r] = divide(a,b) except ZeroDivisionError: zerodiv("b") while True: [q, r] = divide(a,b) if no...
StarcoderdataPython
396552
<filename>Main.py #coding = utf-8 import sys import os if hasattr(sys, 'frozen'): os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH'] from Ui_Main import Ui_MainWindow from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5 import QtCore import downloadNeteaseMusiclib import queue import re musi...
StarcoderdataPython
8064302
<filename>manager/edgeap.py import manager import sys import signal import time import argparse def main(): # CLI options argparser = argparse.ArgumentParser(description='EdgeAP management server') argparser.add_argument('-c', '--config', type=str, default="manager.conf", ...
StarcoderdataPython
4836897
<reponame>rftafas/stdcores<filename>axis_demux/axis_demux_run.py from os.path import join, dirname import sys import glob try: from vunit import VUnit except: print("Please, intall vunit_hdl with 'pip install vunit_hdl'") print("Also, make sure to have either GHDL or Modelsim installed.") exit() root...
StarcoderdataPython
3595343
<filename>example_tester.py import json from photo_dash import image with open('resources/example.json') as f: e = json.load(f) i = image.DashImage(e['module'], e['title'], e['sections']) i.create()
StarcoderdataPython
9616692
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 13 09:32:40 2020 @author: twguest """ ############################################################################### import sys sys.path.append("/opt/WPG/") # LOCAL PATH sys.path.append("/gpfs/exfel/data/user/guestt/WPG") # DESY MAXWELL PATH sys....
StarcoderdataPython
3216113
<reponame>yiguanxianyu/PiGIS<filename>ui/mainwindow.py from PySide6.QtCore import Qt, QStringListModel from PySide6.QtGui import QFont, QStandardItemModel, QStandardItem from PySide6.QtWidgets import QMainWindow, QApplication, QSplitter, QWidget, QTabWidget, QListWidgetItem # import pyqtgraph as pg from ui import L...
StarcoderdataPython
4806590
<reponame>KingaS03/global-divergences import torch from torch.autograd import grad from divergences import kernel_divergence from divergences import regularized_ot, hausdorff_divergence, sinkhorn_divergence from divergences import regularized_ot_visualization, hausdorff_divergence_visualization, sinkhorn_dive...
StarcoderdataPython
3376718
from numbers import Number from math import sqrt, pow from random import uniform # Constants that cn be modified to get different results. # Current values have been arbitrary chosen NB_CABLES = 2 MIN_LOAD = 0 MAX_LOAD = 150 class UNumber: def __init__(self, mean=0., variance=0.): self.mean = mean ...
StarcoderdataPython
165722
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import WebDriverException import time import pandas as pd from datetime import datetime import platform i...
StarcoderdataPython
5190326
<reponame>microsoft/semantic_parsing_with_constrained_lm<filename>src/semantic_parsing_with_constrained_lm/configs/lib/common.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from enum import Enum from typing import Callable, List, Optional from semantic_parsing_with_constrained_lm.datum im...
StarcoderdataPython
5068786
from flask_caching import Cache config = {'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': 'redis://localhost:6379/0' } cache = Cache(config=config)
StarcoderdataPython
8154671
import numpy as np import tensorflow as tf from tensorflow.contrib.framework.python.ops import add_arg_scope from tensorflow.python.framework import function as tff def energy_distance(f_sample, f_data): nr_chunks = len(f_sample) f_sample = np.concatenate(f_sample) f_data = np.concatenate(f_data) grads...
StarcoderdataPython
6432782
<reponame>varikakasandor/dissertation-balls-into-bins<filename>two_thinning/full_knowledge/RL/DeepSarsaRL/__init__.py import two_thinning.full_knowledge.RL.DeepSarsaRL.train
StarcoderdataPython
11284470
__version__ = "1.0.0" __author__ = "vcokltfre" __license__ = "MIT" def bolb() -> str: return "bolb" __all__ = ("bolb",)
StarcoderdataPython
5062285
# (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
StarcoderdataPython
11263151
<filename>network/vis_detection.py import cv2 import os #image_dir = "/data/dataset/VAR/UCF-101/train" #result_dir = "/data/dataset/ucf101/UCF-101_det_vis/" #bbox_dir = "/data/dataset/UCF-101-result/UCF-101-20/" #image_dir = "/data/dataset/something-somthing-v2/20bn-something-something-v2-frames-224/" #result_dir = "...
StarcoderdataPython
281246
<reponame>himanshudabas/spade import time import pytest from aioxmpp import PresenceShow, PresenceState from asynctest import Mock, CoroutineMock from spade.agent import Agent from spade.container import Container from spade import quit_spade @pytest.fixture(autouse=True) def run_around_tests(): # Code that will...
StarcoderdataPython
12826160
import os from pathlib import Path import yaml from hlkit.syntax import MatchPattern, SyntaxDefinition from hlkit.parse import ParseResult, ParseState BASE_DIR = os.path.join(os.path.dirname(__file__), "..", "..") ASSETS_DIR = os.path.join(BASE_DIR, "assets") ASSETS_DIR = os.path.abspath(ASSETS_DIR) class TestParse...
StarcoderdataPython
6691599
SOURCE_FILE = __file__ def in_order_traversal(t): """ Generator function that generates an "in-order" traversal, in which we yield the value of every node in order from left to right, assuming that each node has either 0 or 2 branches. For example, take the following tree t: 1 2 ...
StarcoderdataPython
11210991
<filename>equipment/framework/helpers.py from importlib import import_module from inspect import getfile from pathlib import Path from typing import TYPE_CHECKING, Any, NoReturn, Optional from sys import exit as _exit, modules as _modules from pprint import pformat from equipment.framework.Exceptions.ContainerModuleNot...
StarcoderdataPython
1759539
# PiFrame weather.py # Manages weather data as well as forecast for the "Weather" Extension # Uses Open Weather API https://openweathermap.org/api import requests, settings, json, datetime # Request URLS for weather currentWeatherRequestURL = lambda zip, apiKey : ("http://api.openweathermap.org/data/2.5/weather?zip=%s...
StarcoderdataPython
9681260
#!/usr/bin/env python # Copyright 2015 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. """changes.ChangeStore unit tests""" import datetime import json import unittest import test_env # pylint: disable=W0611 from maste...
StarcoderdataPython
11314885
<reponame>Ouranosinc/Magpie #!/usr/bin/env python # -*- coding: utf-8 -*- """ test_magpie_api ---------------------------------- Tests for :mod:`magpie.api` module. """ import unittest import mock # NOTE: must be imported without 'from', otherwise the interface's test cases are also executed import tests.interfaces...
StarcoderdataPython
4924522
from yunionclient.common import base class Kubecluster(base.ResourceBase): pass class KubeclusterManager(base.StandaloneManager): resource_class = Kubecluster keyword = 'kubecluster' keyword_plural = 'kubeclusters' _columns = ["Name", "Id", "Status", "Cluster_Type", "Cloudregion_Id", "Vpc_Id", "R...
StarcoderdataPython
3554686
from time import sleep from easyprocess import EasyProcess from pykeyboard import PyKeyboard from pyvirtualdisplay.smartdisplay import SmartDisplay from discogui.imgutil import getbbox, grab VISIBLE = 0 def test_zenity(): with SmartDisplay(visible=VISIBLE) as disp: with EasyProcess(["zenity", "--warnin...
StarcoderdataPython
4894240
class Solution: # Sort and sum abs diff (Accepted), O(n log n) time, O(n) space def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: seats.sort() students.sort() res = 0 for i in range(len(seats)): res += abs(seats[i] - students[i]) return r...
StarcoderdataPython
5046597
<filename>src-electron/main-process/python-logic/scripts/message_protocol.py<gh_stars>0 import json from enum import Enum import requests from os import path as osPath, remove as removeFile from hashlib import sha256 from re import split class Types(Enum): INTERNAL = 1 STT = 2 class Message: __blocked_words = []...
StarcoderdataPython
102407
<gh_stars>0 import os import pdf2image from time import sleep class EverythingForms: def __init__(self, pdf_path, img_path): """ :param pdf_path: caminho do PDF com o nome dos alunos :param img_path: destino para as imagens - Tranforma cada página do pdf em imagens. - O n...
StarcoderdataPython
6555197
<reponame>dilr/Coramin import pyomo.environ as pyo from pyomo.core.base.var import _GeneralVarData from pyomo.core.base.PyomoModel import ConcreteModel from pyomo.opt import SolverStatus, TerminationCondition as TC import warnings from pyomo.common.collections import ComponentMap from pyomo.solvers.plugins.solvers.GURO...
StarcoderdataPython
3501059
<filename>openai/api_resources/abstract/__init__.py from __future__ import absolute_import, division, print_function # flake8: noqa from openai.api_resources.abstract.api_resource import APIResource from openai.api_resources.abstract.singleton_api_resource import ( SingletonAPIResource, ) from openai.api_resourc...
StarcoderdataPython
327606
<gh_stars>0 #!/usr/bin/env python # -*- coding: iso-8859-15 -*- import subprocess import tempfile import logging def run_command(command): return run_command_with_input_data(command, input_data = None) def run_command_with_input_data(command, input_data = None): try: logging.debug("About to execute %s", ' '.jo...
StarcoderdataPython
3289405
<reponame>ruanyangry/Spark-ML-study # _*_ coding:utf-8 _*_ ''' GaussianMixture ''' from pyspark.sql import SparkSession from pyspark.ml.clustering import GaussianMixture spark = SparkSession.builder.appName("GaussianMixture").getOrCreate() paths="/export/home/ry/spark-2.2.1-bin-hadoop2.7/data/mllib/" ...
StarcoderdataPython
3205230
<reponame>todhm/wicarproject from mongoengine import * import json class UserAgent(EmbeddedDocument): browser = StringField() language = StringField() platform = StringField() string = StringField() version = StringField() class Tracking(Document): #session_key = models.CharField(max_length=40...
StarcoderdataPython
1862904
<reponame>crcresearch/GOS import numpy as np import pandas as pd from constants import MIN_POPULATION, POPULATION_SCALE COUNTRY_COLS = ["Population", "GDP", "Unemployment", "Conflict", "Fertility", "FullName", "neighbors"] def csv_path(name): """ Shortcut function to get the relative path to...
StarcoderdataPython
6471825
class Solution(object): def countRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """ n = len(nums) sums = [0] * (n + 1) for i in range(0, n): sums[i + 1] = sums[i] + nums[i...
StarcoderdataPython
1913667
class Node: __slots__ = 'next', 'data' def __init__(self, data): self.data = data self.next = None class Queue: """ FiFo Queue Methods: - to_list() - O(n) Returns list representation of queue, used for debugging - enqueue(data) - O(1) Enter data at the end ...
StarcoderdataPython
6466096
<gh_stars>0 # Assignment 3: CSC 486 - Spring 2022 # Author: Dr. <NAME> # The purpose of this assignment is to guide you through building # some common contagion models from scratch and use them to # understand some of the dynamics underlying the spread of a # phenomenon through a network. import matplotlib.pyplot as ...
StarcoderdataPython
11235005
<reponame>AnujBrandy/AdsIdeaInQBO<filename>parameters_8001.py password="<PASSWORD>(1<PASSWORD>,20,sha512)$b7be3eabb9e0f671$42805bad515a5f87e5b75c18f3abe6182f5c2545"
StarcoderdataPython
4818412
<gh_stars>0 import os def parseMegan(filename, prefix=""): ''' Takes the MEGAN_info file generated from the MEGAN GUI and split it into the respective categories (TAX, INTERPRO2GO etc). ''' output = {} key = "" data = "" with open(filename,"r") as f: while True: line = f...
StarcoderdataPython
8011969
import numpy as np import numba as nb from numba import types, typed, typeof from numba import jit from numba.experimental import jitclass from nrc_spifpy.spif import TIME_CHUNK # The size of the metadata in a particle record # Word 1 = Flag 2S # Word 2 = word for h image metadata # Word 3 = word for v image metadata...
StarcoderdataPython
4920107
<filename>heat/core/memory.py<gh_stars>0 import numpy as np import torch from . import dndarray __all__ = ["copy", "sanitize_memory_layout"] def copy(a): """ Return an array copy of the given object. Parameters ---------- a : ht.DNDarray Input data to be copied. Returns ------- ...
StarcoderdataPython
8096778
<gh_stars>0 from flask import Flask, request, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from flask_bootstrap import Bootstrap from flask.ext.modular_auth import AuthManager, SessionBasedAuthProvider, current_authenticated_entity def unauthorized_callback(): if current_authenticated_entity.i...
StarcoderdataPython
3268296
<gh_stars>0 #/usr/bin/env/ python #coding=utf8 import tornado.ioloop import tornado.web import httplib import md5 import urllib import random import time from tornado.escape import json_decode from apps_info_setting import apps_info apps = [ "01_41","01_51","01_61","01_71","01_81", "02_11","02_12","02_13","02_...
StarcoderdataPython
9780303
<reponame>k88097/Switch-Fightstick<filename>example/Fossil.py from NXController import Controller import time ctr = Controller() count = 0 goal = int(input("目標幾隻:")) print("{}開始{}".format("=" * 10, "=" * 10)) while count < goal: count += 1 print("目前第{}隻,剩餘{}隻達到目標。".format(count, goal - count)) Fossil() p...
StarcoderdataPython
1877627
from typing import Any, Dict, List, Optional class Node: """Just to make mypy happy""" class Contents: """Simulated context manager for file.open for tests and helpers""" def __init__(self, contents=None): self.contents = contents def read(self): """Just returns the contents""" ...
StarcoderdataPython
127933
import unittest import numpy as np from pax import core, plugin from pax.datastructure import Event, Peak class TestPosRecMaxPMT(unittest.TestCase): def setUp(self): self.pax = core.Processor(config_names='XENON100', just_testing=True, config_dict={'pax': { 'plugin_group_names': ['test'], ...
StarcoderdataPython
6511931
<reponame>kaitai-io/formats-kaitai-io.github.io # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version import kaitaistruct from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO from enum import Enum import zlib if parse_versio...
StarcoderdataPython
5118189
<filename>test/test_copy.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved. # import pytest from snowflake.sqlalchemy import ( AWSBucket, AzureContainer, CopyFormatter, CopyIntoStorage, CSVFormatter, ExternalStage, JSONFo...
StarcoderdataPython
1932405
<reponame>stadham/mudpy import rooms color = { "black": u"\u001b[30;1m", "red": u"\u001b[31;1m", "green": u"\u001b[32;1m", "yellow": u"\u001b[33;1m", "blue": u"\u001b[34;1m", "magenta": u"\u001b[35;1m", "cyan": u"\u001b[36;1m", "white": u"\u001b[37;1m", "reset": u"\u001b[...
StarcoderdataPython
11386813
<reponame>OasisLMF/OasisLMF __all__ = [ 'oasis_log', 'read_log_config', 'set_rotating_logger' ] """ Logging utils. """ import inspect import logging import os import time from functools import wraps from logging.handlers import RotatingFileHandler def getargspec(func): if hasattr(inspect, 'getfullar...
StarcoderdataPython
6475588
""" Helper utils to compose objects as blobs of html """ import yattag from . import util from .recipe import QuantizedIngredient def close(content, tag, **kwargs): if "class_" in kwargs: kwargs["class"] = kwargs["class_"] if "klass" in kwargs: kwargs["class"] = kwargs["klass"] attributes ...
StarcoderdataPython
1631424
<filename>sdk/metricsadvisor/azure-ai-metricsadvisor/tests/async_tests/test_hooks_async.py # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license informati...
StarcoderdataPython
3450281
<reponame>nalderto/otter-grader<gh_stars>0 """ Runs Otter on Gradescope with the configurations specified below """ import os import subprocess from otter.generate.run_autograder import main as run_autograder config = { "score_threshold": {{ threshold }}, "points_possible": {{ points }}, "show_stdout_on_...
StarcoderdataPython
206993
<reponame>jihyungSong/plugin-azure-power-state<filename>src/spaceone/inventory/model/virtual_machine.py import logging from schematics import Model from schematics.types import ModelType, StringType, ListType, DictType from spaceone.inventory.libs.schema.cloud_service import CloudServiceResource, CloudServiceResponse ...
StarcoderdataPython
3575265
from __future__ import annotations import functools from typing import Any, Union, Tuple, Callable, Type, cast, TypeVar FuncSig = TypeVar("FuncSig", bound=Callable) class MissingValue: def __repr__(self) -> str: return type(self).__name__ missing = MissingValue() def _set_value_ignoring_exceptions(e...
StarcoderdataPython
4951571
<filename>sdk/python/pulumi_newrelic/get_entity.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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,...
StarcoderdataPython
5159779
#Current key bindings: #left/right arrow: change direction (forward/backword, respectively) and make a step in that direction #space bar: start/stop the animation #from Scientific.IO.NetCDF import NetCDFFile as Dataset import numpy as np from mpl_toolkits.mplot3d import Axes3D from threading import Timer from matplot...
StarcoderdataPython
6430021
<reponame>pradeep-charism/bigdata-analytics-ml<filename>prediction/test_bband.py import matplotlib.pyplot as plt import numpy as np import pandas as pd import pandas_datareader.data as web import yfinance as yf from talib import RSI, BBANDS start = '2022-01-22' end = '2022-04-21' symbol = 'TSLA' max_holding = 100 pri...
StarcoderdataPython
8106084
<gh_stars>1-10 #! /usr/bin/python # -*- coding: utf-8 -*- # # create/xindice_create.py # # Oct/16/2012 # # ------------------------------------------------------------------ import os import sys import pycurl # sys.path.append ("/var/www/data_base/common/python_common") # from xml_manipulate import dict_to_xml_proc ...
StarcoderdataPython
6581755
from requests import Session as RequestsSession from ISEApi import logger class Session(RequestsSession): def __init__(self, base_url): self.base_url = base_url super().__init__() def _set_content_type(self, request): """Checks for the content-type and accept headers and if they dont...
StarcoderdataPython
85096
""" This package contains all objects managing Tunneling and Routing Connections.. - KNXIPInterface is the overall managing class. - GatewayScanner searches for available KNX/IP devices in the local network. - Routing uses UDP/Multicast to communicate with KNX/IP device. - Tunnelling uses UDP packets and builds a stat...
StarcoderdataPython
4986400
<filename>draw_qrcode.py from qrcode import coded_msg from PIL import Image, ImageFont, ImageDraw, ImageEnhance MSG = "MATHSDISCRETES" MODE = "0010" MAX = 19*8 CORRECTION = [211, 212, 181, 2, 31, 139, 106] def draw_pattern(qrcode, x, y): draw = ImageDraw.Draw(qrcode) draw.rectangle( [(x, y), (x+6, y+...
StarcoderdataPython
6544717
<filename>settings.py ### GAME SETTINGS ### # IMPORT LIBRARIES # IMPORT GAME FILES # WINDOW SETTINGS TITLE = "Battler V1" WIDTH = 500 HEIGHT = 500 FPS = 60 #COLOURS WHITE = (255, 250, 250) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) #FONT SETTINGS FO...
StarcoderdataPython
5112484
<filename>Workflow.py from pathlib import Path from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.cluster import KMeans, DBSCAN from sklearn.preprocessing import StandardScaler, RobustScaler, PowerTransformer, Normalizer, FunctionTransformer from sklearn.pipeline import make_pipeline f...
StarcoderdataPython
6628146
# -*- coding: utf-8 -*- from robotkernel.builders import build_suite TEST_SUITE = """\ *** Settings *** Library Collections *** Keywords *** Head [Arguments] ${list} ${value}= Get from list ${list} 0 [Return] ${value} *** Tasks *** Get head ${array}= Create list 1 2 3 4 5 ${head}=...
StarcoderdataPython
3382775
<reponame>cjw296/mush from unittest import TestCase from testfixtures import ShouldRaise from mush import Context from .compat import PY32 class TheType(object): def __repr__(self): return '<TheType obj>' class TestContext(TestCase): def test_simple(self): obj = TheType() context =...
StarcoderdataPython
5053944
<filename>setup.py # -*- coding: utf-8 -*- import os import sys __DIR__ = os.path.abspath(os.path.dirname(__file__)) import codecs from setuptools import setup from setuptools.command.test import test as TestCommand import demeter def read(filename): """Read and return `filename` in root dir of project and return...
StarcoderdataPython
3231456
class Solution(object): def distributeCandies(self, candyType): """ :type candyType: List[int] :rtype: int """ return min(len(set(candyType)),len(candyType)//2)
StarcoderdataPython
3527762
import turtle as t from turtle import * import random as r import time n = 100.0 speed("fastest") screensize(bg='black') left(90) forward(3 * n) color("orange", "yellow") begin_fill() left(126) for i in range(5): forward(n / 5) right(144) forward(n / 5) left(72) end_fill() right(...
StarcoderdataPython
6440026
<gh_stars>0 """ The MIT License (MIT) Copyright (c) 2015 Red Hat 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 to use, copy, modify,...
StarcoderdataPython
139275
import graphene from ...invoice import models from ..core.types import Job, ModelObjectType from ..meta.types import ObjectWithMetadata class Invoice(ModelObjectType): number = graphene.String() external_url = graphene.String() created_at = graphene.DateTime(required=True) updated_at = graphene.DateT...
StarcoderdataPython
11264998
import pytest from networkx import symmetric_difference from src import HierarchicalGraph trivial_data = [ ( [ 'abc', 'bcd', 'cde', ], 5, ), ( [ 'cde', 'bcd', 'abc', ], 9, ), ( ...
StarcoderdataPython
8078648
import math a = float(input('Digite o comprimento de uma reta:')) b = float(input('Digite o comprimento de outra reta:')) c = float(input('Digite o comprimento de uma terceira reta:')) if abs(b-c)<a and a<(b+c) and abs(a-c)< b and b<(a+c) and abs(a-b)<c and c<(a+b): if a==b and b==c: print('Este e um trian...
StarcoderdataPython
1736611
import esgfpid import logging import sys import datetime input('Make sure you have an exchange "test123" ready, including a queue and the required bindings (see inside this script). Ok? (press any key)') if not len(sys.argv) == 4: print('Please call with <host> <user> <password>!') exit(999) # Please fill i...
StarcoderdataPython
6695310
def is_number(string): try: float(string) return True except ValueError: return False def continue_calculations(): while True: choice_ = input(msg_5) if choice_ == "y": return True elif not choice_ == "n": continue return Fals...
StarcoderdataPython
8172956
<filename>src/call_cmd.py<gh_stars>0 #!/usr/bin/env python # coding: utf-8 import subprocess import os, sys class ExitException(Exception): def __init__(self, retcode): self.retcode = retcode def raise_exit(retcode=1, err_msg="Error"): print(err_msg) raise ExitException(retcode) def re_if_not(re...
StarcoderdataPython
9625167
<filename>Calculus methods/1 part/lab3/lab.py import numpy as np import matplotlib.pyplot as plt import pylab import math def find_y_in_x(X,Y,x): m= len(X) y = Y.copy() for k in range(1,m): y[0:m-k] = ((x-X[k:m])*y[0:m-k] + (X[0:m-k]-x)*y[1:m-k+1])/(X[0:m-k]-X[k:m]) return y[0] def main(): ...
StarcoderdataPython
1834487
# Helper Functions # Function checkCommas: checks if word has comma at front or at last or at both if true then return front,word and last def checkCommas(word): start = "" last = "" if(len(word) > 1): if word[-1] == ',' or word[-1] == '.': last = word[-1] word = word[:-1] ...
StarcoderdataPython
3398270
<filename>Example-University-System/university.py<gh_stars>0 class College: def __init__(self, **kwargs): ''' **kwargs is the keyworded arguments ''' self.name = kwargs['name'] self.id = kwargs['id'] # Initialize an empty college. self.professors = {} ...
StarcoderdataPython
1895616
<reponame>nfd/atj2127decrypt import os import sys import difflib def hexdump(b): for line in [b[n:n+16] for n in range(0, len(b), 16)]: charpart = ''.join(chr(x) if (x >= 0x20 and x <= 0x7e) else '.' for x in line) hexpart = ' '.join('%02x' % (x) for x in line) yield('%-48s %s' % (hexpart, charpart)) def hexco...
StarcoderdataPython
5143839
from typing import Any, Dict, Optional, Union from tartiflette import Scalar from tartiflette.constants import UNDEFINED_VALUE from tartiflette.language.ast import IntValueNode from tartiflette.utils.values import is_integer _MIN_INT = -2_147_483_648 _MAX_INT = 2_147_483_647 class ScalarInt: """ Built-in sc...
StarcoderdataPython
3547665
<gh_stars>1-10 import warnings import torch import torch.nn as nn try: from mmcv.ops import RoIAlign, RoIPool except (ImportError, ModuleNotFoundError): warnings.warn('Please install mmcv-full to use RoIAlign and RoIPool') try: import mmdet # noqa from mmdet.models import ROI_EXTRACTORS except (Impo...
StarcoderdataPython
4959058
<filename>aioqiwi/core/tooling/datetime.py import datetime import typing class DatetimeModule: TZD = "03:00" """Moscow city default timezone""" DATETIME_FMT = "%Y-%m-%dT%H:%M:%S+{}" """Qiwi API datetime format""" @property def datetime_fmt(self): """Get datetime format string with qi...
StarcoderdataPython
1626161
# Generated by Django 2.2.1 on 2019-07-09 04:04 from django.db import migrations, models import stdimage.models class Migration(migrations.Migration): dependencies = [ ('authentication', '0011_auto_20190625_1458'), ] operations = [ migrations.AddField( model_name='user', ...
StarcoderdataPython
3213299
<gh_stars>10-100 from django.db import migrations from django.utils import timezone def update_login(apps, schema_editor): UserModel = apps.get_model("users", "User") UserModel.objects.all().update(last_login=timezone.now()) class Migration(migrations.Migration): dependencies = [ ("users", "002...
StarcoderdataPython
4836614
<filename>graphics/VTK-7.0.0/Examples/Infovis/Python/streaming_statistics_pyqt.py #!/usr/bin/env python from __future__ import print_function from vtk import * import os.path import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot()...
StarcoderdataPython
4835658
from typing import Any, Optional import psycopg2 from pypandas_sql.dbconnector.db_connector import DBConnector from utils import config_helper, credential_helper, filepath_helper __CREDENTIALS__ = 'credentials' __ENGINE_NAME__ = 'redshift+psycopg2' class RedshiftConnector(DBConnector): def __init__(self) -> N...
StarcoderdataPython
9771384
from setuptools import setup setup( name="deviantart", version="0.1.5", description="A Python wrapper for the DeviantArt API", url="https://github.com/neighbordog/deviantart", author="<NAME>", author_email="<EMAIL>", license="MIT", packages=["deviantart"], install_requires=[ ...
StarcoderdataPython
113869
# Generated by Django 2.1.7 on 2019-06-03 05:58 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('contacts', '0003_merge_20190214_1427'), migrations.swappable_dep...
StarcoderdataPython