id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1656245 | #!/usr/bin/env python3
import math
def main():
# enter you solution here
if __name__ == "__main__":
main()
| StarcoderdataPython |
4810021 | <filename>py/test/selenium/webdriver/ie/ie_launcher_tests.py
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under t... | StarcoderdataPython |
3347359 | from __future__ import annotations
import pandas as pd
from patsy import dmatrix
from sklearn.base import BaseEstimator, TransformerMixin
from hcl_model.labels import LabelsCommon, LabelsExog
class AddPeriodicSplines(BaseEstimator, TransformerMixin):
lbl = LabelsCommon()
lbl_exog = LabelsExog()
def __i... | StarcoderdataPython |
56447 | <reponame>kuyu12/pygame_fight_game
import pygame
from pygame.rect import Rect
from utils.color import WHITE
from utils.path_utils import PROFILE_IMAGES_PATH
from utils.utils_factory import UtilsFactory
from views.gui_views.surface_inteface import SurfaceInterface
# self.player_name = self.player_info_data[InfoMapper... | StarcoderdataPython |
1701041 | import torch
from torchvision import datasets, transforms
from utils.sampling import mnist_iid, mnist_iid_normal, mnist_noniid, cifar_iid, mnist_noniid_normal, minmax_dataset, fmnist_iid_normal, fmnist_noniid_normal
import numpy as np
import random
def load_data(args):
# load dataset and split users
if args.dat... | StarcoderdataPython |
1740449 | """Setup config for the varats namespace package."""
import os
from setuptools import find_namespace_packages, setup
base_dir = os.path.dirname(__file__)
with open(base_dir + '/README.md') as f:
long_description = f.read()
setup(
name='varats',
version='11.1.3',
url='https://github.com/se-sic/vara-t... | StarcoderdataPython |
4826309 | <reponame>samrika25/TRAVIS_HEROKU_GIT
from .DetailView import * | StarcoderdataPython |
3333744 | import pandas as pd
# Excelファイルを開く --- (※1)
filename = "population.xlsx" # ファイル名
sheet_name = "list-sjis.csv" # シート名
book = pd.read_excel(filename, sheetname=sheet_name)
# データを人口順に表示 --- (※2)
book.sort_values(by="法定人口", ascending=False)
print(book)
| StarcoderdataPython |
3273407 | <filename>git.py
# Import all the required modules
import os, sys, time
# Clear the screen
sys.stdout.write('\x1bc')
# Our main function
def main():
sys.stdout.write('(\033[1;32mInfo\033[1;0m): Please enter your commit message\n')
sys.stdout.write('(\033[1;32mInfo\033[1;0m): You can also enter \'exit... | StarcoderdataPython |
12424 | # Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
__version__ = "0.0.8"
# flake8: noqa: F401,F402
from . import errors, events, relation, testing
from .relation import EndpointWrapper
| StarcoderdataPython |
3389830 | import os
import numpy as np
from scipy.io import loadmat, whosmat
from mindaffectBCI.decoder.utils import block_randomize, butter_sosfilt, upsample_codebook, lab2ind, window_axis
marker2stim=dict(lh=(1,3),rh=(2,4))
def load_twofinger(datadir, sessdir=None, sessfn=None, fs_out=60, stopband=((45,65),(0,1),(25,-1)), su... | StarcoderdataPython |
1688234 | <filename>cmg/mathlib/vec2.py
import math
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def vec2_oper(op, self, other):
if isinstance(other, Vec2) or isinstance(other, tuple):
return Vec2(op(self.x, other.x), op(self.y, other.y))
else:
re... | StarcoderdataPython |
3376395 | <gh_stars>1-10
import os
import shutil
from glob import glob
from pathlib import Path
class PathUtil:
@staticmethod
def get_root_path():
"""
- retorna: O caminho raiz do programa
"""
root_path = os.getcwd()
return root_path
@staticmethod
def get_dirs(root_p... | StarcoderdataPython |
89817 | <filename>pointpats/window.py<gh_stars>0
"""
Window class for point patterns
"""
__author__ = "<NAME> <EMAIL>"
import libpysal as ps
import numpy as np
__all__ = ["as_window", "poly_from_bbox", "to_ccf", "Window"]
def poly_from_bbox(bbox):
l, b, r, t = bbox
c = [(l, b), (l, t), (r, t), (r, b), (l, b)]
r... | StarcoderdataPython |
146610 | # 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
__a... | StarcoderdataPython |
3265003 | from intcode import Computer
def p1():
c = Computer("input.txt")
out = c.run(1)
print(out)
return out[-1]
def p2():
c = Computer("input.txt")
out = c.run(5)
return out[-1]
| StarcoderdataPython |
3266095 | <gh_stars>1-10
# Don't call this flask.py!
# Documentation for Flask can be found at:
# https://flask.palletsprojects.com/en/1.1.x/quickstart/
from flask import Flask, render_template, request, session, redirect, url_for, jsonify, abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_
from werkzeug.... | StarcoderdataPython |
98085 | <gh_stars>0
from unittest import main, TestCase
from unittest.mock import patch
from importlib import reload
import grader.self as grader
class TestGrading(TestCase):
def print_loud(self, msg, end='\n'):
self.assertEqual(int(msg), 5, msg='{} has to fail for default Selfie'.format(self.current_assignment))
... | StarcoderdataPython |
1608825 | #!/usr/bin/env python3
# ISKRA MT174 Smartmeter, Optical serial power consumption monitor
#
# Hardware:
# - Energiesensor für Smart Meter ES-IEC at /dev/ttyUSB0
# https://de.elv.com/elv-homematic-energiesensor-fuer-smart-meter-es-iec-komplettbausatz-142148
# - 4 digit TM1637 display
#
# need library/packages:
#... | StarcoderdataPython |
3385398 | <gh_stars>0
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Test... | StarcoderdataPython |
3213577 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on %(date)s
@author: %(username)s
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from functools import wraps
class Parent():
def decorate(f):
@wraps(f)
def decorated(*args, **kwargs):
pr... | StarcoderdataPython |
1761555 | # Generated by Django 3.2.6 on 2021-08-20 12:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('content', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='category',
... | StarcoderdataPython |
1645417 | <reponame>dls-controls/bluefly<filename>bluefly/cli.py
from argparse import ArgumentParser
from bluefly import __version__
def main(args=None):
parser = ArgumentParser()
parser.add_argument("--version", action="version", version=__version__)
args = parser.parse_args(args)
| StarcoderdataPython |
1703566 | from newrelic.agent import wrap_function_trace
def instrument_tornado_httputil(module):
if hasattr(module, 'parse_body_arguments'):
wrap_function_trace(module, 'parse_body_arguments')
if hasattr(module, 'parse_multipart_form_data'):
wrap_function_trace(module, 'parse_multipart_form_data')
| StarcoderdataPython |
94952 | ##############################################################
# The bodyPartsDetection python module is the one which apply
# wished body parts detection to images and webcam frames
##############################################################
import cv2
# Specified class to apply body parts detections
class bodyPa... | StarcoderdataPython |
1760569 | <reponame>jp-96/micropython
# test calling a function with multiple **args
def f(a, b=None, c=None):
print(a, b, c)
f(**{"a": 1}, **{"b": 2})
f(**{"a": 1}, **{"b": 2}, c=3)
f(**{"a": 1}, b=2, **{"c": 3})
try:
f(1, **{"b": 2}, **{"b": 3})
except TypeError:
print("TypeError")
# test calling a method wit... | StarcoderdataPython |
1673687 | <reponame>Macuyler/mac
"""
src.output:
* Output functions for use throughout the code.
"""
def log(txt=None, err=False, blank=False, pad=False, dunn=False):
"""
Print a formatted log to the user.
"""
if pad:
print()
if blank:
print(txt)
elif err:
print(f' ! {txt}')
... | StarcoderdataPython |
114243 | # This problem was recently asked by Google:
# Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions?
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Function to print the list
def printList... | StarcoderdataPython |
3319103 | import unittest
import responses
from tests.api.base import MediaFireApiTestCase
from mediafire.api import MediaFireApiError
class TestErrorResponse(MediaFireApiTestCase):
def __init__(self, *args, **kwargs):
super(MediaFireApiTestCase, self).__init__(*args, **kwargs)
self.url = self.build_url(... | StarcoderdataPython |
60777 | import os
import logging
import re
from copy_reg import pickle
from multiprocessing import Pool
from subprocess import check_output
from types import MethodType
from RsyncUploadThread import RsyncUploadThread
from mongodb_consistent_backup.Common import config_to_string
from mongodb_consistent_backup.Errors import O... | StarcoderdataPython |
1610195 | <gh_stars>0
from django.db import models
import datetime as dt
from django.contrib.auth.models import User
from tinymce.models import HTMLField
from PIL import Image
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank... | StarcoderdataPython |
1795347 | """ create minimal-length, increasing IDs for couchdb """
from threading import Lock
from uuid import uuid4
from time import time
from random import choice
class IDFactory(object):
def create_id(self):
pass
class RandomIDFactory(IDFactory):
def create_id(self):
return uuid4().hex
class Sal... | StarcoderdataPython |
3238951 | import torch
from jaclearn.logic.propositional.logic_induction import search
from tqdm import tqdm
def get_logic_formula(inputs, outputs, in_names, f):
"""
Return searched logic formula
inputs, outputs are torch tensors
in_names are the names for input
f[k] is the set of considered variables for t... | StarcoderdataPython |
3371728 | # -*- coding: utf-8 -*-
from unittest import mock
from unittest.mock import MagicMock, Mock
from asyncy import Metrics
from asyncy.Exceptions import AsyncyError, InvalidKeywordUsage
from asyncy.Stories import Stories
from asyncy.Types import StreamingService
from asyncy.constants.LineConstants import LineConstants
fro... | StarcoderdataPython |
3285048 | <reponame>rlaphoenix/BasicSR
from __future__ import absolute_import
import os
import logging
from collections import OrderedDict
import itertools
import torch
import torch.nn as nn
import models.networks as networks
from .base_model import BaseModel, nullcast
from . import losses
from . import optimizers
from . imp... | StarcoderdataPython |
1755585 | <reponame>jiadaizhao/LintCode<filename>1001-1100/1043-Couples Holding Hands/1043-Couples Holding Hands.py
class Solution:
"""
@param row: the couples' initial seating
@return: the minimum number of swaps
"""
def minSwapsCouples(self, row):
# Write your code here
count = 0
tab... | StarcoderdataPython |
1647123 | <reponame>E-RROR/django-file-upload-handler
"""
# @2019
#
# Write Test For Djfiler
#
# <NAME>
#
"""
import unittest
import json
import os
from djfiler import djfiler
from djfiler.core import namegen, founder
tests_dir = os.getcwd()+'/djfiler/tests'
# Test Name Generation
def test_namegen():
"""
Test Nam... | StarcoderdataPython |
47316 | <reponame>tfukaza/harvest<gh_stars>10-100
# Builtins
import datetime as dt
from typing import Any, Dict, List, Tuple
import os.path
from pathlib import Path
# External libraries
import pandas as pd
import numpy as np
from tqdm import tqdm
import pytz
# Submodule imports
from harvest.storage import PickleStorage
impor... | StarcoderdataPython |
1709261 | def c_star(x, β, γ):
return (1 - β ** (1/γ)) * x
def v_star(x, β, γ):
return (1 - β**(1 / γ))**(-γ) * (x**(1-γ) / (1-γ))
| StarcoderdataPython |
3238911 | <gh_stars>0
import datetime
import os
from unittest.mock import patch
import httplib2
import pytest
from googleapiclient.http import HttpMock, RequestMockBuilder
from inapppy import googleplay, errors, GooglePlayVerifier
def test_google_verify_subscription():
with patch.object(googleplay, "build", return_value=... | StarcoderdataPython |
3247942 | <reponame>ashemedai/hatch
from hatch.project.core import Project
def test_default(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = '<NAME>'
with temp_dir.as_cwd():
result = hatch('new', project_name)
... | StarcoderdataPython |
3379879 | # Floor implementation in Python3
import os
import sys
def floor(n):
return -1
if __main__=="__main__":
# DO NOTHING FOR NOW :)
| StarcoderdataPython |
3318678 | <filename>ticketing_gen.py
from PIL import Image, ImageFont, ImageDraw
from datetime import datetime, timedelta
import calendar
from math import ceil
import csv
import os
# ini
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser # ver. < 3.0
import... | StarcoderdataPython |
122462 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import beanmachine.ppl as bm
import torch.distributions as dist
from torch import Tensor
class BetaBinomialModel(object):
"""This Bean... | StarcoderdataPython |
1689816 | import sys
import wordnet
import argparse
import os
import pickle
from autocorrect import Speller
def update_def(wn, synset, defn, add):
spell = Speller(lang='en')
if any([spell(w) != w for w in defn.split()]):
if input(
"There may be spelling errors in this definition. Proceed [y/N] :... | StarcoderdataPython |
3334415 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import logging
from django.conf import settings
from django.db import models
from django.db.models import CASCADE
from django.utils import timezone
if settings.DATABASES['default']['ENGINE'] == 'django.db... | StarcoderdataPython |
3318141 | <reponame>joshuaipwork/cdptools
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
from pathlib import Path
from unittest import mock
import pytest
from cdptools.file_stores.app_dirs_file_store import AppDirsFileStore
@pytest.fixture
def fs(tmpdir):
with mock.patch("appdirs.user_data_dir") as MockAppD... | StarcoderdataPython |
1788703 | from django.conf import settings
from django.contrib import admin, messages
from jcasts.podcasts import feed_parser, models
@admin.register(models.Category)
class CategoryAdmin(admin.ModelAdmin):
ordering = ("name",)
list_display = (
"name",
"parent",
)
search_fields = ("name",)
cla... | StarcoderdataPython |
3307215 | from energy_py.common.policies.epsilon_greedy import epsilon_greedy_policy
from energy_py.common.policies.softmax import softmax_policy
policy_register = {
'epsilon_greedy': epsilon_greedy_policy,
'softmax': softmax_policy
}
| StarcoderdataPython |
1688304 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-import itertools as it
import numpy as np
_convertible = {
# lvalue : rvalue
'b': 'b',
'i': 'iu',
'u': 'iu',
'f': 'f',
'c': 'c',
'm': 'm',
'M': 'M',
'O': 'O',
'S': 'S',
'U': 'U',
'V': 'V'
}
def can_cast(src, ... | StarcoderdataPython |
3343266 | <gh_stars>1-10
# coding=utf-8
# Copyright 2010 <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 la... | StarcoderdataPython |
1672516 | <filename>text_cnn/train.py
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from text_cnn.graph import Graph
import tensorflow as tf
from utils.load_data import load_data
from text_cnn import args
x, y = load_data('input/train.csv', data_size=None)
eval_index = int(0.9 * len(x))
... | StarcoderdataPython |
1714389 | # -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=missing-docstring
"""Test for the DAGCircuit object"""
import unittest
from qiskit.dagcircuit import DAG... | StarcoderdataPython |
95215 | import unittest
from pygame.tests.test_utils import question, prompt
import pygame
pygame.cdrom.init()
# The number of CD drives available for testing.
CD_DRIVE_COUNT = pygame.cdrom.get_count()
pygame.cdrom.quit()
class CDROMModuleTest(unittest.TestCase):
def setUp(self):
pygame.cdrom.ini... | StarcoderdataPython |
134172 | <filename>utilities/plotting.py
# -*- encoding: utf-8 -*-
"""Function for Plotting"""
import seaborn as sns
from IPython import display
from typing import Iterable
import matplotlib.pyplot as plt
plt.ion() # interactive
sns.set_style('whitegrid');
plt.style.use('default-style');
def plot(x_args : Iterable[Iterable]... | StarcoderdataPython |
3203783 | <filename>request-management-api/request_api/models/NotificationTypes.py<gh_stars>0
from .db import db, ma
from .default_method_result import DefaultMethodResult
from sqlalchemy.orm import relationship,backref
from datetime import datetime
from sqlalchemy import text
class NotificationType(db.Model):
__tablename_... | StarcoderdataPython |
1777899 | <filename>evaluate-from-csv.py
"""
This script reads news URLs from a CSV and runs our code against them for evaluation. It compares parsing raw HTML,
HTML rendered by a headless browser so JS can run, and also runs Goose's extraction code. This produces a CSV we
can use for comparing how well our code performs in a... | StarcoderdataPython |
3292380 | <reponame>Jeremiad/Flexget
import pytest
from flexget.components.managed_lists.lists.radarr_list import RadarrAPIService
RADARR_API_KEY = '65e246ce581a426781e1a8645f0a1f2c'
RADARR_BASE_URL = 'http://127.0.0.1'
RADARR_PORT = 7878
# Load up a radarr container and put VCR in record mode to record.
# NOTE: You'll need to... | StarcoderdataPython |
5284 | <filename>Perforce/AppUtils.py
import os
import sys
import re
import logging
p4_logger = logging.getLogger("Perforce")
# Import app specific utilities, maya opens scenes differently than nuke etc
# Are we in maya or nuke?
if re.match( "maya", os.path.basename( sys.executable ), re.I ):
p4_logger.info("Conf... | StarcoderdataPython |
1773492 | import expressions
import parse
import operators
Sum = operators.OpExprUniform
Prod = operators.OpExprUniform
Mod = operators.OpExprUniform
class Power(expressions.Expression):
def __init__(self, parent, expr):
super(Power, self).__init__(parent)
self.value = parse.parse(self, expr.children[0])
... | StarcoderdataPython |
23425 | <filename>src/stations/datastructures.py
from enum import Enum
# ifu
ifu = {"name": "IFU", "geo_lat": 47.476180, "geo_lon": 11.063350}
# tereno stations
tereno_stations = [
{"name": "Fendth", "geo_lat": 47.83243, "geo_lon": 11.06111},
{"name": "Grasswang", "geo_lat": 47.57026, "geo_lon": 11.03189},
{"name... | StarcoderdataPython |
3234010 | <reponame>olavolav/textplot<filename>uniplot/options.py
from dataclasses import dataclass, field
from typing import List, Optional
import numpy as np # type: ignore
def _default_gridlines() -> List[float]:
return [0.0]
def _default_lines() -> List[bool]:
return [False]
@dataclass
class Options:
# Col... | StarcoderdataPython |
133816 | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address, DEFAULT_ATTACHMENT_MIME_TYPE
from django.core.mail.backends.smtp import EmailBackend
from ..models import *
class ... | StarcoderdataPython |
133009 | <filename>hikari/api/event_factory.py
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021 davfsa
#
# 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 Sof... | StarcoderdataPython |
4837984 | <reponame>vgmartinez/luigi
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | StarcoderdataPython |
3241509 | # Language: Python
# Level: 8kyu
# Name of Problem: Keep Hydrated!
# Instructions: Nathan loves cycling.
# Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling.
# You get given the time in hours and you need to return the number of litres Nathan will drink,
# rounde... | StarcoderdataPython |
21420 | <gh_stars>1-10
from sportstrackeranalyzer.plugins.plugin_simple_distances import Plugin_SimpleDistance | StarcoderdataPython |
141922 | from django.db import models
# Create your models here.
#serializer converts to and from JSON
| StarcoderdataPython |
166091 | import turtle
def rectangle(horizontal, vertical, color):
turtle.pendown()
turtle.pensize(1)
turtle.color(color)
turtle.begin_fill()
for counter in range(1, 3):
turtle.forward(horizontal)
turtle.right(90)
turtle.forward(vertical)
turtle.right(90)
turtle.end_fill(... | StarcoderdataPython |
1761841 | """
@Author <NAME>
Utilities go right here.
"""
import time
import functools
DEFAULT_CLOCK_FMT = '[{elapsed:0.8f}s] {name}({args}) -> {result}'
def time_it(fmt=DEFAULT_CLOCK_FMT, print_handler=print):
"""
@Credits to "Fluent Python" chapter on decorators for this neat function.
:param fmt... | StarcoderdataPython |
1686020 | import pandas as pd
import numpy as np
from sklearn import preprocessing, cross_validation
from sklearn.ensemble import RandomForestRegressor
df = pd.read_csv('../equity.csv')
df_close = df[[3]]
forecast_out = int(30) # predicting 30 days into future
df['Prediction'] = df_close.shift(-forecast_out) # label colum... | StarcoderdataPython |
135737 | <reponame>parachutel/garage
"""
This script creates a test that fails when garage.tf.algos.PPO performance is
too low.
"""
import gym
import pytest
import tensorflow as tf
from garage.envs import normalize
from garage.tf.algos import PPO
from garage.tf.baselines import ContinuousMLPBaselineWithModel
from garage.tf.env... | StarcoderdataPython |
1690153 | from urllib.request import urlopen
from bs4 import BeautifulSoup
import sys
import datetime
import pandas as pd
import tabula
import re
from janome.tokenizer import Tokenizer
import numpy as np
def getLastMeetingNo():
df = pd.read_csv('data/monitoring_comments.csv')
if len(df.index) > 0:
return int(df.... | StarcoderdataPython |
1763684 | # %%
#######################################
def get_content(thepath: str, as_bytes=False):
import pathlib
path_obj = pathlib.Path(thepath).resolve()
if as_bytes:
contents = path_obj.read_bytes()
else:
contents = path_obj.read_text()
return contents
| StarcoderdataPython |
4823952 | neighborhood = list(map(int, input().split('@')))
hearts = 2
i = 0
while True:
line = input()
if line == 'Love!':
last_position = i
break
tokens = line.split()
length = int(tokens[1])
if length < len(neighborhood) and (i + length) < len(neighborhood):
i += leng... | StarcoderdataPython |
3284210 | <reponame>Qiselong/LT_Project_shared_files
## Date 8.12
# Author: <NAME>
# Objective: Print an iterative solution with a gif
import igraph
from igraph import Plot
from igraph import layout
from matplotlib import use
import time
import requests
import math
import imageio
p1 = Plot()
# Operation:
# 1. Gather g... | StarcoderdataPython |
1678617 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside the [MANUAL] ta... | StarcoderdataPython |
1788614 | <reponame>AlexCWolff/Portfolio<gh_stars>0
from flask import render_template, redirect, url_for
from fpflask import FunctionalFlask
from effect.do import do, do_return
from effect import Effect, Func, base_dispatcher
counter = 0
def increment_counter(num):
global counter
counter += num
def get_counter(): retu... | StarcoderdataPython |
1795299 | #Algoritimo que leia o salario do funcionario e mostre seu novo salario, com 15% de aumento
n = float(input('Qual o valor do seu salário? '))
d = (n*15)/100
print('O seu salário com valor de {} reais, com 15% de aumento fica por: {} reais.'.format(n, n+d))
| StarcoderdataPython |
1609682 | """An example of how to use the light parser for parsing UBX messages from a serial device.
You will need to change the port name to that of the port you want to connect to. Also make sure that the baud rate is
correct and that the device has been setup to output the messages via UBX protocol to your desired port!
Th... | StarcoderdataPython |
76685 | <gh_stars>1-10
import discord
from discord.ext import commands
from utils import functions, variables
class TagsCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases = ['тег', 'тэг', 'tag'])
async def astag(self, ctx, user: discord.Member, *, args):
eng = 'T... | StarcoderdataPython |
3301271 | DEBGU = False
SECRET_KEY = 'Crash-Info-Show'
DATA_SRC_ROOT = '/export/dump/backup'
DATA_DEST_ROOT = '/home/m-out-ll/crash_data'
APP='kof97ol'
| StarcoderdataPython |
159942 | from collections import OrderedDict
from django.db.models import Count, Case, When, IntegerField, Sum
from onadata.apps.fieldsight.models import Site
from onadata.apps.fsforms.models import FInstance, FieldSightXF
class BarGenerator(object):
def __init__(self, sites):
self.data = OrderedDict()
sel... | StarcoderdataPython |
1739192 | <filename>codes/Neural_network_models/Unsupervised_learning_models/DCGAN_RU.py<gh_stars>1-10
# В программе реализованы глубокие сверточные генеративно-состязательные сети с помощью двух сверточных слое
# Проектирование структуры сетей в соответствии с DCGAN в статье A Radford, разница в том, что полносвязный нейронный ... | StarcoderdataPython |
18682 | <reponame>boddulurisrisai/python-practice
import re
b=input('enter string')
r=[];max=-1;z=-1
for i in range(len(b)):
for j in range(i+1,len(b)+1):
c=b[i:j]
for k in c:
if k=='a' or k=='e' or k=='i' or k=='o' or k=='u':
flag=0
else:
fl... | StarcoderdataPython |
1763869 | from django.http import QueryDict
from rest_framework.request import Request
from rest_framework.exceptions import ParseError
def get_query_param_or_400(request: Request, key: str, _list=False):
"""
Returns a query parameter and raises a 400 if it is malformed or missing
"""
if _list and isinstance(r... | StarcoderdataPython |
96707 | <reponame>kaio358/Python
pessoa =[]
lista = []
maior = menor = 0
continuar = 's'
while continuar not in 'Nn':
pessoa.append(str(input('Informe o nome : ')))
pessoa.append(float(input('Informe o peso : ')))
if maior == 0:
maior = pessoa[1]
menor = pessoa[1]
if pessoa[1]>maior:
ma... | StarcoderdataPython |
4826170 | """Collection of Ivy neural network layers in functional form."""
# global
import numpy as np
from typing import Union
# local
import ivy
from ivy.framework_handler import current_framework as _cur_framework
# Extra #
# ------#
# Linear #
def linear(x, weight, bias=None):
"""Applies a linear transformation ... | StarcoderdataPython |
1721027 | <gh_stars>0
#!/usr/bin/envthon
# coding: utf-8
#import requests
#from bs4 import BeautifulSoup
#from pandas import DataFrame
#import re
#import datetime
import argparse
import os, re
import sys
import pandas as pd
def get_path(args_master):
"""Prepare the paths for the master DB and output DB
""... | StarcoderdataPython |
3262085 | WSGISCRIPT_TEMPLATE = """\
# -*- coding: utf-8 -*-
import sys
import os
sys.path[0:0] = [
{0}
]
_application = None
def application(environ, start_response):
global _application
# Potential app environment setup
if _application is None:
from {1} import {2} as _application
return _application(env... | StarcoderdataPython |
3369570 | """
Holds current state and is referenced via the global variable
Allows for us to easily load a new set of configurations during runtime.
"""
import logging
from activity_factory import create_activities
from app_context_lock import AppContextLock
from app_settings import AppSettings, create_app_settings, create_app_... | StarcoderdataPython |
1744405 | <filename>skmultilearn/model_selection/iterative_stratification.py<gh_stars>0
# -*- coding: utf-8 -*-
"""Iterative stratification for multi-label data
The classifier follows methods outlined in Sechidis11 and Szymanski17 papers related to stratyfing
multi-label data.
In general what we expect from a given stratificat... | StarcoderdataPython |
3373148 | def tribonacci(signature, n):
if n<len(signature):
return signature[:n]
else:
for i in range(0,n-3):
b=sum(signature[-3:])
signature.append(b)
return signature
| StarcoderdataPython |
3268001 | import numpy as np
from scipy.optimize import minimize
from PySide2 import QtWidgets
from opencmiss.zinc.status import OK as ZINC_OK
from opencmiss.zinc.node import Node
from opencmiss.zinc.field import Field
from opencmiss.utils.zinc.handlers.scenemanipulation import SceneManipulation
from mapclientplugins.electrod... | StarcoderdataPython |
4825586 | <filename>examples/src/main/python/mllib/correlations.py<gh_stars>10-100
#
# 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 Yo... | StarcoderdataPython |
112612 | """
A module for plotting candlesticks
"""
import pandas as pd
from pyalgotrading.constants import PlotType
def import_with_install(package_import_name, package_install_name=None, dependancies=()):
"""
Helps import 'package' even if its not installed.
If package is installed, it will be imported and ret... | StarcoderdataPython |
3296620 | <reponame>nuprl/retic_performance
import enum
class SituationFlag(enum.Enum):
"""
Enumeration of the possible relative owners of a TraitCard an attack scenario
"""
ATTACKER = 1
DEFENDER = 2
DEFENDER_L_NEIGHBOR = 3
DEFENDER_R_NEIGHBOR = 4
@staticmethod
def is_belligerent(flag):
... | StarcoderdataPython |
3235497 | <reponame>MRMRMRMAY/AI-project<filename>gui.py
def center_window(root, width, height):
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
size = '%dx%d+%d+%d' %(width,height,(screen_width-width)/2, (screen_height-height)/2)
root.geometry(size) | StarcoderdataPython |
1609129 | <gh_stars>0
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Tests flow of API keys',
'category': 'Tools',
'depends': ['web_tour'],
'data': ['views/assets.xml'],
'license': 'LGPL-3',
}
| StarcoderdataPython |
149308 | """
Creates Indexes on contentstore and modulestore databases.
"""
from django.core.management.base import BaseCommand
from xmodule.contentstore.django import contentstore
from xmodule.modulestore.django import modulestore
class Command(BaseCommand):
"""
This command will create indexes on the stores used ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.