id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
158187 |
class TurboSMSRouter(object):
app_label = 'turbosms'
db_name = 'turbosms'
def db_for_read(self, model, **hints):
if model._meta.app_label == self.app_label:
return self.db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == self... | StarcoderdataPython |
116337 | import torch
from torch.autograd import Variable
from typing import Dict
from torch.nn import Module, Linear, Dropout, Sequential, Embedding, LogSigmoid, ReLU
from torch.nn.functional import sigmoid, logsigmoid, softmax, normalize, log_softmax
from embeddings.representation import SpanRepresentation
from torch.nn.init ... | StarcoderdataPython |
115910 | from datetime import datetime
import json
import logging
from multiprocessing.queues import Empty
from multiprocessing import Process, Queue
import random
import re
import requests
import pickle
import sys
import time
import threading
import traceback
from sleekxmpp import ClientXMPP
from sleekxmpp.exceptions import I... | StarcoderdataPython |
1747264 | <reponame>bryan-brancotte/rank-aggregation-with-ties
from mediane.distances.enumeration import GENERALIZED_KENDALL_TAU_DISTANCE, GENERALIZED_INDUCED_KENDALL_TAU_DISTANCE, \
GENERALIZED_KENDALL_TAU_DISTANCE_WITH_UNIFICATION
from mediane.algorithms.median_ranking import MedianRanking, DistanceNotHandledException
from... | StarcoderdataPython |
3391186 | import unittest
from liquer import Q
class TestLiquer(unittest.TestCase):
def testQ(self):
a = {'foo': {'bar': 'Hello World!', 'baz': 1}}
self.assertTrue(Q(foo__bar='Hello World!')(a))
self.assertFalse(Q(foo__bar='hello world!')(a))
self.assertTrue(Q(foo__bar__iexact='hello world!... | StarcoderdataPython |
3207332 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
class MainApp(App):
def build(self):
self.operators = ["/", "*", "+","%","^","Mod"]
self.last_was_operator = None
se... | StarcoderdataPython |
3395177 | <filename>tests/test_basisset/test_basisset.py
import numpy as np
import unittest
from chemtools import basisset
from chemtools.basisset import BasisSet
class TestSequenceFunctions(unittest.TestCase):
def test_eventemp_if_nf_is_integer(self):
self.assertRaises(TypeError, basisset.eventemp, (0.0, (1.0, 2... | StarcoderdataPython |
1739143 | <reponame>KevinGetandGive/flurs
from unittest import TestCase
import numpy as np
from flurs.data.entity import User, Item, Event
from flurs.baseline import Random
class RandomTestCase(TestCase):
def setUp(self):
self.recommender = Random()
self.recommender.initialize()
def test_register_use... | StarcoderdataPython |
35830 | <filename>hwtLib/handshaked/ramAsHs_test.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwt.hdl.constants import NOP, READ, WRITE
from hwt.interfaces.utils import addClkRstn, propagateClkRstn
from hwt.simulator.simTestCase import SingleUnitSimTestCase
from hwtLib.common_nonstd_interfaces.addr_data_h... | StarcoderdataPython |
45515 | class Solution:
def isValid(self, s: str) -> bool:
if not s: return True
if len(s) % 2: return False
if s[0] in ']})': return False
maps = {'(':')', '{':'}', '[':']'}
stack = []
for char in s:
if char in '({[':
stack.appen... | StarcoderdataPython |
1704099 | <gh_stars>1-10
from accessible_output.output import OutputError, AccessibleOutput
from accessible_output import priority
class SpeechOutput (AccessibleOutput):
"""Parent speech output class"""
def __init__(self, *args, **kwargs):
super(SpeechOutput, self).__init__(*args, **kwargs)
def canSpeak (self):
return... | StarcoderdataPython |
14736 | from django.apps import AppConfig
class CmspluginMarkdownConfig(AppConfig):
name = 'cmsplugin_markdown'
| StarcoderdataPython |
1636817 | # flake8: noqa
import unittest
from smolcalc.nodes import *
from smolcalc.interpreter import Interpreter
from smolcalc.values import Number
class TestInterpreter(unittest.TestCase):
def test_numbers(self):
value = Interpreter(False).visit(number_node(123.456))
self.assertEqual(value, Number(123.... | StarcoderdataPython |
21672 | import os
from docx import Document
from docx.shared import Inches
from docx import Document
from docx.text.paragraph import Paragraph
def Iceriyomu(dosyayol):
document = Document('{}'.format(dosyayol))
headings = []
texts = []
para = []
giris = ""
for paragraph in document.paragraphs... | StarcoderdataPython |
169414 |
l = [2, 5, 6, 5, 11]
def isPal(x):
str_num = str(x)
if len(str_num) == 1:
return True
if len(str_num) % 2 != 0:
mid = int(len(str_num)/2)
front = str_num[:mid]
back = str_num[mid+1:]
else:
mid = int(len(str_num)/2)
front = str_num[:mid]
back =... | StarcoderdataPython |
1658711 | from datetime import timedelta
from .entity_object import EntityObject
class TokenObject(EntityObject):
"""
An abstract base class for CookieObject and AuthenticationObject
"""
TOTAL_SYMBOL_NUMBER = 20
EXPIRATION_TERM = timedelta(milliseconds=300)
_initial_password = None
def __init__(... | StarcoderdataPython |
1651088 | from discord.ext import commands
from stubs import ZombieBotStub
from utils import extensions
class Admin(commands.Cog):
def __init__(self, bot: ZombieBotStub):
self.bot = bot
async def cog_check(self, ctx):
return ctx.author.id == self.bot.owner_id
@commands.group()
async def ext(s... | StarcoderdataPython |
3273591 | <filename>appname/forms/teams.py<gh_stars>10-100
from appname.forms import BaseForm
from wtforms import validators, StringField, SelectField
from appname.constants import TEAM_MEMBER_ROLES
class InviteMemberForm(BaseForm):
email = StringField('Email', validators=[validators.email(), validators.InputRequired()])
... | StarcoderdataPython |
1636429 | <filename>input_gen.py
import grp
import os
import pwd
import time
import keyboard
HISTORY = {}
RUN_LOOP = True
A_PRESSED = False
def key_recording(e):
global A_PRESSED
if e.name == "a":
if e.event_type == keyboard.KEY_DOWN:
A_PRESSED = True
else:
A_PRESSED = False
... | StarcoderdataPython |
3320736 | <filename>tiles.py
from globals import *
import libtcodpy as tcod
BLANK_TILE = {'id':'blank_tile',
'icon': '.',
'color':(tcod.darker_gray, tcod.black)}
SHORT_GRASS_TILE = {'id':'short_grass',
'icon':'.',
'color':(GRASS_GREEN_DARK, tcod.desaturated_green),
'burnable':8,
'cost':... | StarcoderdataPython |
3272390 | from autovars import *
import ROOT
from math import sqrt
# sip = ROOT.SignedImpactParameter()
TRACK_HITS = 0,
MISSING_INNER_HITS = 1,
MISSING_OUTER_HITS = 2
eventNTObject = NTupleObjectType("event", variables = [
NTupleVariable("run", lambda x : x.run(), int),
NTupleVariable("lumi", lambda x : x.lum... | StarcoderdataPython |
3229757 | <filename>nativepython/type_wrappers/exceptions.py
# Coyright 2017-2019 Nativepython Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/L... | StarcoderdataPython |
4802144 | # (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from ..utils import requires_py3
from .utils import get_legacy_check
pytestmark = [requires_py3, pytest.mark.openmetrics, pytest.mark.openmetrics_compat_scraper]
class TestRawMetricPrefix... | StarcoderdataPython |
1678700 | import numpy as np
import time
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from src.rsqt_forest import RSQT
start_time = time.time()
nr_points = 1000
contamination = 0.00
N = int((1-contamination) * nr_points) # number of points
print("N = ", N)
rectangles = []
for i in range(int(N / 12... | StarcoderdataPython |
108672 | import numpy as np
import sys
lines = []
for line in sys.stdin:
lines.append(line.rstrip('\n'))
n = int(lines[0])
count = 1
for i in range(n):
size = int(lines[count])
count += 1
m = [[int(x) for x in lin.split()] for lin in lines[count:count+size]]
m = np.array(m)
k = np.trace(m)
r = su... | StarcoderdataPython |
105487 | <filename>bin/snpit-run.py
#! /usr/bin/env python
import argparse
from snpit import snpit
# programme to report the lineage/subspecies of a TB sample alligned to NC000962
# usage: python SNP-IT.py [guuid] [name of outfile]
# or for lots of samples: cat [list of samples] | parallel -j[no. of threads] python fasta_typ... | StarcoderdataPython |
3248072 | <reponame>Chromico/bk-base
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------... | StarcoderdataPython |
1643732 | import warnings
from ..warns import BotNotFound
from ..util.base_request import request, default_baseURL
def get_bot_data(id, **anydata):
data = request(url=str(anydata.get("baseURL") or default_baseURL) + '/api/v1/bots/' + str(id)).get()
if data.status_code != 200:
warnings.warn("Bot data not f... | StarcoderdataPython |
114283 | <filename>tests/test_trolley.py
from pyticketswitch.trolley import Trolley
from pyticketswitch.bundle import Bundle
from pyticketswitch.event import Event
from pyticketswitch.order import Order
class TestTrolley:
def test_from_api_data_with_trolley_data(self):
data = {
'discarded_orders': [
... | StarcoderdataPython |
3208463 | <reponame>ubiquity6/OldMVSNet
from mvsnet import preprocess as pp
import imageio
import argparse
import json
import utils
import os
"""
Converts DTU depth data from the format that is consumed by the original MVSNet
to the mvs-training format that is created by export_densify_frames
"""
def convert_dtu(dtu_dir, outp... | StarcoderdataPython |
1722187 | <reponame>kurylo/openvino
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import re
from openvino.tools.mo.graph.graph import Node, Graph
from openvino.tools.mo.middle.MarkSubgraphsWithCorrectLayout import MarkSubGraphsWithCorrectLayout
from openvino.tools.mo.mi... | StarcoderdataPython |
3299438 | # Copyright (C) <NAME> <<EMAIL>>
# See LICENSE for details.
# from twisted.internet.defer import inlineCallbacks
import re
from base64 import b64decode
from os import environ, makedirs
from os.path import dirname, isdir, join
from shutil import copyfile, rmtree
from tempfile import mkdtemp
from twisted.internet impor... | StarcoderdataPython |
1708253 | __all__ = ['read', 'write'] | StarcoderdataPython |
1689476 | <gh_stars>1-10
class Node(object):
"""docstring for Node"""
def __init__(self, value):
self.info = value
self.link = None
class LinkedList :
def __init__(self):
self.start = None
# display your linked list
def displayList(self):
if self.start == None:
print("List is empty \n")
else :
print("List ... | StarcoderdataPython |
1608069 | <reponame>HaoZeke/aiida-core
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | StarcoderdataPython |
3329709 | <reponame>MosyMosy/cellemnet
"""
Copied with modification from https://github.com/fastai/fastai1/blob/6a5102ef7bdefa9058d0481ab311f48b21cbc6fc/fastai/widgets/image_cleaner.py
Modifications:
--------------
1. Added new Dataset class
2. Changed widget to show a grid with multiple rows
"""
import cv2
import numpy as np... | StarcoderdataPython |
1783997 | def check_required_db_properties(properties):
if isinstance(properties, dict):
db_keys = [
"db.host",
"db.type",
"db.username",
"db.password",
"db.database",
"db.table",
]
for key in db_keys:
if not _has_prop... | StarcoderdataPython |
39230 |
## Python Crash Course
# Exercise 6.4: Glossary#2:
# Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102)
# by replacing your series of print statements with a loop that runs through the dictionary’s keys and values.
# Whe... | StarcoderdataPython |
3361133 | <reponame>la3mmchen/pulumi-gcp
# 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, Optional, Sequence,... | StarcoderdataPython |
1727167 | <gh_stars>0
from . import fft
from . import utils
| StarcoderdataPython |
1712153 | <reponame>athira-vs/Firewall
#!/usr/bin/python3
from rich.prompt import Prompt
from firewall import *
while True:
fw_get_status()
colour_print("green", f"{'_'*20}MENU{'_'*20}")
colour_print("green", "[1] Add rules")
colour_print("green", "[2] Delete rules")
colour_print("green", "[3] Get Active Zo... | StarcoderdataPython |
3226385 | """
Riak Plugin
"""
import logging
from newrelic_plugin_agent.plugins import base
LOGGER = logging.getLogger(__name__)
class Riak(base.JSONStatsPlugin):
DEFAULT_PATH = '/stats'
GUID = 'com.meetme.newrelic_riak_agent'
def add_datapoints(self, stats):
"""Add all of the data points for a node
... | StarcoderdataPython |
881 | # Copyright 2012 OpenStack Foundation
# 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 requ... | StarcoderdataPython |
1698678 | <filename>shopping-cart.py
#shopping_cart.py
import datetime as dt
TAX_RATE = 0.06
products = [
{"id":1, "name": "Chocolate Sandwich Cookies", "department": "snacks", "aisle": "cookies cakes", "price": 3.50},
{"id":2, "name": "All-Seasons Salt", "department": "pantry", "aisle": "spices seasonings", "price": ... | StarcoderdataPython |
114175 | <gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
import math
def split_file(file):
answer = [[]]
j = 0
for i in file:
if i == "\n":
j += 1
if j == 16:
pass
else:
answer.append([])
elif i[:3] == "VOM":
... | StarcoderdataPython |
3212089 | <gh_stars>0
import os
import sys
from os.path import abspath, dirname, expanduser, getsize, isfile, splitext
from typing import List, TypedDict
from zipfile import ZipFile
ROOT = dirname(dirname(abspath(__file__)))
class ProcessResponse(TypedDict):
download_filename: str
filesize: int
output_filesize: i... | StarcoderdataPython |
134499 | <gh_stars>1-10
#!/usr/bin/python
# Copyright 2022 Northern.tech AS
#
# 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 |
1781654 | import json
import os
import pickle
import re
from collections import namedtuple
import numpy as np
import pandas as pd
from django.contrib.auth.models import User
from django.db import transaction
from django.db.models import F
from django.shortcuts import HttpResponse, render
from django.template.loader import rende... | StarcoderdataPython |
17922 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2019/9/17 15:07
@Author : <NAME>
@FileName: models.py
@GitHub : https://github.com/cRiii
"""
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from jaysblog.extensions import db
from flask_login i... | StarcoderdataPython |
1673839 | <reponame>KaijianYou/papaya<gh_stars>0
from datetime import datetime
from sqlalchemy.orm.interfaces import MapperExtension
from sqlalchemy.orm.attributes import set_attribute
from app import db
class ModelUpdateExtension(MapperExtension):
def before_update(self, mapper, connection, instance):
if hasattr... | StarcoderdataPython |
3221207 | #!/usr/bin/env python
import errno
import os
import pytest
import sys
# Import our local xcross.
test_dir = os.path.dirname(os.path.realpath(__file__))
xcross_dir = os.path.dirname(test_dir)
sys.path.insert(0, xcross_dir)
import xcross
os.environ['CROSS_TARGET'] = 'alpha-unknown-linux-gnu'
os.environ['CROSS_WITH_PAC... | StarcoderdataPython |
4829707 | # Copyright (C) 2002, <NAME> (<EMAIL>)
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Classes that deal with macromolecular c... | StarcoderdataPython |
3235777 | """
Day 4 - Part 2
https://adventofcode.com/2021/day/4#part2
By NORXND @ 04.12.2021
(C) NORXND 2021 - Under The MIT License
"""
import typing
input_file = open('Day4/input.txt', 'r')
input_data = input_file.read().split("\n\n")
numbers = input_data[0].split(",")
raw_boards = input_data[1:]
class Num:
def __ini... | StarcoderdataPython |
91996 | <reponame>MaximKalininMS/onnxruntime<gh_stars>0
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
# Convert Bert ONNX model... | StarcoderdataPython |
1701243 | #!/usr/bin/env python
import unittest
try:
from unittest import mock # py3
except ImportError:
import mock # requires "pip install mock"
class ChrtmeDaemonTestToolkit(unittest.TestCase):
"""Base class for all ChrtmeD tests."""
@classmethod
def setUp(cls):
"""Pre-test setup steps"""
... | StarcoderdataPython |
184157 | <filename>testData/wrappers_storage/bio/hisat2/index/wrapper.py
"""Snakemake wrapper for HISAT2 index"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, <NAME>"
__email__ = "<EMAIL>"
__license__ = "MIT"
import os
from snakemake.shell import shell
# Creating log
log = snakemake.log_fmt_shell(stdout=True, stder... | StarcoderdataPython |
1761269 | <filename>Kelas Rabu/Nilai Hash/1310651094 Irvan/irfan.py
__author__ = 'irfan'
import hashlib
print
print "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
print("Program Sederhana Untuk Melakukan Generate Terhadap Nilai Hash dari sha512")
print "- - - - - - - - - - - - - - - - - - - - -... | StarcoderdataPython |
1694499 | <reponame>bhardwajRahul/minos-python
import os
import unittest
from unittest import (
mock,
)
from minos.common import (
ConfigV2,
)
from tests.utils import (
BASE_PATH,
)
class TestConfigV2WithEnvironment(unittest.TestCase):
def setUp(self) -> None:
self.file_path = BASE_PATH / "config" / "v... | StarcoderdataPython |
3393330 | <reponame>MatthewAlexanderFisher/GaussED
from torch import nn
class Basis(nn.Module):
def __init__(self):
super().__init__()
def forward(self):
"""Forward the forward computation .
Raises:
NotImplementedError: [description]
"""
raise NotImplementedError
... | StarcoderdataPython |
130477 | import pytest
from firebase_admin import messaging
from backend.common.consts.fcm.platform_priority import PlatformPriority
from backend.common.models.fcm.platform_config import PlatformConfig
from backend.common.models.notifications.notification import Notification
from backend.common.models.notifications.tests.mocks... | StarcoderdataPython |
3298598 | """
original project = "bgflow" https://github.com/noegroup/bgflow
copyright = MIT License
author = <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
"""
import torch
import numpy as np
def is_list_or_tuple(x):
return isinstance(x, list) or isinstance(x, tuple)
def assert_numpy(x, arr_type=None):
if isinstance(x, torch... | StarcoderdataPython |
1734949 | from pydantic import Field
from pydantic.main import BaseModel
class MessageOk(BaseModel):
message: str = Field(default="OK")
class UserToken(BaseModel):
displayName: str = None
givenName: str = None
jobTitle: str = None
mail: str = None
provider: str = None
role: str = None
class Mine... | StarcoderdataPython |
1728251 | <reponame>garcia/msdparser
import unittest
from io import StringIO
from msdparser import MSDParserError, parse_msd
class TestMSDParser(unittest.TestCase):
def test_constructor(self):
data = "#A:B;"
from_file = parse_msd(file=StringIO(data))
from_string = parse_msd(string=data)
... | StarcoderdataPython |
123860 | # -*- coding: utf-8 -*-
# Copyright 2019, 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.
"""Assemble function for converting a list of circuits into a qobj"""
import uuid
import sympy
import numpy
from qiskit.circ... | StarcoderdataPython |
1706940 | <reponame>h-terao/hazuchi<gh_stars>0
from __future__ import annotations
import jax
import jax.numpy as jnp
from flax import struct
import chex
@struct.dataclass
class Observation:
"""An immutable class to summarize metrics.
Attributes:
values (dict of str: tuple[array, array]): Accumulated metrics to... | StarcoderdataPython |
3339647 | <reponame>moschlar/mod_md<filename>test/md_acme.py<gh_stars>0
import logging
import os
import shutil
import subprocess
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta
from threading import Thread
from md_env import MDTestEnv
log = logging.getLogger(__name__)
def monitor_proc(env: MD... | StarcoderdataPython |
1708051 | from django.test import TestCase
# Create your tests here.
# TO RUN TESTS #####################
# python manage.py test football
# TEST EXAMPLE ####################
# import datetime
# from django.test import TestCase
# from django.utils import timezone
# from .models import Question
# class QuestionModelTests(... | StarcoderdataPython |
1633811 | <gh_stars>1-10
from io import StringIO
from unittest.mock import patch
from hera.main import main
def execute_program_helper(program, *, flags=[]):
with patch("sys.stdin", StringIO(program)):
return main(flags + ["--no-color", "-"])
def preprocess_program_helper(program):
with patch("sys.stdin", St... | StarcoderdataPython |
1623563 | <filename>tests/unit/spanner_dbapi/test_types.py
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
# Copyright 2020 Google LLC All rights reserved.
#
... | StarcoderdataPython |
3362923 | <reponame>archiekey/AuroraBorealis<filename>Clustering.py<gh_stars>0
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_selection import SelectPercentile, f_classif
from sklearn.metrics import accuracy_score
from sklearn.cluster i... | StarcoderdataPython |
1728277 | <reponame>ashhadulislam/TechDesignForumJan2019
import cv2
import time
## Read image
data = cv2.imread("dbs.png", cv2.IMREAD_COLOR )
print(type(data))
## Display Image
cv2.imshow("image input", data)
if cv2.waitKey(0) & 0xFF == ord('q'):
cv2.destroyAllWindows()
print("exit")
## Write Image
cv2.imwrite('output.... | StarcoderdataPython |
158594 | # filter_plugins/passwdhash.py
#
# Generate password hashes that can be used in /etc/shadow.
#
# Example usage:
#
# Assume you have the following variable defined in Yaml:
#
# users:
# - name: alice
# password: <PASSWORD>
# - name: bob
# password: <PASSWORD>
#
# You can use this filter in your playbook like... | StarcoderdataPython |
4829455 | # Copyright 2012 OpenStack Foundation
# 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 requ... | StarcoderdataPython |
1668508 | <filename>tests/test_axis.py
"""Testing axis class
"""
import pytest
import numpy as np
from shellplot.axis import Axis
@pytest.fixture(autouse=True)
def set_np_seed():
np.random.seed(42)
@pytest.mark.parametrize(
# fmt: off
"x,expected_limits",
[
(np.random.uniform(1, 9, 100), np.array([1... | StarcoderdataPython |
1753561 | <filename>server/edd/rest/routers.py
# coding: utf-8
from rest_framework import routers as rest_routers
from rest_framework_nested import routers as nested_routers
from . import views
###################################################################################################
# Define a router for base REST AP... | StarcoderdataPython |
1688285 | <reponame>eob/eob.github.com
# trends.csv is the CSV file with the HN front page data
f = open('trends.csv')
titles = open('titles.csv', 'w')
seen = {}
for line in f:
l = line.replace('"', '')
a = l.split(',')
if (len(a) >2):
if a[2] not in seen:
seen[a[2]] = 1
titles.... | StarcoderdataPython |
4819101 | from flask import Flask
from flask import request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from requests import Session
import json
# For article summary
import nltk
from newspaper import Article
# For news extract
import requests
app = Flask(__name__)
app.config['SQLALCHEMY_DAT... | StarcoderdataPython |
50416 | from .FHIR_Generator import Generator
from .genomics_test_generator.fhir_genomics_test_gene import *
import os
spec_basepath = os.path.join(os.getcwd(), 'task_runner/resources/spec/')
def get_resource_correct_cases(version, resource_type):
'''
get correct resource objects for a certain resource type
'''
... | StarcoderdataPython |
3341150 | import pandas as pd
import argparse
import sys
def reform(target_bed, output_f, detected_variants, padding, file_format):
targets = pd.read_csv(target_bed, sep="\t",
names=["CHROM", "START", "END", "ID", "GENE"],
dtype={"START": int, "END": int})
if detected... | StarcoderdataPython |
198261 | from Tkinter import *
showing = True
def show():
global showing
if showing:
myFrame.grid_remove()
ShowButton.configure(text="Show")
showing = False
else:
myFrame.grid()
ShowButton.configure(text="HIDE")
showing = True
def update_label():
Label1.configure(text=str(myScale.get()))
mw = Tk()
ShowButt... | StarcoderdataPython |
1777011 | #
# webappfb - Facebook tools for Google's AppEngine "webapp" Framework
#
# Copyright (c) 2009, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must r... | StarcoderdataPython |
811 | <reponame>jiji-online/neptune-cli
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, deepsense.io
#
# 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... | StarcoderdataPython |
1638440 | # Copyright 2018 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.
"""Build indexing and search."""
import heapq
import logging
import random
import re
from google.appengine.ext import db
from google.appengine.ext import n... | StarcoderdataPython |
121310 | # coding: utf-8
# Aluno: <NAME>
# Matrícula: 117110525
# Problema: Limite açude
limite = float(raw_input())
nivel_atual = float(raw_input())
while nivel_atual < limite:
operacao = raw_input().split()
if operacao[0] == "chuva" or operacao[0] == "afluente":
nivel_atual += float(operacao[1])
else:
if (nivel_atual... | StarcoderdataPython |
3210237 | import Qt as Qt
import Qt.QtGui as QtGui
import Qt.QtCore as QtCore
from qtLearn.nodes import Node
import qtLearn.uiUtils as uiUtils
class ItemModel(QtCore.QAbstractItemModel, uiUtils.QtInfoMixin):
def __init__(self, rootNode, font=None):
super(ItemModel, self).__init__()
self._rootNode = None
... | StarcoderdataPython |
29720 | <gh_stars>0
import png
import pyrealsense2 as rs
import logging
logging.basicConfig(level=logging.INFO)
import numpy as np
import cv2
import os
def make_directories():
if not os.path.exists("JPEGImages/"):
os.makedirs("JPEGImages/")
if not os.path.exists("depth/"):
os.makedirs("depth/")
if ... | StarcoderdataPython |
1659699 | <filename>thenReturn2DoReturn.py<gh_stars>0
import clipboard
def findIndexByWord(splitedSentence, wordToSearch):
for index, item in enumerate(splitedSentence) :
if wordToSearch in item:
return index
def thenReturn2DoReturn(sentence):
print("Transforming thenReturn sentence to doReturn ... | StarcoderdataPython |
1733802 | <filename>src/data/tweet2csv.py
import os
import pandas
twitterName = 'revistasuper'
tweetFilesList = os.listdir('./' + twitterName)
sentences = []
for i in tweetFilesList:
with open('./' + twitterName + '/' + i) as file:
for j in file.readlines():
curSentences = j.strip('\n')
i... | StarcoderdataPython |
1676299 | <reponame>Gavaharlal/fpTask1
a = "str"
b = -a
print(b) | StarcoderdataPython |
160756 | <reponame>StanleyHou117/group66_LentTermProject
from floodsystem.station import inconsistent_typical_range_stations
from floodsystem.stationdata import build_station_list
def run():
print(sorted(inconsistent_typical_range_stations(build_station_list())))
print(len(inconsistent_typical_range_stations(build_stat... | StarcoderdataPython |
3264578 | <gh_stars>1-10
class Flagger:
"""
Class Name: Flagger
Responsibility: Provide a means to make multiple checks without large/nested if statements
Usage: Set the desired state (true or false) each call to test records information
about the provided value counting total numbe... | StarcoderdataPython |
1613555 |
def from_url(url, db=None, **kwargs):
"""
Returns an active Ledis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
"""
from ledis.client import Ledis
return Ledis.from_url(url, db, **kwargs)
| StarcoderdataPython |
132296 | <filename>metadata-ingestion/src/datahub/metadata/schema_classes.py
# flake8: noqa
# This file is autogenerated by /metadata-ingestion/scripts/avro_codegen.py
# Do not modify manually!
# fmt: off
import json
import os.path
import decimal
import datetime
import six
from avrogen.dict_wrapper import DictWrapper
from avr... | StarcoderdataPython |
3316509 | <reponame>matthewdeanmartin/so_pip
"""
Version file
Starts at 0.1.0
Increments to 0.1.1, etc on build
"""
__version__ = "0.1.30"
| StarcoderdataPython |
1667046 | import tensorflow as tf
from tensorflow.keras.initializers import random_normal, constant
from common.nets.resnet import ResNetBackbone
from config import cfg
class RootNet(tf.keras.Model):
def __int__(self):
self.inplanes = 2048
self.outplanes = 256
super(RootNet, self).__int__()
... | StarcoderdataPython |
1627567 | """Inventory Plugin for Nornir designed to work with Nautobot ORM."""
# pylint: disable=unsupported-assignment-operation,unsubscriptable-object,no-member
from typing import Any, Dict
from django.db.models import QuerySet
from django.utils.module_loading import import_string
from nornir.core.inventory import (
Inv... | StarcoderdataPython |
1758493 | <gh_stars>1-10
"""
The pytoil CLI, implemented with Typer.
"""
| StarcoderdataPython |
1731285 | from flask import render_template, request, session, redirect, url_for, flash
from controller.Controller import login_required
from config.config import ip_address
from model.User import User
class UserController(object):
"""
Controller untuk model/tale User
"""
def __init__(self, **kwargs):
... | StarcoderdataPython |
3350788 | <gh_stars>0
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remov... | StarcoderdataPython |
1762626 | <gh_stars>0
import os
import sys
from bentoml.saved_bundle import load_bento_service_metadata
from bentoml.configuration import LAST_PYPI_RELEASE_VERSION
from utils import (
get_configuration_value,
run_shell_command,
build_docker_image,
push_docker_image_to_repository,
)
from azure import generate_a... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.