id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3289083 | <filename>scramblies.py
#<NAME>
#Codewars : @Kunalpod
#Problem name: Scramblies
#Problem level: 5 kyu
from itertools import groupby
def scramble(s1,s2):
for key, group in groupby(sorted(s2)):
if len(list(group)) > s1.count(key):
return False
return True
| StarcoderdataPython |
3244676 | <gh_stars>1-10
from .database import recoBase
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
class bbox2d(recoBase):
"""docstring for cluster"""
def __init__(self):
super(bbox2d, self).__init__()
self._product_name = 'bbox2d'
# this is the function that actually draws the ... | StarcoderdataPython |
3203976 | <reponame>zuzhi/rssant<filename>tests/feedserver/main.py<gh_stars>1000+
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/feed/302')
def do_redirect():
target = 'http://blog.guyskk.com/feed.xml'
return redirect(target, 302)
if __name__ == "__main__":
app.run()
| StarcoderdataPython |
24742 | <gh_stars>0
from model.contact import Contact
from model.group import Group
import random
def test_add_contact_in_group(app, db):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(firstname="ADDNewFirstName1", lastname="ADDNewLastName1"))
if len(db.get_group_list()) == 0:
app.grou... | StarcoderdataPython |
3317015 | <reponame>farhadrgh/molssi_devops_uf
"""
string_math.py
A sample repository for the MOLSSI workshop at UF.
Some string functions.
"""
def title_case(sentence):
"""
make the string title cased
Parameters
----------
sentence : string
The string to make the title case of
Returns
--... | StarcoderdataPython |
1738737 | #coding:utf-8
#------requirement------
#pymongo-3.7.1
#------requirement------
import pymongo
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import gc
sys.path.append("/home/dev/Repository/news/Tegenaria/tSpider/tSpider/")
from Tegenaria.tSpider.tSpider.settings import Settings
class MongoMiddleware():
def... | StarcoderdataPython |
88667 | <filename>Aperture/ApertureSquare.py<gh_stars>0
"""
Represents a square aperture.
"""
from BeamlineComponents.Aperture.ApertureRectangle import ApertureRectangle
class ApertureSquare(ApertureRectangle):
def __init__(self, side_length):
AperatureRectangle.__init__(self, side_length, side_length)
def s... | StarcoderdataPython |
1621557 | <reponame>ThomasEdwardRiley/nestcheck<filename>nestcheck/diagnostics_tables.py
#!/usr/bin/env python
"""
High-level functions for calculating results of error analysis and diagnostic
tests for batches of nested sampling runs.
"""
import numpy as np
import pandas as pd
import nestcheck.error_analysis
import nestcheck.i... | StarcoderdataPython |
21616 | <reponame>Kazuhito00/yolo2_onnx
from Onnx import make_dir, OnnxImportExport
import subprocess
import pickle
import os
import numpy as np
import time
def generate_svg(modelName, marked_nodes=[]):
"""
generate SVG figure from existed ONNX file
"""
if marked_nodes ==[]:
addfilenamestr = ""
... | StarcoderdataPython |
101567 | <filename>app_folder/tools/image_upload.py<gh_stars>0
from cloudinary import uploader
def image_upload(image_str) -> str:
try:
result = uploader.upload(image_str)
except FileNotFoundError as e:
raise ValueError(e)
return result['url'] | StarcoderdataPython |
1670240 | <filename>scraper_pipeline/models/scrape.py
import typing
class Scrape(typing.NamedTuple):
page_id: str
url: str
| StarcoderdataPython |
1666692 | <gh_stars>1-10
"""unittest"""
import unittest
from main import (EventHandlers,
CrashReportEvent,
PurchaseEvent,
InstallEvent,
pre_processing,
input_processing,
get_err_ret,
get_ok_ret)
import e... | StarcoderdataPython |
3368150 | <filename>crawlino/plugins/extractors_plugins/extractors_dummy_plugin/dummy_plugin.py
import logging
from crawlino import extractor_plugin, PluginReturnedData
log = logging.getLogger("crawlino-plugins")
@extractor_plugin
def extractor_dummy(prev_stepPluginReturnedData, **kwargs) \
-> PluginReturnedData:
... | StarcoderdataPython |
1622212 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2016 .
# <NAME>, <EMAIL>
# All rights reserved
#
# backend/mqttpush.py
# The entry form mqttpush service
#
from ppmessage.core.constant import REDIS_HOST
from ppmessage.core.constant import REDIS_PORT
from ppmessage.core.constant import REDIS_MQTTPUSH_KEY
from ppmessage.... | StarcoderdataPython |
1690124 | from flask import Flask
from flask import render_template
from flask import request
from flask_cors import CORS , cross_origin
import json
import datetime
import base64
import time
import logging
from cmosasr import CMOSASR
import re
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
... | StarcoderdataPython |
3297610 | # !/usr/bin python3
# encoding:utf-8
'''
@Time :2020/2/24 5:32 AM
@Author :TaibiaoGuo
@FileName :__init__.py
@Github :https://github.com/TaibiaoGuo
@Describe :
''' | StarcoderdataPython |
3363255 | <filename>ldap-connector/commands.py
# Copyright (C) 2012 innoQ Deutschland GmbH
#
# 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
#
# Unles... | StarcoderdataPython |
1687003 | <gh_stars>1-10
from brightway2 import *
import warnings
from .utils import ParameterNameGenerator
from presamples.models.parameterized import ParameterizedBrightwayModel as PBM
from numpy import inf
import copy
class ActivityWaterBalancer():
"""Balances water exchange samples at the activity level
Upon instan... | StarcoderdataPython |
4824161 |
from parameters import *
import cv2
import pandas as pd
import numpy as np
from PIL import Image
from os.path import join
cascade_classifier = cv2.CascadeClassifier(CASC_PATH)
def format_image(image, flag=0):
if len(image.shape) > 2 and image.shape[2] == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY... | StarcoderdataPython |
3258970 | from functools import wraps, partial
from typing import TypeVar
import torch
import numpy as np
import networkx as nx
TensorLike = TypeVar("TensorLike", np.ndarray, torch.Tensor)
def random_seed_consistent_rng(seed=None) -> np.random.RandomState:
if seed is not None:
torch.manual_seed(seed=seed)
... | StarcoderdataPython |
35670 | from django.utils.translation import ugettext_lazy as _
from mayan.apps.authentication.link_conditions import condition_user_is_authenticated
from mayan.apps.navigation.classes import Link, Separator, Text
from mayan.apps.navigation.utils import factory_condition_queryset_access
from .icons import (
icon_current_... | StarcoderdataPython |
3358186 | #!/usr/bin/env python
# coding: utf-8
# # Tabulate policies by country and adm-level
# - Save Google Sheet of policies as Excel file
# - Calculate number of policies for each country / adm-level
import pandas as pd
import src.utils as cutil
path_data_sources = cutil.DATA_RAW / "multi_country" / "data_sources.xlsx"
... | StarcoderdataPython |
52242 | from torch.utils.data import Sampler
import numpy as np
def get_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def flatten(l):
return [item for sublist in l for item in sublist]
class LengthSortSampler(Sampler):
def __init__(self, data_source, bs):
super().__init__(data_s... | StarcoderdataPython |
107735 | <filename>python/driz_funcs.py
import os
import glob
import shutil
import numpy as np
from math import sqrt
from astropy import units as u
from astropy.io import fits as pf
from astropy.io import ascii
from astropy.table import Table
from drizzlepac import tweakreg
from drizzlepac import tweakback
from drizzlepac imp... | StarcoderdataPython |
1778735 | from compas.topology import breadth_first_paths
from compas.datastructures import mesh_substitute_vertex_in_faces
from compas.utilities import pairwise
# from ..grammar_pattern import strip_polyedge_update
__all__ = [
]
def add_strips(mesh, polyedges, callback=None, callback_args=None):
to_add = polyedges[:]
... | StarcoderdataPython |
3210383 | # Copyright (c) 2013 Rex
from datetime import datetime
from types import Block, Transaction
from connection import BitcoinConnection
from lxml import html
UNIX_EPOCH = datetime(1970, 1, 1, 0, 0)
def fetch_data(url):
"""
:type url: str
"""
import urllib2
return urllib2.urlopen(url).read()
def... | StarcoderdataPython |
3257108 | # -*- coding: utf-8 -*-
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from blog.models import Entry
from tagging.models import Tag, TaggedItem
def make_count(bits, default_count=50):
"""
Return items count from URL bits if last bit is positive integer.
... | StarcoderdataPython |
4840720 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: health_checker.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.proto... | StarcoderdataPython |
153514 | from gevent import monkey
_PATCHED = False
if not _PATCHED:
monkey.patch_all(thread=False, select=False)
_PATCHED = True
from ._version import VERSION as __version__ # noqa: F401
from .functional import pipeline, stop # noqa: F401
from .reactive import * # noqa: F401, F403
| StarcoderdataPython |
3368406 | #=========================================================================
# run_handler
#=========================================================================
# Primary handler for generating build system files for a given graph
#
# Author : <NAME>
# Date : June 2, 2019
#
import importlib
import os
import sys
i... | StarcoderdataPython |
1774561 | from rpn.generation import compute_deltas
import numpy as np
def make_corners(regions):
"""Transforms boxes from center format to corners"""
x0, y0, x1, y1 = np.transpose(regions)
ws = x1 - x0 // 2
hs = y1 - y0 // 2
return np.transpose([x0 + ws, y0 + hs, 2 * ws, 2 * hs])
def compute_iou(regions,... | StarcoderdataPython |
1761432 | <gh_stars>0
#!/usr/bin/env python3
#
# Copyright 2022 Graviti. Licensed under MIT License.
#
"""The implementation of the Draft and DraftManager."""
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Tuple
from graviti.dataframe import DataFrame
from graviti.exception import StatusError
from gra... | StarcoderdataPython |
3314055 | fp = open("C:/xampp2/htdocs/ghtorrent/reaper/path/73853335/pttg-ip-hmrc-access-code/.drone.yml",'r')
totalNumberOfDependencyLines = 0
for x in fp:
if("0." in x or "1." in x or "2." in x or "3." in x or "4." in x or "5." in x or "6." in x or "7." in x or "8." in x or "9." in x):
print(x)
totalNumberO... | StarcoderdataPython |
3391385 | #!/usr/bin/env python3
#
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
... | StarcoderdataPython |
3344481 | import asyncio
import uuid
from urllib.parse import urlencode
from telepot.namedtuple import InputTextMessageContent, InlineQueryResultArticle
from bot import markdown_escape
from message import Message
@asyncio.coroutine
def run(message, matches, chat_id, step):
get_params = urlencode({'q': matches})
retur... | StarcoderdataPython |
1782234 | <filename>tests/open_alchemy/schemas/association/test_get_association_tablename.py
"""Tests for _get_association_tablenames association schemas function."""
import pytest
from open_alchemy import types
from open_alchemy.schemas import association
class TestGetAssociationTablenames:
"""Tests for _get_association... | StarcoderdataPython |
3305507 | <gh_stars>0
from operator import itemgetter
from herbarium.layers.relative_attention import AttentionConv
from torch import Tensor, nn
import torch
from herbarium.config import configurable
from torch.distributions.normal import Normal
from torch.distributions.log_normal import LogNormal
from torch.distributions.dirich... | StarcoderdataPython |
3221668 |
from concurrent.futures import Future, TimeoutError
from functools import partial
from deprecated import deprecated
from enum import Enum
from ... import RouterClient
from ...NotificationHandler import NotificationHandler
from ... import BitMaskTools
from ..messages import ControlConfig_pb2 as ControlConfigPb # NOQA... | StarcoderdataPython |
92956 | <filename>parking_lot/parking.py
import sys
class ParkingLot:
def __init__(self):
self.slots = -1
self.blocked = []
self.occupancy = []
def create_parking_lot(self, slots):
'''
Class function to help create
the parking lot with required
slots
sl... | StarcoderdataPython |
1742221 | <gh_stars>10-100
import os
import os.path
import unittest
from typing import Set, Union, Sequence
from xcube.constants import FORMAT_NAME_ZARR
from xcube.core.chunk import chunk_dataset
from xcube.core.dsio import rimraf
from xcube.core.new import new_cube
from xcube.core.optimize import optimize_dataset
TEST_CUBE = ... | StarcoderdataPython |
78604 | from dataclasses import dataclass
from typing import Tuple
from manim import config
from manim import DEFAULT_MOBJECT_TO_EDGE_BUFFER
from manim import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER
from manim import DOWN
from manim import LEFT
from manim import Mobject
from manim import np
from manim import ORIGIN
from manim impor... | StarcoderdataPython |
3349239 | <filename>user/migrations/0002_conversionrate.py
# Generated by Django 3.0.5 on 2022-01-08 11:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Conversi... | StarcoderdataPython |
3387065 | # Copyright (c) [2021] [wlicsnju]
# [HKMF-T] is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
# http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRA... | StarcoderdataPython |
197212 | <reponame>papamarkou/bnn_mcmc_examples
# %% Import packages
from bnn_mcmc_examples.datasets import data_paths
# %% Define constants
data_base_name = 'data1'
data_path = data_paths['pima'].joinpath(data_base_name)
| StarcoderdataPython |
125140 | #!/usr/bin/env python
import unittest, rosunit, rospy
import numpy as np
import math
import tf.transformations as tr
from apriltags2_ros_post_process.data_adapter_utils import *
class DataAdapterUtils(unittest.TestCase):
if __name__ == '__main__':
rosunit.unitrun('apriltags2_ros', 'data_adapter_utils', DataAdapt... | StarcoderdataPython |
1694610 | #### standard provider code ####
# import the correct PROVIDER_SUBMODULE and PROVIDER_ID constants for your provider
from .constants import PROVIDER_ID
from ..constants import PROVIDER_SUBMODULE
# define common provider functions based on the constants
from ckan_cloud_operator.providers import manager as providers_ma... | StarcoderdataPython |
1728681 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class IP(models.Model):
"""IP address of spams"""
ip = models.GenericIPAddressField()
class Word(models.Model):
"""Word of spams"""
word = models.CharField(max_length=50)
| StarcoderdataPython |
3251672 | # ----------------------------------------------------------------------
# Fix ETL format to JSONL
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Pyth... | StarcoderdataPython |
3281285 | <filename>forte/processors/ir/bert_reranking_processor.py
# Copyright 2019 The Forte Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | StarcoderdataPython |
1779638 |
from collections import namedtuple
Sub = namedtuple("Sub", "start start_delim end end_delim pre body post")
def balanced_match(start_delim, end_delim, s):
sl = len(s)
msl = len(start_delim)
mel = len(end_delim)
match = None
depth = 0
x = 0
max_x = sl - msl - mel
while x < max_x:
... | StarcoderdataPython |
1632062 | <gh_stars>0
from korg import LineGrokker, PatternRepo
def test_pattern_not_found():
pr = PatternRepo()
lg = LineGrokker('%{UNKNOWN}', pr)
assert lg.regex is None
# test samples taken from logstash/spec/filters/grok.rb v1.1.13
"""
describe "parsing an event with multiple messages (array of strings)" do... | StarcoderdataPython |
79427 | #!/usr/bin/env python3
"""Connects the bot."""
import os
import os.path
import random
import re
import sys
import threading
import time
import hclib
import pymongo
from commands import currency
from commands import dictionary
from commands import jokes
from commands import katex
from commands import password
from c... | StarcoderdataPython |
1686249 | <gh_stars>10-100
from typing import Callable, Dict, List
import pycond as pc
from bxutils import logging
logger = logging.get_logger(__name__)
pc.ops_use_symbolic_and_txt(allow_single_eq=True)
def get_validator(filter_string: str) -> Callable[[Dict], bool]:
logger.trace("Getting validator for filters {}", filt... | StarcoderdataPython |
3219702 | <reponame>Lunarmagpie/mCodingBot
from __future__ import annotations
import platform
from typing import TYPE_CHECKING
import psutil
from pincer import command
if TYPE_CHECKING:
from pincer.objects import Embed
from mcoding_bot.bot import Bot
def _percent_info_unit_ram(used, total):
mb: int = 1024 ** 2
... | StarcoderdataPython |
164188 | <reponame>google/expt-analysis
#
# 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 applicab... | StarcoderdataPython |
1645023 | <gh_stars>0
import boto3
from collections import namedtuple
ssm_client = boto3.client('ssm', region_name='us-east-1')
def get_parameter(parameter_name: str) -> str:
"""
Fetches the value of the given parameter from AWS SSM Parameter Store.
:param parameter_name: String
:return: String
"""
r... | StarcoderdataPython |
3231324 | import asyncio
import io
import logging
import os
import unittest
from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN
from integration_tests.helpers import async_test
from slack import WebClient
class TestWebClient(unittest.TestCase):
"""Runs integration tests with real Slack API
https... | StarcoderdataPython |
1698886 | <reponame>SimonHashtag/dynetlsm
import numpy as np
from sklearn.utils import check_random_state
from .gaussian_likelihood_fast import compute_gaussian_likelihood
from .distributions import spherical_normal_log_pdf
def log_normalize(probas):
max_proba = np.max(probas)
probas -= max_proba
np.exp(probas, pr... | StarcoderdataPython |
3328753 | <gh_stars>10-100
import smacha
import uuid
from smacha.util import bcolors
from smacha.exceptions import ParsingError
__all__ = ['Generator']
class Generator():
"""Main SMACHA code generator class.
This class recursively processes the state machines described in SMACHA
YAML scripts while generating exe... | StarcoderdataPython |
4300 | import functools
import sys
from contextlib import contextmanager
import pytest
_orig_trace = None
def pytest_configure():
global _orig_trace
_orig_trace = sys.gettrace()
@pytest.fixture(scope="session", autouse=True)
def term():
"""Configure TERM for predictable output from Pygments."""
from _pyt... | StarcoderdataPython |
3306380 | """
Test the create_random_users command line script
"""
import pytest
from django.contrib.auth import get_user_model
from django.core.management import call_command
from opaque_keys import InvalidKeyError
from common.djangoapps.student.models import CourseEnrollment
from xmodule.modulestore.tests.django_utils impor... | StarcoderdataPython |
45322 | from setuptools import setup, find_packages
setup(name='dune.common',
namespace_packages=['dune'],
version='2.4',
description='Python package accompanying the DUNE project',
url='http://www.dune-project.org',
author='<NAME>',
author_email='<EMAIL>',
license='BSD',
packag... | StarcoderdataPython |
3302232 | #!/usr/bin/env python
'''
Parallelize functions with simple arguments via torque
'''
import errno
import os
import subprocess
import tempfile
def submit(walltime, memory, cwd, tmpdir,
script, name, nodes='1:ppn=1',
shellfname=None, env=None, ssh_to=None):
'''
Submit a script to torque
... | StarcoderdataPython |
3225095 | <reponame>zhangyaqi1989/LeetCode-Solutions<gh_stars>1-10
class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
if runningCost > 4 * boardingCost:
return -1
nwaits = 0
best_profit = 0
best_rotations = 0
... | StarcoderdataPython |
3294212 | from datetime import datetime
def to_time_range_sql_query(index, time, min: datetime, max: datetime, query=""):
sql = """SELECT * FROM "{}" WHERE {} BETWEEN '{}' AND '{}'""".format(
index, time, min.isoformat(),
max.isoformat())
if query:
query = query.replace('"', "'")
sql +=... | StarcoderdataPython |
119331 | <gh_stars>0
from travelperk_python_api_types.webhooks.webhooks.webhooks import Webhooks
from travelperk_python_api_types.webhooks.webhooks.webhook import Webhook
from travelperk_python_api_types.webhooks.webhooks.event import Event
class TestWebhooks:
def test_webhooks_entities_are_buildable(self):
webhoo... | StarcoderdataPython |
3228269 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2015, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2015. UChicago Argonn... | StarcoderdataPython |
1739005 | <gh_stars>0
# coding=utf-8
"""
1.执行带参数的SQL时,请先用sql语句指定需要输入的条件列表,然后再用tuple/list进行条件批配
2.在格式SQL中不需要使用引号指定数据类型,系统会根据输入参数自动识别
3.在输入的值中不需要使用转意函数,系统会自动处理
"""
from DBUtils.PooledDB import PooledDB
from config import *
class MySQL(object):
"""
MYSQL数据库对象,负责产生数据库连接
此类中的连接采用连接池实现获取连接对象, conn = Mysql.getConn()
... | StarcoderdataPython |
3317107 | # Generated by Django 2.2.4 on 2019-12-02 14:46
from django.db import migrations, models
class Migration(migrations.Migration):
def copy_owners_to_owner(apps, schema_editor):
Flat = apps.get_model('property', 'Flat')
Owner = apps.get_model('property', 'Owner')
for owner in Flat.objects.a... | StarcoderdataPython |
1604950 | <reponame>Fourdee/mayan-edms<gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-10 06:39
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
def create_parsing_setting_for_existing_document_types(apps, schema_editor):
Docum... | StarcoderdataPython |
3212534 | <reponame>DouglasCarvalhoPereira/Interact-OS-PYTHON
#!/usr/bin/env python
#Script que verifica se o código foi executado com sucesso ou não.
import os
import sys
filename=sys.argv[1]
if not os.path.exists(filename):
with open(filename, 'w') as f:
f.write("New file created\n")
else:
print("Error, the... | StarcoderdataPython |
3205896 | from flask import abort, Blueprint, render_template, request, redirect, flash
from django.core.exceptions import ValidationError
from config.settings import DOMAIN_NAME
from database.study_models import Survey
from libs.admin_authentication import authenticate_admin_study_access,\
get_admins_allowed_studies, admin... | StarcoderdataPython |
1782302 | <filename>utils/routines.py<gh_stars>1-10
import numpy as np
def load_sample_data_pca():
np.random.seed(3)
eps=0.5
n=30
x=np.random.uniform(-1,1,n)
y=x+eps*np.random.uniform(-1,1,n)
x=x-np.mean(x)
y=y-np.mean(y)
data=np.vstack((x,y)).transpose()
return data
def load_mul... | StarcoderdataPython |
3252602 | <gh_stars>0
import os
from keras import models, layers
from keras.applications import VGG16
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from optimizer.KerasOptimizer import KerasOptimizer
from optimizer.Strategy import Strategy
def custom_model():
num_of_classes = 2... | StarcoderdataPython |
186101 | import pickle
from utils import *
def visualize(_id, predict, label, masks, words, sent_attns=[1], msg=False, save_html=False, save_img=True):
h5_string_list = list()
h5_string_list.append('<div class="cam">')
h5_string_list.append("<head><meta charset='utf-8'></head>")
h5_string_list.append("Change Id... | StarcoderdataPython |
78201 | import os
from unittest import mock
import pytest
from kubernetes.client.exceptions import ApiException
from task_processing.plugins.kubernetes.kube_client import ExceededMaxAttempts
from task_processing.plugins.kubernetes.kube_client import KubeClient
def test_KubeClient_no_kubeconfig():
with mock.patch(
... | StarcoderdataPython |
1788285 |
from apgl.io.GraphReader import GraphReader
from apgl.graph.VertexList import VertexList
from apgl.graph.SparseGraph import SparseGraph
import logging
class SimpleGraphReader(GraphReader):
'''
A class to read SimpleGraph files.
'''
def __init__(self):
pass
def re... | StarcoderdataPython |
3200328 | from injector import Injector, Module, provider, singleton, inject
from ...ioc import injector
from ...types import Apps
class CommandLineHelp:
def run():
apps = injector.get(Apps)
print('Available modules:', ', '.join(apps.keys()))
injector.binder.bind(Apps, to={'help': CommandLineHelp}, scope=singleton)
| StarcoderdataPython |
1611869 | #!/usr/bin/env python3
## cl-Jupyter installation script
## Note: since the kernel of Jupyter is written itself in Python,
## it is much simpler to have a Python-based installation script.
import subprocess
import sys
import shutil
import os
import json
class RequirementException(BaseException):
pass
d... | StarcoderdataPython |
4807564 | <reponame>cgx027/alfred-workflow
import unittest
import mock
from utest.helper import (write_json, read_json, remove_file)
from utils.confluence import *
class TestFtpLogMove(unittest.TestCase):
maxDiff = None
def test_get_space_title(self):
# https://confluence.eng.vmware.com/display/CERTSH/Bugzilla+... | StarcoderdataPython |
44268 | <reponame>unmtransinfo/Exfiles<gh_stars>0
#!/usr/bin/env python3
"""exfiles_similarity.py
Expression profiles similarity computation.
- Author: <NAME>
- Required: Python3, Pandas 0.22+
- Input expression profiles format expected: TSV, 2 columns of identifiers (ENSG, SEX) followed by multiple columns of expression... | StarcoderdataPython |
1643522 | #orignal was: from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .models import Program, Episode, Tweeter, Tweet
from .tasks import sdelta
import datetime
def index(request):
template = "rewyndapp/b_index.html"
return render(request, template)
def programs... | StarcoderdataPython |
88287 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import types
import re
import cgi
from functools import wraps
import logging
from decorators import FuncDecorator, property
from ..compat import *
from ..exception import CallError
logger = logging.getLogger(_... | StarcoderdataPython |
1761429 | <reponame>OpenGeoOne/GeoRural
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GeoINCRA
A QGIS plugin
Georreferenciamento de Imóveis Rurais
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
... | StarcoderdataPython |
123519 | from .geohash_base import encode, bbox, expand
from .distance_metrics import distance, dimensions
from math import sqrt
from shapely.geometry import Polygon
from shapely.ops import unary_union
# Note: (lat, lon) are essentially in the (y, x) format in the cartesian plane.
# shapely works with/assumes coordinates in ... | StarcoderdataPython |
3373516 | # encoding=utf-8
import datetime
import os
import random
import re
import time
import unicodedata
import jieba
from torch import nn
from config import *
def ensure_folder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def maskNLLLoss(inp, target, mask):
nTotal = mask.sum()
crossEntr... | StarcoderdataPython |
1630044 | <reponame>hendriksanta/probability
# Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | StarcoderdataPython |
3326814 | #!/usr/bin/env python
# coding: utf8
# / usr / bin / python
import os
import sys
import time
import zmq
import json
"""
sock.send(part1, zmq.SNDMORE)
sock.send(part2, zmq.SNDMORE)
sock.send(part3, zmq.SNDMORE)
sock.send(final)
"""
import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from... | StarcoderdataPython |
1610596 | <gh_stars>0
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'robots.views',
url(r'^$', 'rules_list', name='robots_rule_list'),
)
| StarcoderdataPython |
3254714 | <filename>tests/conftest.py
import pytest
@pytest.fixture(scope="module")
def new_incoming():
return {
"text": "**good** incoming",
"markdown": True,
"channel": "testing",
"attachments": [{
"title": "title_1",
"text": "attachment_text",
"color": ... | StarcoderdataPython |
3204453 | <reponame>chasesagar/Python-Programming
# A program to find prime numbers in given range
class MathBasic:
def __init__(self, start: int = 2, end: int = 10):
self.start = start
self.end = end
self.recursion_prime_list = []
def prime_numbers_list_compression(self):
"""
[... | StarcoderdataPython |
156488 | #!/usr/bin/env python
from clipper_admin import ClipperConnection, DockerContainerManager
clipper_conn = ClipperConnection(DockerContainerManager())
clipper_conn.stop_all() | StarcoderdataPython |
4843331 | <filename>processlib/csvToInfluxdb.py
import requests
import argparse
import csv
import datetime
import json
from pytz import timezone
from influxdb import InfluxDBClient
epoch_naive = datetime.datetime.utcfromtimestamp(0)
epoch = timezone('UTC').localize(epoch_naive)
def unix_time_millis(dt):
retur... | StarcoderdataPython |
3319415 | <reponame>arabindamahato/DjangoREST_API_DRF
from django.db import models
# Create your models here.
class Teacher(models.Model):
tno=models.IntegerField()
tname=models.CharField(max_length=64)
tsal=models.FloatField()
taddr=models.CharField(max_length=64)
| StarcoderdataPython |
3292433 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from google.cloud.bigquery.schema import SchemaField
class BigQuerySchemaField(object):
def __init__(self, name, field_type, mode='NULLABLE',
description=None, fields=None):
self.name = name
self.field... | StarcoderdataPython |
1721757 | from __future__ import nested_scopes, generators, division, absolute_import, with_statement, \
print_function, unicode_literals
from .utilities.compatibility import backport
backport()
import serial.abc
from copy import deepcopy
import serial
from .utilities import qualified_name
from .abc.model import Model
tr... | StarcoderdataPython |
3211204 | from .reader import load
__version__ = '1.0.1' | StarcoderdataPython |
3388053 | """
Test settings for ``polymorphic_auth`` app.
"""
AUTH_USER_MODEL = 'polymorphic_auth.User'
POLYMORPHIC_AUTH = {
'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser',
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
DEBUG = True
EMAIL_BAC... | StarcoderdataPython |
27624 | <reponame>noironetworks/shade<gh_stars>10-100
import shade
# Initialize and turn on debug logging
shade.simple_logging(debug=True)
for cloud_name, region_name in [
('my-vexxhost', 'ca-ymq-1'),
('my-citycloud', 'Buf1'),
('my-internap', 'ams01')]:
# Initialize cloud
cloud = shade.opensta... | StarcoderdataPython |
16100 | <filename>tests/explainers/test_explainer.py
""" Tests for Explainer class.
"""
import pytest
import shap
def test_wrapping_for_text_to_text_teacher_forcing_logits_model():
""" This tests using the Explainer class to auto choose a text to text setup.
"""
transformers = pytest.importorskip("transformers"... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.