id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3453293
from spaceone.repository.manager.repository_manager import RepositoryManager class LocalRepositoryManager(RepositoryManager): def register_repository(self, params): # Assume there is only one local repository return self.repo_model.create(params)
StarcoderdataPython
12849110
import types from tf.advanced.helpers import dh from tf.advanced.find import loadModule from tf.advanced.app import App def transform_prime(app, n, p): return ("'" * int(p)) if p else "" def transform_ctype(app, n, t): if t == "uncertain": return "?" elif t == "properName": return "=" ...
StarcoderdataPython
3286016
import random TAG_MASC = "Masculine" TAG_FEMME = "Feminine" class Gender(object): def __init__(self, noun="person", adjective="nonbinary", subject_pronoun="ze", object_pronoun="zem", possessive_determiner="zir", absolute_pronoun="zirs", card_pattern="card_*_*.png", tags=(TAG_MAS...
StarcoderdataPython
354598
# -*- coding: utf-8 -*- from os import path as op from nose.tools import assert_raises, assert_true, assert_equal import numpy as np from mne._hdf5 import write_hdf5, read_hdf5 from mne.utils import requires_pytables, _TempDir, object_diff tempdir = _TempDir() @requires_pytables() def test_hdf5(): """Test HDF5...
StarcoderdataPython
4836310
# 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 may not u...
StarcoderdataPython
1913399
class MockController: def returns_instance_of(self, obj): pass
StarcoderdataPython
6438189
<gh_stars>0 # # Copyright (C) 2001-2004 <NAME> and Rational Discovery LLC # All Rights Reserved # """ The "parser" for compound descriptors. I almost hesitate to document this, because it's not the prettiest thing the world has ever seen... but it does work (for at least some definitions of the word). Rather than ...
StarcoderdataPython
11293354
# Copyright 2021 Zuru Tech HK Limited. 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 applicable la...
StarcoderdataPython
4891874
from pathlib import Path import click import pandas as pd import functions as f current_directory = Path(__file__).absolute().parent default_data_directory = current_directory.joinpath('..', '..', 'data') @click.command() @click.option('--data-path', default=None, help='Directory for the CSV files') def main(data_...
StarcoderdataPython
11327839
<reponame>rpSebastian/AutoCFR<gh_stars>1-10 import pandas as pd from pathlib import Path import matplotlib import matplotlib.pyplot as plt import seaborn as sns import numpy as np from autocfr.utils import load_df, remove_border, png_to_pdf plt.rc("pdf", fonttype=42) plt.rc("ps", fonttype=42) class PlotA...
StarcoderdataPython
6455594
<filename>statscraper/scrapers/work_injury_scraper.py # encoding: utf-8 """ A scraper to fetch Swedish work injury stats from http://webbstat.av.se This is an example of a scraper using Selenium. TODO: Move some useful functionality to a SeleciumFirefoxScraper To change download location: expor...
StarcoderdataPython
12863017
<gh_stars>1-10 """ Distributed under the MIT License. See LICENSE.txt for more info. """ from django import template register = template.Library() @register.filter def get_item(dictionary, key): """ Returns the object for that key from a dictionary. :param dictionary: A dictionary object :param key:...
StarcoderdataPython
9778189
import unittest from datetime import datetime import tempfile import netCDF4 as nc import os from ncagg.attributes import ( StratFirst, StratLast, StratUniqueList, StratIntSum, StratFloatSum, StratAssertConst, ) from ncagg.attributes import ( StratDateCreated, StratStatic, StratTime...
StarcoderdataPython
20217
<filename>gamestate-changes/change_statistics/other/rectangleAnimation.py<gh_stars>1-10 # https://stackoverflow.com/questions/31921313/matplotlib-animation-moving-square import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib import animation x = [0, 1, 2] y = [0, 10, 20] y2 = [40, 30, 20]...
StarcoderdataPython
9680799
<filename>tests/integration/test_charm.py #!/usr/bin/env python3 # Copyright 2021 Canonical Ltd. # See LICENSE file for licensing details. import base64 import json import logging import re from pathlib import Path import pytest import requests import tenacity import yaml from lightkube import Client from lightkube....
StarcoderdataPython
40500
<reponame>jbargu/imagetagger from django import forms from imagetagger.annotations.models import AnnotationType class AnnotationTypeCreationForm(forms.ModelForm): class Meta: model = AnnotationType fields = [ 'name', 'active', 'node_count', 'vector_...
StarcoderdataPython
375412
import math import pygame from utils import * from sprite import MySprite class Story(): def __init__(self, screen): self.screen = screen # Load all background images self.bg_dragon_castle = MySprite('pictures/dragon_castle.jpg') self.bg_lock_sword = MySprite('pictures/sword_lock...
StarcoderdataPython
240233
# -*- encoding: utf-8 -*- ''' @Time : 2018-3-19 @Author : EvilRecluse @Contact : https://github.com/RecluseXU @Desc : ROI与泛洪填充 ''' # here put the import lib import cv2 as cv import numpy as np def roi_demo(src): # ROI操作-----------ROI(Region of Interest) face = src[100:310, 170:400] # 框选出脸的位置,...
StarcoderdataPython
3420590
<reponame>Wolodija/aucote from unittest.mock import patch, MagicMock, call from cpe import CPE from os import path from tornado.concurrent import Future from tornado.httpclient import HTTPError, HTTPRequest, HTTPResponse from tornado.testing import gen_test, AsyncTestCase from fixtures.exploits import Exploit from s...
StarcoderdataPython
9736137
#coding=utf-8 import sys from selenium import webdriver import time import re reload(sys) sys.setdefaultencoding('utf-8') browser = webdriver.Chrome() browser.get('https://192.168.0.1') browser.maximize_window() browser.implicitly_wait(10) browser.find_element_by_id('iptUserName').send_keys('Admin') browser.impli...
StarcoderdataPython
6612834
<gh_stars>1-10 #! /usr/bin/env python # # # similar to test_FM, but in the official ADMIT environment # these are meant to be able to run without CASA, ie. in a # vanilla python environment # # you might need to run # rm ../at/__init__.py ../at/__init__.pyc ; touch ../at/__init__.py # before, an...
StarcoderdataPython
5141453
from stable_baselines.acer.acer_simple import ACER
StarcoderdataPython
1810880
import os import subprocess from typing import Dict import boto3 from absl import flags, logging from xain.helpers import project from xain.ops.ec2 import user_data FLAGS = flags.FLAGS root_dir = project.root() # Note: # We actually would like to use the m5.large up to m5.24xlarge # but AWS is not easily willing to...
StarcoderdataPython
4855048
from __future__ import print_function from setuptools import setup import raspgif setup( name='raspgif', version=raspgif.__version__, url='https://github.com/tomislater/raspgif', license='MIT License', author='<NAME>', author_email='<EMAIL>', description='Regional Atmospheric Soaring Pred...
StarcoderdataPython
11262517
<filename>src/solution_29c11459.py # This file has the solution to the task 29c11459.json from ioOps import read_file, get_file_path, print_grid import json import sys """ Method to find solution for the task 29c11459.json Args: data(input): The data grid to be processed Returns: Output grid with a line of t...
StarcoderdataPython
1844215
<filename>tests/test_api.py # Copyright (c) 2014 VMware, 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/LICENS...
StarcoderdataPython
1690319
""" Test request.render() and the predicates related to rendering """ def test_get_templatestring_view( fake_templatestring_view, requestservice, resourceservice, fake_article1 ): resourceservice.resources[fake_article1.id] = fake_article1 request = requestservice.make_reques...
StarcoderdataPython
5137009
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2008 <NAME> - CrysaLEAD - www.crysalead.fr from . import models from odoo import api, SUPERUSER_ID def _l10n_fr_post_init_hook(cr, registry): _preserve_tag_on_taxes(cr, registry) _setup_inaltera...
StarcoderdataPython
11390546
import pandas as pd from functions import random_iid def noisify(data, signal_col, noise_type, intensity, noisy_signal_col='degraded', normalize=False): """Adds noise to signal :param noisy_signal_col: name of column that should be created to save noisy data in :param data: Pandas Dataframe :param sig...
StarcoderdataPython
8070428
<reponame>Rijul24/StressMeOut-1<gh_stars>0 """MIT License Copyright (c) 2021 armaanbadhan 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 rig...
StarcoderdataPython
5144328
<reponame>forgi86/RNN-adaptation import os import numpy as np import time import torch import torch.nn as nn from models import LSTMWrapper from diffutil.products import jvp_diff, unflatten_like import torch.optim as optim from open_lstm import OpenLSTM from torchid import metrics if __name__ == '__main__': time...
StarcoderdataPython
12832581
from numpy import array, matrix, diag, exp, inner, nan_to_num from numpy.core.umath_tests import inner1d from numpy import argmin, array class GKS: """Gaussian kernel smoother to transform any clustering method into regression. setN is the list containing numpy arrays which are the weights of clustering centors. ...
StarcoderdataPython
5145721
#!/usr/bin/env python import os, sys import json import fnmatch, re from collections import namedtuple from ..helper import slugify from ..exceptions import * Key = namedtuple("Key", ["name","version"]) class Repo: """ Class to track each repo """ def __init__(self, username, reponame): self....
StarcoderdataPython
9737090
<reponame>YiWeiShen/Project-Euler-Hints from multiprocessing.pool import Pool import math def cal_dividor(num): list_a = [] i = 0 while num > 1: if num % prime_list_clear[i] == 0: print(prime_list_clear[i]) list_a.append(prime_list_clear[i]) num /= prime_list_cl...
StarcoderdataPython
4908470
from devices.cisco import CiscoIOS class CiscoIOSSSHTelnet(CiscoIOS): """ Class to represent Cisco IOS device to connect via ssh or telnet if unsure what connection is required """ def __init__(self, **kwargs): super(CiscoIOS, self).__init__(**kwargs) @property def device_type(self):...
StarcoderdataPython
254373
<filename>tests/python/pants_test/subsystem/subsystem_util.py<gh_stars>0 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.testutil.subsystem.util import global_subsystem_instance as global_subsystem_instance # noqa from pants...
StarcoderdataPython
9679414
import seaborn as sns from Perceptron import Perceptron, accuracy from sklearn.model_selection import KFold from sklearn import linear_model # Load dataframe sns.set(font_scale=1.5) df = sns.load_dataset('penguins') # We are going to try and find the difference between # Adelie and Gentoo penguins using all fields re...
StarcoderdataPython
12811128
<gh_stars>1-10 # -------------- # Importing header files import numpy as np import warnings warnings.filterwarnings('ignore') #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Reading file data = np.genfromtxt(path, delimiter=",", skip_header=1) #Code starts here census=np.concatenate((data,ne...
StarcoderdataPython
11274620
from django.core.management import BaseCommand from django.conf import settings class Command(BaseCommand): def handle(self, *args, **options): for key, value in settings.ENV.__dict__.items(): print(f'{key:25} {value}')
StarcoderdataPython
343082
<filename>cap02_variaveis_tipos_estrututurasDeDados/exercicios/ex01.py # Exercício 1 - Imprima na tela os números de 1 a 10. Use uma lista para armazenar os números. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers)
StarcoderdataPython
3386335
import time from django.core.wsgi import get_wsgi_application import os import subprocess import logging from loghandler.loghandler import setup_logging setup_logging() logger = logging.getLogger(__name__) # Django specific settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") # Ensure settings are re...
StarcoderdataPython
6404852
<reponame>hooooolyshit/VocabularyNoteBook<filename>bing.py import requests import bs4 import time import random # 暂时没用的class class ExampleSentance: meanings = '' sentences = [] def set_meaning(self, meanings): self.meanings = meanings def add_sentence(self, s): if ty...
StarcoderdataPython
3590322
<reponame>leandroaquinopereira/real-estate from django.contrib.messages.views import SuccessMessageMixin from django.shortcuts import render # Create your views here. from django.urls import reverse_lazy from django.views.generic import ListView, DetailView, DeleteView, CreateView, UpdateView from records.forms impor...
StarcoderdataPython
4922542
<reponame>scrasmussen/icar import numpy as np import units from bunch import Bunch R=8.3144621 # J/mol/K cp=29.19 # J/mol/K =1.012 J/g/K g=9.81 # m/s^2 def convert_atm(data,sfc): output_data=Bunch() # [time,z,ns,ew] output_data.u = data.u # m/s output_data.v = da...
StarcoderdataPython
1690984
from tensorflow_sparsemax.sparsemax_regression import SparsemaxRegression
StarcoderdataPython
3480561
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
StarcoderdataPython
1864238
<reponame>saydulk/admin4<gh_stars>0 # The Admin4 Project # (c) 2013-2014 <NAME> # # Licensed under the Apache License, # see LICENSE.TXT for conditions of usage moduleinfo={ 'name': "PostgreSQL Server", 'modulename': "PostgreSQL", 'description': "PostgreSQL database server", 'vers...
StarcoderdataPython
11397121
<reponame>mzy2240/GridCal<gh_stars>100-1000 import pandas as pd import numpy as np from scipy.sparse import lil_matrix, csc_matrix pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) # file_name = 'D:\\GitHub\\GridCal\\Grids_and_profiles\\grids\\Reduc...
StarcoderdataPython
5112196
<reponame>lvxiaojie111/2019NCCCU- import os #read pic from col from PIL import Image #array col import numpy as np import tensorflow as tf #data file data_dir="data" #train or test train=True #MODEL PATH model_path="model/image_model" #read pic and label from file #label form:1_400.jpg def read_data(data_dir): da...
StarcoderdataPython
9660223
<filename>run_client.py import sys from Client import * if __name__ == '__main__': log = logger.getChild('Run_Client') try: mainWindow.show() sys.exit(app.exec_()) except Exception as err: log.error(err)
StarcoderdataPython
9748032
<filename>tests/api/users/test_user.py # -*- coding: utf-8 -*- """ Onyx Project https://onyxlabs.fr Software under licence Creative Commons 3.0 France http://creativecommons.org/licenses/by-nc-sa/3.0/fr/ You may not use this software for commercial purposes. @author :: <NAME> """ import json import pytest from flask i...
StarcoderdataPython
12817521
<filename>tools/mo/openvino/tools/mo/front/tf/lrn_ext.py<gh_stars>1-10 # Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openvino.tools.mo.front.extractor import FrontExtractorOp from openvino.tools.mo.ops.lrn import AttributedLRN class LRNExtractor(FrontExtractorOp): """ ...
StarcoderdataPython
3288935
class Borg(object): _shared_state = {} def __new__(cls, *a, **k): obj = object.__new__(cls, *a, **k) obj.__dict__ = cls._shared_state return obj def __hash__(self): return 9 # any arbitrary constant integer def __eq__(self, other): try: return self.__dict__ is other....
StarcoderdataPython
1611384
#To input username&pass and check if it's correct. Q22 #Made by INS, Using dictionary for faster credential check. d={} while True: x=raw_input("Enter a user name : ") y=raw_input("Enter a password : ") d[x]=y cont=raw_input("Do you want to add more usernames? [y/n] ") if cont=='y': ...
StarcoderdataPython
11210713
import unittest import numpy as np import os import pycqed as pq import time import openql import warnings import pycqed.analysis.analysis_toolbox as a_tools import pycqed.instrument_drivers.virtual_instruments.virtual_AWG8 as v8 import pycqed.instrument_drivers.virtual_instruments.virtual_SignalHound as sh import pyc...
StarcoderdataPython
11217518
<filename>Python/1235.py<gh_stars>0 def execucoes(): return int(input()) def entrada(): return input() def imprimir(v): print(v) def dividir(s): return (int(len(s)/2) -1) def processar(e, s): return (s[e::-1] + s[len(s)-1:e:-1]) def decifrar(n, e): n -= 1 imprimir(processar(dividir(e), ...
StarcoderdataPython
225414
<filename>silver/migrations/0034_auto_20170203_1644.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("silver", "0033_auto_20170203_1540"), ] operations = [ migrations.AddF...
StarcoderdataPython
4890562
"""Evaluation of the model.""" import numpy as np import tensorflow as tf import os import logging import sys import imp import include.tensorvision.utils as utils logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG, stream=sys.stdout) FL...
StarcoderdataPython
8069829
# # DVI.py # # (c) 2020 by <NAME> # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:DeviceInfo # from .MgmtObj import * from Constants import Constants as C from Validator import constructPolicy import Utils # Attribute policies for this resource are constructed duri...
StarcoderdataPython
8135650
<reponame>Joe310/GenomeBuilder """ Created on June 20, 2014 @author: <NAME> """ import time import mmap import random import sys import re import argparse import pickle import shutil import unittest import os from heapq import merge class chromosome_builder(): def __init__(self, args=None): if not args: ...
StarcoderdataPython
8069786
import pathlib class FileMissingError(Exception): def __init__ (self, path_to_file): self.path_to_file = path_to_file def __str__ (self): return "File " + self.path_to_file + " doesn't exist!" class Target: def __init__ (self, output_path): self.output_path = output_path def...
StarcoderdataPython
9619523
<reponame>OCHA-DAP/hdx-ckan import datetime import ckan.lib.helpers as h import ckan.plugins.toolkit as tk import ckanext.hdx_search.controller_logic.search_logic as sl _ = tk._ from ckanext.hdx_package.helpers.freshness_calculator import UPDATE_STATUS_URL_FILTER,\ UPDATE_STATUS_UNKNOWN, UPDATE_STATUS_FRESH, UPD...
StarcoderdataPython
3400830
/home/runner/.cache/pip/pool/a4/b9/c2/6cef50a2615b8634e197d0968a205ba0b576e792319aeb4ac358edd850
StarcoderdataPython
8019695
from django import forms from sistema.mail import send_mail_template from .models import Cliente from usuario.models import Usuario from carteira.models import Carteira from eth_account import Account from web3 import Web3 import random class ClienteNovoForm(forms.ModelForm): name = forms.CharField(label='Nome',wi...
StarcoderdataPython
9755484
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved. The source code contained or described here in and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains wi...
StarcoderdataPython
4814494
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
StarcoderdataPython
6460753
<reponame>alex-mil/gcleaner<filename>python2/gcleaner.py<gh_stars>0 import sys if sys.version_info[0] > 2: sys.stderr.write("Python version must be 2.x.x\n") sys.exit(-1) from os import path, curdir, walk from subprocess import Popen, PIPE from threading import Timer class GCleaner(object): def __init__...
StarcoderdataPython
4885729
<gh_stars>1-10 import sqlite3, datetime class DateTimeParseError (RuntimeError): pass #stupid sqlite datetime_fields = { "last_login", "expiration", "expiration", "time" } def sql_close_connections(): return; def parse_dt(str): i = [0] def expect(s): if not str[i[0]:].startswith(s): raise D...
StarcoderdataPython
3396230
<gh_stars>100-1000 import argparse import time import os import shutil import logging import torch import torch.backends.cudnn as cudnn import loaddata from tqdm import tqdm from models import modules, net, resnet from util import query_yes_no from test import test from tensorboardX import SummaryWriter parser = argpa...
StarcoderdataPython
1924077
import sys cache = {} def num_pebbles(pos): return len([1 for x in pos if x == 'o']) def move(pos, n, m): p = pos[:] p[n] = '-' p[(n+m)//2] = '-' p[m] = 'o' return p def min_number_pebbles(pos): assert len(pos) == 23 try: return cache[''.join(pos)] except: pas...
StarcoderdataPython
158810
import os from ..exceptions import ArgumentError from ..thirdparty.download import download_binaries from ..thirdparty.kaldi import collect_kaldi_binaries, validate_kaldi_binaries def validate_args(args): available_commands = ['download', 'validate', 'kaldi'] if args.command not in available_commands: ...
StarcoderdataPython
3510397
"""Simple calculation to find most UTM zones given (lat/lng) coordinate.""" import math def lat_lng_to_epsg(lat_coord, lng_coord): """Calculate the EPSG code of the given WGS84 (lat/lng) coordinate. Parameters: lat_coord (float): number between -90 and 90 indicating latitute coordinate. ...
StarcoderdataPython
3340331
<reponame>TooTouch/tootorch<filename>setup.py<gh_stars>1-10 from setuptools import setup, find_packages with open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name = 'tootorch', version = '0.2', long_description = long_description, ...
StarcoderdataPython
8068740
from __future__ import absolute_import from mock import Mock from celery.concurrency.threads import NullDict, TaskPool, apply_target from celery.tests.case import AppCase, Case, mask_modules, mock_module class test_NullDict(Case): def test_setitem(self): x = NullDict() x['foo'] = 1 wit...
StarcoderdataPython
1626015
<gh_stars>0 """ Backward compatibility support for Python 3.5 """ import sys import test.support import subprocess # copied from Python 3.9 test.support module def _missing_compiler_executable(cmd_names=[]): """Check if the compiler components used to build the interpreter exist. Check for the existence of ...
StarcoderdataPython
4972408
def extractNanjamora(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Endless Dantian' in item['tags']: return buildReleaseMessageWithType(item, 'Endless Dantian', vol, chp, frag=frag, postfix=po...
StarcoderdataPython
6557453
<reponame>inidun/unesco_data_collection from pathlib import Path from tempfile import TemporaryDirectory from typing import List from courier.config import get_config from courier.extract.interface import ITextExtractor from courier.extract.tesseract_extractor import TesseractExtractor from courier.extract.utils impor...
StarcoderdataPython
4917257
from pyteal import * from blob import Blob def test(): b = Blob() test = Seq( Pop(b.write(Int(0), Int(0), Bytes("deadbeef" * 16))), Log(b.read(Int(0), Int(8), Int(32))), Int(1), ) return Cond( [Txn.application_id() == Int(0), Int(1)], [Txn.on_completion() == On...
StarcoderdataPython
192725
from fabric.api import task, local @task def start(): local("fab server.start:server=mooc,mooc") def stop(): local("fab server.stop")
StarcoderdataPython
6535204
<reponame>josecostamartins/pythonreges # *-* coding: utf-8 *-* ''' 1. Classe Bola: Crie uma classe que modele uma bola: a. Atributos: Cor, circunferência, material b. Métodos: trocaCor e mostraCor ''' class Bola(object): def __init__(self, cor, circunferencia, material): self.cor = cor sel...
StarcoderdataPython
4829202
from decimal import Decimal import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounting', '0001_squashed_0052_ensure_report_builder_plans'), ('sms', '0010_update_sqlmobilebackend_couch_id'), ] operations ...
StarcoderdataPython
5155768
""" Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example : Given s = "aab", Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. """ class Solution: def plindrome_part...
StarcoderdataPython
1843750
import tensorflow as tf import numpy as np #100 phony y, x data points are created in NumPy, y = 0.3 + x * 0.1 x_data = np.random.rand(100).astype(np.float32) y_data = x_data * 0.1 + 0.3 # calculate y_data = b + W * x_data, by finding the values for b and W # Knowing that b should be 0.3 and W 0.1, but it will be fig...
StarcoderdataPython
1663092
"""Implements a buildable, serializable, deserializable lexicon.""" from typing import Any, Dict, Iterator, Tuple, Union, Optional from textprobability.core.types import ( Unit, Probability, NGram, ContextLexicon, Splitter, Text, Lexicon, ) SerializableLexicon = Tuple[Dict[Unit, int], int...
StarcoderdataPython
6599429
arr = [25, 11, 7, 87, 56]; max = arr[0]; for i in range(0, len(arr)): if(arr[i] > max): max = arr[i]; print("Largest element present in given array: " + str(max));
StarcoderdataPython
1803431
#Importando as coisas que o código precisa para funcionar import pandas as pd import requests from bs4 import BeautifulSoup #def que retorna a informação def RetornarResposta(req): print("0 = Visão geral") print ("1 = Casos ativos no mundo") print("3 = Casos leves ativos no mundo") print("5 = Casos se...
StarcoderdataPython
4946783
<reponame>Sannso/GameCG2 import pygame import configparser #850×480 ANCHO=850 #x4 = 3400 ALTO=480 #x3 = 1440 if __name__ == '__main__': pygame.init() pantalla=pygame.display.set_mode([ANCHO,ALTO]) archivo=configparser.ConfigParser() archivo.read('info_mapa.txt') nom_imagen=archivo.get('info'...
StarcoderdataPython
6401810
import os import pathlib from typing import List import boto3 import botocore def s3_bucket_exists(name: str) -> bool: s3 = boto3.client("s3") try: s3.head_bucket(Bucket=name) except botocore.exceptions.ClientError as e: print(e) return False return True def file_exists(buck...
StarcoderdataPython
5194328
# -*- coding: utf-8 -*- import ujson from flask import request from flask_restplus import Namespace, Resource, fields from models.user import User as orm_user from models.project import Project as orm_project from models.file import File as orm_file from orator.exceptions.orm import ModelNotFound from orator.exception...
StarcoderdataPython
12838081
''' Tkinter implementation of Meta Noughts and Crosses. Requires Python >3.6, tkinter and mnac. 1.0: release 1.1: keyboard indicators / keyboard controls are like numpad 1.2: new status menu, controls, help menu 1.3: better mouse handling 1.4: UI tweaks and touchups ''' import random import os import tkinter as tk i...
StarcoderdataPython
3294069
#!/usr/bin/python import subprocess p = subprocess.Popen(["ps", "-aux"], stdout=subprocess.PIPE) out, err = p.communicate() if ('netdisco-dhcp-listener.py' in out): print('\nDHCP Sniffer is running') else: print('\nDHCP Sniffer NOT running!') if ('netdisco-pinger.py' in out): print('Pinger is running') e...
StarcoderdataPython
1943769
<reponame>efabless/volare #!/usr/bin/env python3 from setuptools import setup, find_packages from volare import __version__ requirements = open("requirements.txt").read().strip().split("\n") setup( name="volare", packages=find_packages(), version=__version__, description="A sky130 PDK builder/version...
StarcoderdataPython
5036684
from summariser.vector.vector_generator import Vectoriser from summariser.utils.corpus_reader import CorpusReader from resources import * from summariser.utils.writer import append_to_file import sys def writeSample(actions,reward,path): if 'heuristic' in path: str = '\nactions:' for act in actio...
StarcoderdataPython
105421
<filename>src/navi/components/other/low_pass_filter.py from navi.components.component import Component __author__ = 'paoolo' class LowPassFilter(Component): """ Used to low pass. """ def __init__(self): super(LowPassFilter, self).__init__(enable=True) self._old_left = 0.0 se...
StarcoderdataPython
6686830
from __future__ import annotations import os from pathlib import Path from typing import Union, TypeVar, Type, Generic from loguru import logger from transformers import PreTrainedModel from codenets.recordable import RecordableTorchModule from codenets.utils import full_classname, instance_full_classname, runtime_im...
StarcoderdataPython
3254290
from .base import * # noqa pylint: disable=unused-import,unused-wildcard-import,wildcard-import from sentry_sdk.integrations.celery import CeleryIntegration from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.logging import LoggingIntegration import logging import sentry_sdk DE...
StarcoderdataPython
3297147
import numpy as np import os from glob import glob import scipy.io as sio from skimage.io import imread, imsave from time import time from api import PRN from utils.write import write_obj_with_colors # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = '0' # GPU number, -1 for CPU prn = PRN(is_dlib = False) # ----...
StarcoderdataPython
1919890
#!/home/andrew/.envs/venv38/bin/python3 import sys import numpy as np def read_input(): vent_lines = [] for line in sys.stdin: halves = (x.strip() for x in line.strip().split("->")) points = [[int(x) for x in y.split(",")] for y in halves] vent_lines.append(points) return vent_li...
StarcoderdataPython
1910845
from .utils import get_cv_data_ann_kfold as get_cv_data from .optimizer import Optimizer as Opt from .stats import calculate_p_values from collections import namedtuple from .full_model import FullModel from .model import Model import numpy as np TestResult = namedtuple('TestResult', ['ml_trn', 'ml_cv_mean', 'ml_cv'])...
StarcoderdataPython
1906246
<gh_stars>1-10 # -*- coding: utf-8 -*- # pylint: disable=C0103 """ This module contains project settings. """ from __future__ import print_function from __future__ import unicode_literals import os # Host and port for web server to listen HOST = "0.0.0.0" PORT = 9999 # Number of seconds to sleep before sending HTTP...
StarcoderdataPython