id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1669145 | <filename>cdk-app/scripts/processing_script/preprocessing.py<gh_stars>1-10
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os
import pyspark
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import (
DoubleType,
... | StarcoderdataPython |
4805796 | import struct
from pathlib import Path
from typing import IO
import numpy as np
_INDIANNESS: str = "<"
"""Based on 'ieee-le' of MATLAB (see ``src/main/matlab/dataset/wu2/generate_audio_files.m``)"""
_SAMPLE_TYPE: str = "f"
"""Based on 'single' of MATLAB (see ``src/main/matlab/dataset/wu2/generate_audio_files.m``)""... | StarcoderdataPython |
65494 | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | StarcoderdataPython |
148419 | <filename>bert-sentiment/src/app.py
import flask
import torch
from flask import Flask, render_template, request
from utils import label_full_decoder
import sys
import config
import dataset
import engine
from model import BERTBaseUncased
from tokenizer import tokenizer
from werkzeug.serving import run_simple
from werkze... | StarcoderdataPython |
17080 | from django.core.mail import EmailMessage
from django.conf import settings
def send_email(name, date, email):
txt = """
<html>
<body>
<table cellpadding='0' cellspacing='0' width='100%' border='0'>
<tbody>
<tr>
<td style='word-wrap:break-word;font-size:0px;padding:0px;padding-bottom:10px' alig... | StarcoderdataPython |
25263 | <reponame>Holly-Jiang/QCTSA
class NeighborResult:
def __init__(self):
self.solutions = []
self.choose_path = []
self.current_num = 0
self.curr_solved_gates = []
| StarcoderdataPython |
1741893 | <filename>Desktop/cs61a/lab/lab02/lab02.py
"""Lab 2: Lambda Expressions and Higher Order Functions"""
# Lambda Functions
def lambda_curry2(func):
"""
Returns a Curried version of a two-argument function FUNC.
>>> from operator import add
>>> curried_add = lambda_curry2(add)
>>> add_three = curried... | StarcoderdataPython |
124849 | import io
import unittest
from unittest.mock import patch
from kattis import k_trip2007
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run and asser... | StarcoderdataPython |
1747869 | <gh_stars>0
"""
Serving class that consumes images and outputs segmentation bitmap.
"""
import numpy as np
import torch
import mmcv
from mmcv.parallel import collate
from mmseg.datasets.pipelines import Compose
from mmseg.apis.inference import init_segmentor, inference_segmentor, LoadImage
from mmseg.ops import resiz... | StarcoderdataPython |
1600260 | <gh_stars>0
from .boilerplate import boilerplate
from .build import build
from .generate import generate
from .precompute import precompute
from .sources import sources
from .update import update
| StarcoderdataPython |
3218340 | """
Support for functionality to have conversations with AI-Speaker.
"""
import asyncio
import datetime
import json
import logging
import re
import subprocess
import warnings
import platform
from aiohttp.web import json_response
import async_timeout
import psutil
import requests
import voluptuous as vol
from homeass... | StarcoderdataPython |
1635651 | from thinsos.core import SOS
| StarcoderdataPython |
167811 | #!/usr/bin/env python3
import argparse
import glob
import os
import send2trash
script_info = ("""
Script to make a Manifest.csv file for importing fastq.gz files into a qiime 2 environment.
To Install:
Open Qiime2 conda environment
Install python package "send2trash" using: pip install send2trash
Put ... | StarcoderdataPython |
3291364 | <gh_stars>10-100
from typing import Dict, List, Optional
from .const import TAG_ESCAPED, TAG_UNESCAPED
def _escape_tag(value: str):
for i, char in enumerate(TAG_UNESCAPED):
value = value.replace(char, TAG_ESCAPED[i])
return value
def format(
tags: Optional[Dict[str, str]],
source: ... | StarcoderdataPython |
199284 | <gh_stars>10-100
'''
Tests for dumpsegd
'''
import os
import sys
import unittest
from mock import patch
from testfixtures import OutputCapture
from ph5.utilities import dumpsegd
from ph5.core.tests.test_base import LogTestCase, TempDirTestCase
class TestDumpSEGD(TempDirTestCase, LogTestCase):
def test_main(self... | StarcoderdataPython |
3296294 | class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
ans = [0 for _ in range(length)]
for i in range(length):
ans[nums[i] - 1] += 1
return [i + 1 for i in range(length) ... | StarcoderdataPython |
4817569 | #! /usr/bin/env python
''' Main program'''
import re
import os.path
import shutil
import json
import sys
from typing import Tuple
class Folder():
''' Stores the folder name and its full path'''
def __init__(self, name: str, path: str):
self.name = name
self.path = path
class File():
'... | StarcoderdataPython |
16230 | <filename>examples/tensorboard/nested.py
import tensorboardX
with tensorboardX.SummaryWriter("foo") as w:
w.add_scalar("a", 1.0, 1)
w.add_scalar("a", 2.0, 2)
with tensorboardX.SummaryWriter("foo/bar") as w:
w.add_scalar("a", 3.0, 3)
w.add_scalar("a", 4.0, 4)
with tensorboardX.SummaryWriter("foo/bar/b... | StarcoderdataPython |
3304456 | <gh_stars>0
lista = []
lista1 = []
while True:
try:
lista.append(input())
except EOFError:
break
for i in lista:
i = i.lower()
lista1.append(i)
lista1.sort()
for i in lista:
if lista1[-1] == i.lower():
print (i)
break
| StarcoderdataPython |
4813010 | import os
from setuptools import find_packages, setup
import versioneer
readMeFile = os.path.join(os.path.abspath(os.path.dirname(__file__)), "README.md")
if os.path.exists(readMeFile):
with open(readMeFile, encoding="utf-8") as readMeFile:
long_description = readMeFile.read()
else:
long_description... | StarcoderdataPython |
58124 |
def clean_path(path):
"""
Removes illegal characters from path (Windows only)
"""
return ''.join(i for i in path if i not in '<>:"/\|?*')
| StarcoderdataPython |
3238404 | <filename>apprest/tests/unit/services/test_users.py
import json
from django.http import HttpRequest
from apprest.services.user import CalipsoUserServices
from apprest.tests.utils import CalipsoTestCase
class UserServiceTestCase(CalipsoTestCase):
def setUp(self):
self.logger.debug('#################### ... | StarcoderdataPython |
3351543 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import time
import unittest
from fvcore.common.config import CfgNode
from fvcore.common.history_buffer import HistoryBuffer
from fvcore.common.timer import Timer
class TestHistoryBuffer(unittest.TestCas... | StarcoderdataPython |
3277150 | """
SimplestCalcLib that contains basic math operations
"""
def add(first_num, second_num):
return first_num + second_num
def subtract(first_num, second_num):
return first_num - second_num | StarcoderdataPython |
77152 | <gh_stars>1-10
# coding=utf-8
# Copyright 2022 The Fiddle-Config 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
#
# Unless require... | StarcoderdataPython |
1696542 | # Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
157906 | """
Tests for salt.modules.boto3_route53
"""
import random
import string
import salt.loader
import salt.modules.boto3_route53 as boto3_route53
from salt.utils.versions import LooseVersion
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.uni... | StarcoderdataPython |
3263336 | import sys
import setuptools
if sys.version_info < (3, 7, 0):
raise OSError(f'Streamlit requires Python 3.7 and above, but yours is {sys.version}')
try:
with open('README.md', encoding='utf8') as fp:
_long_description = fp.read()
except FileNotFoundError:
_long_description = ''
setuptools.setup... | StarcoderdataPython |
94444 | from nose.tools import assert_equal, assert_almost_equal, assert_true, \
assert_false, assert_raises, assert_is_instance
from stats import mean, median, mode, std, var
# mean tests
def test_mean1():
obs = mean([0, 0, 0, 0])
exp = 0
assert_equal(obs, exp)
obs = mean([0, 200])
exp = 100
ass... | StarcoderdataPython |
1742470 | """External Routes functions tests."""
# run these tests like:
#
# flask_env=production python -m unittest test_external_routes.py
from unittest import TestCase
from external_routes import search_board_games, update_mechanics, update_categories, add_game_to_db
from models import db, User, Game, Collection, Categor... | StarcoderdataPython |
3203466 | from base64 import b64encode, b64decode
from bs4 import BeautifulSoup as soup
from bz2 import BZ2File
from collections import Counter, OrderedDict
from copy import deepcopy
from datetime import datetime as dt, timedelta
try:
from etk.extractors.date_extractor import DateExtractor
except OSError:
from s... | StarcoderdataPython |
12815 | <reponame>learning-nn/nn_from_scratch
import numpy
import numpy as np
# converting to a layer with 4 input and 3 neuron
inputs = [[1.2, 2.1, 3.4, 1.2],
[1.2, 2.1, 3.4, 1.2],
[1.2, 2.1, 3.4, 1.2]]
print(numpy.shape(inputs))
weights = [[4.1, -4.5, 3.1, 2.3],
[-4.1, 4.5, 2.1, 2.3],
... | StarcoderdataPython |
3371394 | <gh_stars>1-10
from django.conf.urls import url
from django.conf.urls import include
from rest_framework.routers import DefaultRouter
from .views import (HelloApiView,HelloViewSet,UserProfileViewSet,LoginViewSet,
UserProfileFeedViewSet)
router = DefaultRouter()
router.register('hello-viewset', He... | StarcoderdataPython |
156544 | <filename>analisis-de-algoritmos/algoritmos/binarySearch.py
#
# The Binary Search
#
# cretid: https://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearch.html
def binary_search(vector, item):
inicio = 0
fin = len(vector)-1
encontrado = False
while inicio<=fin and not encontrad... | StarcoderdataPython |
3234230 | <filename>bspump/random/source.py
import logging
import asyncio
import random
from ..abc.source import TriggerSource
L = logging.getLogger(__name__)
class RandomSource(TriggerSource):
'''
`RandomSource` is mostly meant for testing. It
generates n (specified in `Config` as `number`, default is 1000) events per ... | StarcoderdataPython |
1738397 | <reponame>uwase-diane/NewsAPI
class Article:
'''
Source class to define Source Objects
'''
def __init__(self,urlToImage,title,description,url,publishedAt):
self.urlToImage = urlToImage
self.title = title
self.description = description
self.url = url
self... | StarcoderdataPython |
137985 | <gh_stars>10-100
from pydantic import BaseModel
class MyBase(BaseModel):
"""MyBase"""
field_on_base: str
"""Base Field"""
class MySubclass(MyBase):
"""MySubClass"""
field_on_subclass: str
"""Subclass field"""
| StarcoderdataPython |
3287681 | import warnings
import logging
from .base import Attack
from .base import call_decorator
from .saltandpepper import SaltAndPepperNoiseAttack
from .. import rng
class PointwiseAttack(Attack):
"""Starts with an adversarial and performs a binary search between
the adversarial and the original for each dimension... | StarcoderdataPython |
1703721 | import random
from discord.ext import commands
from extras.constants import COMMAND_PREFIXES
# from extras.errors import MusicErros as errors
def get_prefix(client, message):
"""
A callable Prefix for our client. This could be edited to allow per server prefixes.
"""
prefixes = COMMAND_PREFIXES
... | StarcoderdataPython |
156974 | """Bundles all exceptions and warnings used in the package prodsim"""
class InvalidValue(Exception):
""" Raises when a value is not within the permissible range """
pass
class InvalidType(Exception):
""" Raises when a value has the wrong type """
pass
class MissingParameter(Exception):
""" Raised... | StarcoderdataPython |
4826970 | <gh_stars>1-10
# templatefilters.py - common template expansion filters
#
# Copyright 2005-2008 <NAME> <<EMAIL>>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import os
import re
import ti... | StarcoderdataPython |
197544 | <gh_stars>10-100
import sys
import types
import uuid
from StringIO import StringIO
import json
from .outputhandlers.shellcolors import OutputHandler
from .. import unicodehelper
class BaseErrorBundle(object):
"""Keyword Arguments:
**determined**
Whether the validator should continue after a tier fa... | StarcoderdataPython |
130302 | <reponame>gpapaz/eve-wspace
# Eve W-Space
# Copyright 2014 <NAME> and contributors
#
# 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 |
141205 | # © 2019 Nokia
# Licensed under the BSD 3 Clause license
# SPDX-License-Identifier: BSD-3-Clause
import os
from setuptools import setup, find_packages
pkg_name = 'radish_rest'
def _packages():
packages = [f'{pkg_name}.{sub_pkg_name}' for sub_pkg_name in
find_packages(os.path.join(os.path.dirnam... | StarcoderdataPython |
3261242 | # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# ME... | StarcoderdataPython |
85598 | # -*- coding: utf-8 -*-
#
# Copyright © 2021–2022 <NAME> <<EMAIL>>
# Released under the MIT Licence
#
import pytest
from datetime import date
from pytcnz.squashnz.player import Player
from .test_playerbase import PLAYER
PLAYER = PLAYER | dict(
id=14,
squash_code="WNTHJXD",
points=3050,
dob="1-Sep-199... | StarcoderdataPython |
3212929 | # -*- coding: utf-8 -*-
import io
import tqdm
import requests
from PIL import Image
BASE_URL = 'https://api.nosconecta.com.ar/'
PATH = 'eform/thumbnail/{}'
BASE_PARAMS = {
'resize': 'full',
'page': '0',
}
FOLDER_URL = 'https://ar.turecibo.com/bandeja.php?apiendpoint=/folders/{}/documents/available'
MAX_FAILED_... | StarcoderdataPython |
3256056 | <filename>comath/metric/metric.py
"""metric-related utility functions."""
import abc
class MovingMetricTracker(metaclass=abc.ABCMeta):
"""An object that tracks and computes a moving metric."""
def __init__(self, metric_name):
self.metric_name = metric_name
@abc.abstractmethod
def add_value(... | StarcoderdataPython |
29031 | class BaseAnsiblerException(Exception):
message = "Error"
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args)
self.__class__.message = kwargs.get("message", self.message)
def __str__(self) -> str:
return self.__class__.message
class CommandNotFound(BaseAnsiblerEx... | StarcoderdataPython |
3227675 | <gh_stars>10-100
class Material:
def __init__(self, diffuse=[.8, .8, .8], spec_weight=0., specular=[0., 0., 0.],
ambient=[0., 0., 0.], opacity=1., flat_shading=False, texture_file=None):
self.diffuse = diffuse
self.spec_weight = spec_weight
self.specular = specular
... | StarcoderdataPython |
131004 | """
inheritance-diagram:: dfo.optimizer.direct
:parts: 1
"""
from misc.debug import DbgMsgOut, DbgMsg
from .base import BoxConstrainedOptimizer
from numpy import max, min, abs, array
import numpy as np
import heapq
__all__ = ['Cube', 'DIRECT']
class Cube(object):
def __init__(self, x, f, depth):
se... | StarcoderdataPython |
3288493 | <gh_stars>0
from collections import deque
from .node import Node
class AhoCorasick(object):
def __init__(self):
'''
AhoCorasick 이니셜라이징
'''
self.head = Node()
self.head.fail = 0
self.pattern = set()
self.idx = 1
self.aho_corasick = {0: self.head}
... | StarcoderdataPython |
1773369 | from disasm import Types
from utils.ail_utils import ELF_utils, unify_int_list, dec_hex, get_loc
class lib32_helper(object):
"""
Manage PC relative code for x86 32bit binaries
"""
def __init__(self, instrs, funcs):
"""
:param instrs: instruction list
:param funcs: function lis... | StarcoderdataPython |
3397951 | <filename>bfassist/standalone/monitoring/realtimeround.py
#############################################################################
#
#
# Module of BFA that manages server statistics in realtime
#
#
#############################################################################
""" This module implements the real-tim... | StarcoderdataPython |
1715985 | class TestData:
CHROME_EXECUTABLE_PATH = "/Users/User/Desktop/selenium/selinium/python chromedriver/chromedriver"
FIREFOX_EXECUTABLE_PATH = "/Users/User/Desktop/selenium/selinium/python chromedriver/geckodriver"
BASE_URL = "https://app.hubspot.com/login"
"""https://app.hubspot.com/login... | StarcoderdataPython |
3304143 | import os
TEST_WEBGPU = os.environ.get("TEST_WEBGPU", "1") == "1"
TEST_WEBGL = os.environ.get("TEST_WEBGL", "1") == "1"
TEST_WEBASSEMBLY = os.environ.get("TEST_WEBASSEMBLY", "1") == "1"
TEST_FALLBACK = os.environ.get("TEST_FALLBACK", "1") == "1"
| StarcoderdataPython |
3348841 | <reponame>bopopescu/sage-5
r"""
Hasse diagrams of posets
"""
#*****************************************************************************
# Copyright (C) 2008 <NAME> <<EMAIL>>,
# <NAME> <<EMAIL>>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code i... | StarcoderdataPython |
104827 | #!/usr/bin/env python
import os
import re
from collections import OrderedDict
from functools import reduce
import pandas as pd
from unidecode import unidecode
def get_place_names(data_dir):
places = []
for fn in os.listdir(data_dir):
if not fn.endswith('.xlsx'):
continue
print(... | StarcoderdataPython |
57845 | constants.physical_constants["electron-triton mass ratio"] | StarcoderdataPython |
1642232 | <filename>cengal/RequestCache.py
#!/usr/bin/env python
# coding=utf-8
# Copyright © 2016 ButenkoMS. All rights reserved. Contacts: <<EMAIL>>
#
# 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
#... | StarcoderdataPython |
1644354 | <reponame>charlesxin97/ToolFinder_binder<filename>binary_classifier/DNN.py
import torch.nn as nn
import torch
from collections import OrderedDict
class FFN(nn.Module):
def __init__(self, layer_arch, input_size, output_size, bias=True):
super(FFN, self).__init__()
self.layer_arch = layer_arch... | StarcoderdataPython |
1711823 | import argparse
import numpy as np
import math
def is_pos_def(x):
return np.all(np.linalg.eigvals(x) > 0)
def get_multigaussian_pdf(_mean, _cov, _cov_i, num_variable, Y_variable):
"""
calculate multivariate Gaussian PDF for given mean & cov for each sample.
Parameters
----------
_mea... | StarcoderdataPython |
1726339 | <gh_stars>0
class Relation:
def __init__(self,giver,receiver):
self.name = ""
self.description = ""
self.giver = giver
self.receiver = receiver
giver.diplomatic_relations.append(self)
receiver.diplomatic_relations.append(self)
def describe_relation(self):
... | StarcoderdataPython |
76694 | <reponame>SOFIE-project/IAA
import pytest
import requests
import jwt
import nacl.signing
import nacl.encoding
privateKeyHex = '<KEY>'
publicKeyHex = 'E390CF3B5B93E921C45ED978737D89F61B8CAFF9DE76BFA5F63DA20386BCCA3B'
class TestJWTwithPoP:
def test_valid_bearer_get(self):
token = "<KEY>"
headers =... | StarcoderdataPython |
1684533 | <reponame>kraj/intel-iot-refkit<filename>meta-iotqa/lib/oeqa/runtime/multimedia/vaapi/test_vaapi_present.py
'''
This test suit tests VAAPI is present or not
'''
from oeqa.oetest import oeRuntimeTest
class VAAPITest(oeRuntimeTest):
def test_vaapi_present(self):
(status, output) = self.target.run("vainfo")
... | StarcoderdataPython |
94240 | # -*- coding: utf-8 -*-
"""Call back view for OAuth2 authentication."""
from django import http
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.core.handlers.wsgi import WSGIRequest
from django.shortcuts import redirect, reverse
from django.utils.translation ... | StarcoderdataPython |
3215984 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, Inc
#
# 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 |
3247765 | <gh_stars>10-100
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
from matplotlib import pyplot as plot
from utils import plot_image, plot_curve, one_hot, save_data
# step1 装数据
batch_size = 512
# step1. load dataset
train_loader = torch.utils.data... | StarcoderdataPython |
4815282 | from typing import Dict, List, NamedTuple, Optional, Tuple
from app import db
from app.models import Project, Schedule, User, Team
from sqlalchemy import func
class WeekProject(NamedTuple):
week: int
project_id: int
class WeekUser(NamedTuple):
week: int
user_id: int
def set_schedule(
user_id:... | StarcoderdataPython |
104624 | from collections import OrderedDict, defaultdict
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import time
import torch
from FClip.line_parsing import OneStageLineParsing
from FClip.config import M
from FClip.losses import ce_loss, sigmoid_l1_loss, focal_loss, l12loss
from FClip.nms import ... | StarcoderdataPython |
110922 | <gh_stars>0
import urllib, urllib3, json
from datetime import datetime
from core.art.modelsART import ARTSubResult
from django.db import connection, transaction, DatabaseError
from core.settings import defaultDatetimeFormat
import logging
_logger = logging.getLogger('bigpandamon-error')
def getJobReport(guid, lfn, ... | StarcoderdataPython |
1622635 | from setuptools import setup
def read(fname):
import os
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='pdtweak',
version='0.1.1',
description='pandas utility functions',
long_description=read('README.md'),
long_description_content_type='text/markdown',... | StarcoderdataPython |
164568 | <filename>triflow/core/compilers.py
#!/usr/bin/env python
# coding=utf8
from functools import partial
import numpy as np
from scipy.sparse import csc_matrix
from sympy import lambdify
def theano_compiler(model):
"""Take a triflow model and return optimized theano routines.
Parameters
----------
mod... | StarcoderdataPython |
133287 | # Copyright (c) 2018 PaddlePaddle 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.org/licenses/LICENSE-2.0
#
# Unless required by app... | StarcoderdataPython |
1611290 | <reponame>daniele-mc/HacktoberFest2020-4
from operator import ixor
from functools import reduce
def xop(n=4,start=3):
nums=[]
for i in range(0,n):
nums.append(start+2*i)
return (reduce(ixor,nums))
print(xop())
| StarcoderdataPython |
3359602 | import json
import unittest
from os import path
import xarray as xr
from granule_ingester.processors import TileSummarizingProcessor
from granule_ingester.processors.reading_processors import GridMultiVariableReadingProcessor
from granule_ingester.processors.reading_processors.GridReadingProcessor import GridReadingPr... | StarcoderdataPython |
80668 | from setuptools import setup, Extension
import numpy as np
from Cython.Build import cythonize
from Cython.Distutils import build_ext
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
# Obtain the numpy include directory. This logic works across numpy versions.
try:
numpy_include = np.get_includ... | StarcoderdataPython |
178032 | <reponame>tykling/qwiic_exporter
# type: ignore
"""qwiic_exporter.py test suite.
Runs with pytest and tox.
"""
import logging
from qwiic_exporter import QwiicExporter
def test_get_sensor_signatures():
"""Make sure the get_sensor_signatures() method returns the expected signatures for known sensors."""
qwe =... | StarcoderdataPython |
1747904 | # Script to create an env_var by calling the http endpoint localhost:8080/conf/env/{env_var_name}/{env_var_value}
import os
from flask import Flask
app = Flask(__name__)
@app.route("/env/<name>/<var>")
def set_env_var(name, var):
os.environ[name] = str(var)
return os.environ.get(name)
if __name__=='__main__... | StarcoderdataPython |
3334744 | <reponame>jattoabdul/vanhack-cms
from app.repositories.base_repo import BaseRepo
from app.models.student import Student
from uuid import uuid4
from sqlalchemy.sql.expression import or_
class StudentRepo(BaseRepo):
def __init__(self):
BaseRepo.__init__(self, Student)
def new_user(self, first_name, last_name, em... | StarcoderdataPython |
172206 | # --------------
#Importing header files
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = pd.read_csv(path)
data['Rating'].hist()
data = data[data['Rating']<=5]
data['Rating'].hist()
#Code starts here
#Code ends here
# --------------
# code starts here
total_null = data.isn... | StarcoderdataPython |
3336014 | ###################### LEVELING #####################
lvl=0
strn=10
vit=10
dex=10
inte=10
fth=10
stm=10
mge=10
lvl=0
levels=0
freelvls=30
stattochange=0
while freelvls>0:
print("allocate stats")
print("Unallocated levels: "+ str(freelvls))
print("level: "+ str(lvl))
print("1 Vitality:"+str(vit))
print("2 Stamina:"... | StarcoderdataPython |
1756720 | <reponame>legumeinfo/CoNekT
import os
from tempfile import mkstemp
from flask import request, flash, url_for
from conekt.extensions import admin_required
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from conekt.controllers.admin.controls import admin_controls
from conekt.forms.admin.add_s... | StarcoderdataPython |
1730080 | <gh_stars>1-10
import numpy as np
import pytest
from ..sim_utils import Sim
PIXEL_SCALE = 0.263
@pytest.mark.parametrize('gal_type', ['exp'])
@pytest.mark.parametrize('psf_type', ['gauss', 'ps'])
@pytest.mark.parametrize('homogenize_psf', [False, True])
@pytest.mark.parametrize('n_coadd_psf', [1, 2, 3])
def test_s... | StarcoderdataPython |
4836654 | import timm
import torch
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
from torchvision import datasets
import numpy as np
import os
NUM_CLASSES_DICT = {'imagenette':10,'imagenet':1000,'flower102':102,'cifar':10,'cifar100':100,'svhn':10}
def get_model(model_nam... | StarcoderdataPython |
1792584 | <gh_stars>0
import requests as rqt
import datetime as dts
import yagmail
# import sched
import time
from keep_alive import keep_alive
# s = sched.scheduler(time.time, time.sleep)
# user credentials
MAIL = "<EMAIL>"
PASSCODE = "<PASSWORD>"
MY_LAT = 12.971599
MY_LNG = 77.594566
MY_LOC = (MY_LAT, MY_LNG)
# print(MY_LOC... | StarcoderdataPython |
4811508 | <filename>progress/1130_wordcloud.py
#DataFrame을 dictionary형태로 변환
#Positive WordCloud
import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt
%matplotlib inline
data=pd.read_csv("./Keyword_Dataset/Positive_Keyword.csv")
pos_text=''
#display(data)
cloud_dic=data.set_index('Korean (ko)').to_d... | StarcoderdataPython |
74227 | """Run the Celery jobs."""
import os
from app import celery, create_app
import app.tasks
flask_app = create_app(os.getenv('FLASK_CONFIG') or 'default')
flask_app.app_context().push()
| StarcoderdataPython |
1765983 | <filename>image_demo.py
#! /usr/bin/env python
# coding=utf-8
#================================================================
# Copyright (C) 2019 * Ltd. All rights reserved.
#
# Editor : VIM
# File name : image_demo.py
# Author : YunYang1994
# Created date: 2019-01-20 16:06:06
# Description :... | StarcoderdataPython |
1779033 | <filename>locale/pot/api/plotting/_autosummary/pyvista-themes-_SliderStyleConfig-slider_width-1.py
import pyvista
pyvista.global_theme.slider_styles.modern.slider_width = 0.04
| StarcoderdataPython |
4822441 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 The TARTRL 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | StarcoderdataPython |
82205 | from tabulate import tabulate
row = ["o"] * 4
board = [row] * 4
board[1][1] = "x"
print(tabulate(board))
| StarcoderdataPython |
3312486 | <reponame>narumiruna/inference-template
from abc import ABCMeta, abstractmethod
class Hook(metaclass=ABCMeta):
@abstractmethod
def __call__(self, frame):
raise NotImplementedError
@abstractmethod
def begin(self):
raise NotImplementedError
@abstractmethod
def end(self):
... | StarcoderdataPython |
193727 | <reponame>onedata/oneclient-pkg
import sys
from subprocess import STDOUT, check_call, check_output
dist = sys.argv[1]
# get package
packages = check_output(['ls', '/root/pkg']).split()
packages = sorted(packages, reverse=True)
oneclient_package = [path for path in packages
if path.startswith('one... | StarcoderdataPython |
1630361 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import copy
import math
try:
from transformers.modeling_bert import BertConfig, BertEncoder, BertModel
except:
from transformers.models.bert.modeling_bert import BertConfig, BertEncoder, BertModel
class LSTM(nn.M... | StarcoderdataPython |
4808171 | <gh_stars>1-10
import subprocess
import shlex
import os
from rlpython.utils.argument_parser import (
ReplArgumentParserError,
ReplArgumentParser,
)
class ShellRuntime:
def __init__(self, repl):
self.repl = repl
self._old_pwd = os.getcwd()
def validate_source(self, raw_source):
... | StarcoderdataPython |
4804931 | <reponame>zihen/quart-restplus
# -*- coding: utf-8 -*-
import pytest
import quart_restplus as restplus
from quart import url_for, Blueprint
from quart.routing import BuildError
async def test_default_apidoc_on_root(app, client):
restplus.Api(app, version='1.0')
async with app.test_request_context():
... | StarcoderdataPython |
31456 | from typing import Iterable, Optional
from django import VERSION
from django.db.models.base import Model
from django.db.models.fields.related import ManyToManyField
from django.db.models.fields.reverse_related import ManyToOneRel
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
... | StarcoderdataPython |
3343437 | <filename>scripts/study_case/ID_4/torch_geometric/nn/models/autoencoder.py
import math
import random
import torch
import numpy as np
from sklearn.metrics import roc_auc_score, average_precision_score
from scripts.study_case.ID_4.torch_geometric.utils import to_undirected
from ..inits import reset
EPS = 1e-15
MAX_LOG... | StarcoderdataPython |
1737134 | from typing import Any, List, Optional
from ...exceptions import InvalidEnvelopeExpressionError
class SchemaValidationError(Exception):
"""When serialization fail schema validation"""
def __init__(
self,
message: str,
validation_message: Optional[str] = None,
name: Optional[s... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.