id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
3247120 | """Module for generating reports on the results of input files.
.. important::
While this should work generally, autojob is currently tested on the
following types of code: FEFF 9.9.1, VASP 6.2.1, and the default CONFIG
assumes these code versions.
"""
from collections import Counter
from pathlib import ... | StarcoderdataPython |
11350062 | '''
Module to evaluate the fitness value of a scenario
'''
from pymoo.model.problem import Problem
class MyProblem(Problem):
def __init__(self, **kwargs):
super().__init__(
n_var=1, n_obj=1, n_constr=0, elementwise_evaluation=True, **kwargs
)
# self.pool = ThreadPool(8)
... | StarcoderdataPython |
1723849 | from simulation.visualization import Visualizer
import game_events.game_events as events
class TextualVisualizer(Visualizer):
def __init__(self):
pass
def visualize(self, event, params):
if isinstance(event, events.AbilityCastStarted):
self.visualize_ability_cast_started(params)
... | StarcoderdataPython |
3592540 | import enchant
from quasimodo.data_structures.submodule_interface import SubmoduleInterface
import logging
dirty_words = ["their", "so", "also"]
forbidden = ["used", "called", "xbox", "youtube", "xo", "quote",
"quotes", "minecraft", "important", "considered", "why",
"using", "as", "for", "a... | StarcoderdataPython |
9635204 | print('Ola mundo!!')
a = 10
| StarcoderdataPython |
11397623 | <gh_stars>0
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | StarcoderdataPython |
12844560 | <gh_stars>100-1000
from typing import Union, Callable, Iterable, Optional
from typing_extensions import Literal
from anndata import AnnData
from cellrank import logging as logg
from cellrank.ul._docs import d, inject_docs
from cellrank.tl._utils import _deprecate
from cellrank.tl.kernels import VelocityKernel, Connect... | StarcoderdataPython |
6456620 | <reponame>sireliah/polish-python
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer that turns <> into !=."""
# Local imports
z .. zaimportuj pytree
z ..pgen2 zaimportuj token
z .. zaimportuj fixer_base
klasa FixNe(fixer_base.BaseFix):
# This jest so sim... | StarcoderdataPython |
6703335 | <reponame>sanghyun-son/srwarp<filename>src/data/sr/benchmark/urban100.py
from os import path
from data.sr import base
class Urban100(base.SRBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def get_path(self) -> str:
return path.join(self.dpath, 'benchmark', 'urba... | StarcoderdataPython |
5100665 | <reponame>dy1zan/softwarecapstone
from .company import Company
| StarcoderdataPython |
1707995 | # coding: utf-8
#
# This code is part of qclib.
#
# Copyright (c) 2021, <NAME>
import os.path
import pickle
from collections.abc import MutableMapping
from typing import Iterable, Any
def cachekey(*args, **kwargs):
argstr = "; ".join(str(x) for x in args)
kwargstr = "; ".join(f"{k}={v}" for k, v in kwargs.it... | StarcoderdataPython |
12836341 | <filename>pitfall/utils.py
# Copyright 2019 Ali (@bincyber)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | StarcoderdataPython |
6463718 | # Stem module for Tensorflow. A stem is a structure that contains one or more
# substructures called subobjects. These subobjects may be classes that inherit from stem
# or from leaf. Note it is up to inheriting classes whether the subobjects are arranged
# in series, in parallel, or a combination.
#
# <NAME>
#-------... | StarcoderdataPython |
3360701 | <gh_stars>0
def get_form():
from .forms import CustomCommentForm
return CustomCommentForm | StarcoderdataPython |
6444473 | # Copyright (c) 2022 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 appli... | StarcoderdataPython |
8104911 | <gh_stars>1-10
import os
files = ['maya_modeling_v001.mb','maya_modeling_v002.mb','maya_modeling_v003.mb',
'head_model_v001.mb','head_model_v002.mb','head_model_v003.mb','head_model_v004.mb']
def create_file_list(files):
files_list = []
for file in files:
name , ext = os.path.splitext(file)
... | StarcoderdataPython |
3205175 | <reponame>jorisvandenbossche/DS-python-geospatial<gh_stars>10-100
# Make a Grey scale plot
gent_f.sum(dim="band").plot.imshow(cmap="Greys", figsize=(9, 5)) | StarcoderdataPython |
1806071 | import edgeiq
import pandas as pd
import os
import cv2
"""
Use pose estimation to determine human poses in realtime. Human Pose returns
a list of key points indicating joints that can be used for applications such
as activity recognition and augmented reality.
To change the engine and accelerator, follow this guide:
h... | StarcoderdataPython |
5093399 | #!/usr/bin/env python
#
# Author: <NAME> (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2008-2016 California Institute of Technology.
# Copyright (c) 2016-2021 The Uncertainty Quantification Foundation.
# License: 3-clause BSD. The full license text is available at:
# - https://github.com/uqfoundation/dill/blo... | StarcoderdataPython |
1960328 | <reponame>JCSDA/mpas-jedi<gh_stars>1-10
import datetime as dt
import os
import sys
import numpy
import numpy as np
from netCDF4 import Dataset # http://code.google.com/p/netcdf4-python/
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from copy import deepcopy
from datetime import datetime, timedelta
import ... | StarcoderdataPython |
6558338 | from node import Node
# Comment it before submitting
# class Node:
# def __init__(self, left=None, right=None, value=0):
# self.right = right
# self.left = left
# self.value = value
def insert(root, key):
if root is None:
root = Node(value=key)
return root
if key ... | StarcoderdataPython |
162376 | <filename>morpfw/authn/pas/user/typeinfo.py<gh_stars>1-10
from .model import UserCollection, UserModel
from .schema import UserSchema
from .path import get_user, get_user_collection
from ..app import App
@App.typeinfo(name='morpfw.pas.user',schema=UserSchema)
def get_typeinfo(request):
return {
'title': '... | StarcoderdataPython |
1612447 | from flask import json
from flaskapp.models import Paper
from test.main.base_classes import BaseMCQQuestion
from test.main.base_classes import BaseSubQuestion
from test.main.utils import test_post_request
class PaperGenerateRequest(BaseSubQuestion, BaseMCQQuestion):
def test_paper_generate_request(self):
... | StarcoderdataPython |
8090856 | """The module contains package wide custom exceptions and warnings.
"""
class NotProfiledError(ValueError, AttributeError):
"""Exception class to raise if profiling results are acquired before
calling `profile`.
This class inherits from both ValueError and AttributeError to help with
exception handl... | StarcoderdataPython |
6453670 | <reponame>keithfma/py_ice_cascade
from setuptools import setup
import py_ice_cascade as ic
setup(
name=ic.__name__,
version=ic.__version__,
description=ic._description,
url=ic._url,
author=ic._author,
author_email=ic._author_email,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Programming Language... | StarcoderdataPython |
11200516 | <filename>cli.py
"""
Inputs:
- predefined config
- GPU
# check with nvidia-smi first
# Run from within tmux
python cli.py run ./output/cli/ 1 wiki.bert_base__joint__seq512
python cli.py run ./output/cli/ 2 wiki.bert_base__joint__seq256
...
"""
import json
import logging
import os
import pickle
import sys
from im... | StarcoderdataPython |
3269332 | import mobula
@mobula.op.register
class AttSamplerGrid:
def __init__(self, scale=1.0, dense=4, iters=5):
self.scale = scale
self.dense = dense
self.iters = iters
def forward(self, data, attx, atty):#data[1, 1, 224, 224] attx[1, 224, 1]
F = self.F._mobula_hack
# attx:... | StarcoderdataPython |
172821 | <gh_stars>1-10
from tkinter import *
from tkinter import END
class SimpleInfoBox(Frame):
def __init__(self, master, row, column, background='#ADD8E6'):
Frame.__init__(self, master, background=background)
self.grid(row=row, column=column)
self.info = 'Loading Information'
self.info_t... | StarcoderdataPython |
9723347 | <reponame>hboshnak/python_toolbox
# Copyright 2009-2017 <NAME>.
# This program is distributed under the MIT license.
import sys
from python_toolbox.math_tools import binomial
def test():
assert binomial(7, 3) == 35
assert binomial(0, 0) == 1
assert binomial(1, 0) == 1
assert binomial(0, 1) == 0
... | StarcoderdataPython |
12806992 | #Escreva um programa que obtenha um nome de um arquivo texto do usuário e crie um processo para executar o programa do sistema Windows bloco de notas (notepad) para abrir o arquivo.
import subprocess,sys
def cria_arquivo():
nome = str(input("Digite o nome do arquivo:"))
file = open(f"{nome}.txt", "w")
fil... | StarcoderdataPython |
6518207 | <reponame>Srkline3/25-TkinterAndMQTT
"""
Using a Brickman (robot) as the receiver of messages.
"""
# Same as m2_fake_robot_as_mqtt_sender,
# but have the robot really do the action.
# Implement just FORWARD at speeds X and Y is enough.
import ev3dev.ev3 as ev3
import time
import math
class SimpleRoseBot(object):
... | StarcoderdataPython |
9638089 | <reponame>FreeDiscovery/jwzthreading<filename>setup.py
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from jwzthreading.jwzthreading import __version__
kw = {
'name': 'jwzthreading',
'version': __version__,
'description': 'Algorithm for threading mail messag... | StarcoderdataPython |
281914 | <reponame>wenhaopeter/read_pytorch_code<gh_stars>0
import torch.distributed.rpc as rpc
import torch.testing._internal.dist_utils
class RpcAgentTestFixture(object):
@property
def world_size(self):
return 4
@property
def init_method(self):
return torch.testing._internal.dist_utils.INIT_... | StarcoderdataPython |
89513 | <gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('geoinfo', '0006_auto_20160524_1954'),
]
operations = [
migrations.AlterField(
model_name='spatialrep... | StarcoderdataPython |
9727300 | <filename>AtCoder/ABC066/B/abc066_b.py<gh_stars>1-10
s = list(input())[0:-1]
t = 1
while s[0:len(s)//2] != s[len(s)//2:]:
s.pop()
t += 1
print(len("".join(s))) | StarcoderdataPython |
3527273 | # Copyright 2022, NVIDIA CORPORATION & AFFILIATES. 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 retain the above copyright
# notice, this list of con... | StarcoderdataPython |
4879018 | <reponame>kaka-lin/ML-Courses<gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
import math
def sign(x):
if x >= 0:
return 1
else:
return -1
def logistic(x):
return 1 / (1 + math.exp(-x))
def err01(x, y):
if sign(x) == y:
return 0
else:
return 1
def err1(x, y):
return max(0, 1 - y * x)
de... | StarcoderdataPython |
3300692 | from urllib import request
url = "http://quotes.toscrape.com/"
# 设置需要打开的链接
resp = request.urlopen(url)
# 使用请求函数打开链接
print(resp.read())
# 打印获取到的信息
| StarcoderdataPython |
4964393 | <reponame>jdavidagudelo/tensorflow-models
# Copyright 2018 The TensorFlow 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/L... | StarcoderdataPython |
3228254 | import cv2
from glob import glob
import numpy as np
import random
from sklearn.utils import shuffle
import pickle
import os
def pickle_images_labels():
images_labels = []
images = glob("gestures/*/*.jpg")
images.sort()
for image in images:
print(image)
label = image[image.find(os.sep)+1: image.rfind(os.sep)]
... | StarcoderdataPython |
5172781 | # -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class GlacierRetrievalTypeEnum(object):
"""Implementation of the 'GlacierRetrievalType' enum.
Specifies the way data needs to be retrieved from the external target.
This information will be filled in by Iris and Magneto will pass it along
to the ... | StarcoderdataPython |
4863530 | import os
import sys
import logging
import inspect
import fossor
from fossor.engine import Fossor
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
log = logging.getLogger(__name__)
def test_no_popen_usage():
f = Fossor()
for plugin in f.list_plugins():
for line in inspect.getsourcelines(p... | StarcoderdataPython |
8048712 | import torch.nn as nn
from .dropout import LockedDropout
class Embedding(nn.Embedding):
def __init__(self, num_embeddings, embedding_dim, dropoute=.0, dropout=.0, **kwargs):
super(Embedding, self).__init__(num_embeddings, embedding_dim, **kwargs)
self.dropoute = dropoute
self.drop = Locke... | StarcoderdataPython |
3320544 | from pynwb import TimeSeries
import numpy as np
from bisect import bisect, bisect_left
def get_timeseries_tt(node: TimeSeries, istart=0, istop=None) -> np.ndarray:
"""
For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be
generated.
Parameters
... | StarcoderdataPython |
11332624 | <reponame>drewtray/spotify_net<gh_stars>0
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_retrieve_last.ipynb (unless otherwise specified).
__all__ = ['last_cred', 'last_get', 'last_format']
# Cell
import pandas as pd
import requests
import boto3
import json
# Cell
def last_cred():
secret_name = "last_keys"
... | StarcoderdataPython |
3288053 | <filename>mmgen/core/scheduler/lr_updater.py<gh_stars>1-10
from mmcv.runner import HOOKS, LrUpdaterHook
@HOOKS.register_module()
class LinearLrUpdaterHook(LrUpdaterHook):
"""Linear learning rate scheduler for image generation.
In the beginning, the learning rate is 'base_lr' defined in mmcv.
We give a ta... | StarcoderdataPython |
17354 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .application import *
from .application_... | StarcoderdataPython |
1731116 | <reponame>pervcomp/Procem
# -*- coding: utf-8 -*-
"""Module for handling electricity SPOT price data from Nord Pool."""
# Copyright (c) TUT Tampere University of Technology 2015-2018.
# This software has been developed in Procem-project funded by Business Finland.
# This code is licensed under the MIT license.
# See t... | StarcoderdataPython |
8023548 | <reponame>c-yan/atcoder<filename>abc/abc186/abc186d.py<gh_stars>1-10
N, *A = map(int, open(0).read().split())
A.sort()
s = sum(A)
result = 0
for i in range(N):
a = A[i]
s -= a
result += s - a * (N - i - 1)
print(result)
| StarcoderdataPython |
3338183 | import itertools
from datetime import timedelta
from unittest.mock import Mock
from pfun import schedule, success
two_seconds = timedelta(seconds=2)
def test_spaced():
deltas = schedule.spaced(two_seconds).run(None)
assert list(itertools.islice(deltas, 3)) == [two_seconds] * 3
def test_exponential():
... | StarcoderdataPython |
3434299 | def test_logger():
import tempfile
from tblogging import TBLogger
with tempfile.TemporaryDirectory() as logdir:
logger = TBLogger(logdir, "test")
logger.register_scalar("mean", "scalar")
logger.freeze()
logger.log(1, {"mean": 0.0})
logger.close()
| StarcoderdataPython |
3393366 | import itertools
__author__ = 'danny'
#Human helper - cheats
NO_JUMP = -1
class Cpu(object):
def __init__(self, memory, pc):
"""Memory should be an array. Which is writable/readable is up to implementation.
pc should be an offset into that memory. Memory word size, a, b and pc should be the same.... | StarcoderdataPython |
3553302 | <reponame>JoshPattman/Spot-Puppy-Lib<filename>spotpuppy/rotation/mpu6050_rotation_sensor.py
from math import atan, sqrt, pow, radians, degrees
from . import rotation_sensor_base
IS_IMPORTED=False
class sensor(rotation_sensor_base.sensor):
def __init__(self, inverse_x=False, inverse_z=False, accelerometer_bias=0.0... | StarcoderdataPython |
313710 | from __future__ import annotations
import abc
import string
from typing import TypeVar
class _EndStringFormatter(string.Formatter):
""" Custom string formatter to not throw errors when args or kwargs are missing."""
def get_value(self, key, args, kwargs):
if isinstance(key, int):
if len... | StarcoderdataPython |
11251505 | <reponame>dntoll/loraMesh
from simulator.FakePycomInterface import FakePycomInterface
from simulator.Radio import Radio
from simulator.SimTestView import SimTestView
from view.CompositeView import CompositeView
from simulator.SimulatorSocket import SimulatorSocket
from meshlibrary.PymeshAdapter import PymeshAdapter
fr... | StarcoderdataPython |
9765893 | <reponame>tomichec/covid-cz-regions
import json
def main():
dates = ["2020-03-25@21-45",
"2020-03-26@12-45",
"2020-03-26@18-04",
"2020-03-27@09-49",
"2020-03-27@18-09",
"2020-03-28@09-44",
"2020-03-29@18-28",
"2020-0... | StarcoderdataPython |
4878743 | import ast
import logging
from .environment import Robot
import numpy as np
import itertools
import matplotlib
import matplotlib.style
import pandas as pd
import sys
from collections import defaultdict
from . import plotting_r as plotting
import json
matplotlib.style.use('ggplot')
SPEED = 0.7
logging.basicConfig(filen... | StarcoderdataPython |
6524767 | <gh_stars>1-10
from unittest import TestCase
from .helpers.parser import ParserTesterMixin
from jaqalpaq.parser.extract_let import extract_let
from jaqalpaq.parser.tree import make_lark_parser
from jaqalpaq.parser.identifier import Identifier
class ExtractLetTester(ParserTesterMixin, TestCase):
def test_extract_... | StarcoderdataPython |
4915943 |
import re
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open("jsview/__init__.py") as fh:
version = re.search(r'^__version__\s*=\s*"(.*)"', fh.read(), re.M).group(1)
setuptools.setup(
name="jsview",
version=version,
author="<NAME>",
author_email="<EMA... | StarcoderdataPython |
95496 | <reponame>zhongtianxie/fm-orchestrator
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import absolute_import
from mock import patch, PropertyMock
import pytest
from module_build_service.common import models
from module_build_service.common.modulemd import Modulemd
from module_build_service.com... | StarcoderdataPython |
9706738 | """Simple periodic timer"""
from threading import Timer
from typing import Callable, Optional
class PeriodicTimer:
"""Simple periodic timer"""
# Note: callback is not optional but mypy has a bug:
# https://github.com/python/mypy/issues/708
_callback: Optional[Callable[[], None]]
_period: float
... | StarcoderdataPython |
3227449 | <filename>src/atcoder/abc226/a/sol_0.py
import typing
def main() -> typing.NoReturn:
a, b = input().split('.')
print(int(a) + (int(b[0]) >= 5))
main() | StarcoderdataPython |
8103473 | <reponame>joeyzhou85/python<gh_stars>1000+
"""
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
Example:"abc", "abg" are subsequences of "abcdefgh".
"""
from __... | StarcoderdataPython |
8041458 | begin_unit
comment|'# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. Y... | StarcoderdataPython |
9685754 | import unittest
import os
import time
from flow.core.experiment import Experiment
from flow.core.params import VehicleParams
from flow.controllers import IDMController, RLController, ContinuousRouter
from flow.core.params import SumoCarFollowingParams
from flow.core.params import SumoParams
from flow.core.params impor... | StarcoderdataPython |
11242155 | <filename>tests/test_list.py
from django.test import TestCase
from rest_assured.testcases import ListAPITestCaseMixin
from tests import mocks
class TestListTestCase(TestCase):
def get_case(self, **kwargs):
class MockListTestCase(ListAPITestCaseMixin, mocks.MockTestCase):
base_name = 'stuff'
... | StarcoderdataPython |
6657368 | # ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... | StarcoderdataPython |
8072497 | <gh_stars>1-10
# adata scripts/mqtt_subscription
'''
Simple example MQTT
'''
from adata import echo, Module
from adata.mqtt import Broker
class Define(Module):
name = "mqtt_channels"
menu = "Service"
def task(self):
broker = ScanTopics("test.mosquitto.org", 1883)
broker.app = self.... | StarcoderdataPython |
5158267 | <gh_stars>1-10
# Copyright 2017 Intel Corporation
#
# 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 a... | StarcoderdataPython |
8114430 | from json import JSONDecodeError
from pathlib import Path
from bx_py_utils.test_utils.assertion import assert_equal
from bx_py_utils.test_utils.snapshot import assert_snapshot
def build_requests_mock_history(mock, only_json=True):
history = []
for request in mock.request_history:
request_info = {
... | StarcoderdataPython |
6443645 | from pyspark.sql import SparkSession
from pyspark.sql import functions as func
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatType
# creates a SparkSession
spark = SparkSession.builder.appName("MinTemperatures").getOrCreate()
# we are determining the Schema of the Table
schema = ... | StarcoderdataPython |
291218 | <gh_stars>10-100
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import copy
import decimal
import json
import os
import uuid
import boto3
import math
import urllib3
from decimal import Decimal
from datetime import datetime
from boto3.dynamodb.condition... | StarcoderdataPython |
1665125 | import numpy as np
from astropy import wcs
def makeGaussian(size, fwhm=3, center=None):
x = np.arange(0, size, 1, float)
y = x[:,np.newaxis]
if center is None:
x0 = y0 = size // 2
else:
x0 = center[0]
y0 = center[1]
return np.exp(-4*np.log(2)*((x-x0)**2 + (y-y0)**2)/fwhm**2... | StarcoderdataPython |
154963 | import unittest
import models.EndNode as n
class TestEndNode(unittest.TestCase):
def setUp(self):
self.a = n.EndNode('192.168.0.1', id = 1)
self.b = n.EndNode('192.168.0.1')
self.c = n.EndNode('192.168.0.3')
def testEquality(self):
self.assertTrue(self.a == self.a)
self... | StarcoderdataPython |
1613765 | <filename>src/reader.py
import collections
import numpy as np
import re
class TextProcessor(object):
@staticmethod
def from_file(input_file):
with open(input_file, 'r', encoding = 'utf8') as fh:
text = fh.read()
return TextProcessor(text)
def __init__(self, text):
# se... | StarcoderdataPython |
3376239 | from multiprocessing import Pipe
# 双工
conn1, conn2 = Pipe()
conn1.send('conn1第1次发送的数据')
conn1.send('conn1第2次发送的数据')
conn2.send('conn2第1次发送的数据')
conn2.send('conn2第2次发送的数据')
print(conn1.recv())
print(conn1.recv())
print(conn2.recv())
print(conn2.recv())
# 单工
c1, c2 = Pipe(False)
c2.send('c2发送的数据')
print(c1.recv()... | StarcoderdataPython |
3387708 | <filename>csc work/misc/w5/r/collatz.py
def count_collatz_steps(n):
''' (int) -> int
Return the number of steps it takes to reach 1, by repeating the two steps
of the Collatz conjecture beginning from n.
>>> count_collatz_steps(6)
8
'''
count = 0
while n > 1:
if n ... | StarcoderdataPython |
134732 | import toolz
import toolz.curried
from toolz.curried import (take, first, second, sorted, merge_with, reduce,
merge, operator as cop)
from collections import defaultdict
from importlib import import_module
from operator import add
def test_take():
assert list(take(2)([1, 2, 3])) == [1, ... | StarcoderdataPython |
395664 | from codecs import open
import toml
from setuptools import find_packages, setup
with open("README.rst") as f:
readme = f.read()
project = toml.load("pyproject.toml")["mewo_project"]
setup(
name="sty",
version=project["version"],
author="<NAME>",
author_email="<EMAIL>",
maintainer="<NAME>",... | StarcoderdataPython |
12848471 | """
A PyTorch implmentation of the KL-Divergence Loss as described in (https://arxiv.org/abs/1511.06321)
Lua Implementation (not inspected yet TODO) (https://github.com/yenchanghsu/NNclustering/blob/master/BatchKLDivCriterion.lua)
"""
import torch
import torch.nn.functional as F
from torch import nn
import numpy as ... | StarcoderdataPython |
3538375 | <reponame>helderthh/leetcode<filename>medium/merge-intervals.py
# 56. Merge Intervals
# https://leetcode.com/problems/merge-intervals/
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
res = [] # list of final intervals
# for each interval
for interv... | StarcoderdataPython |
11219614 | <filename>practice/filecompross/rarunrar/unrarfiles.py
# -*- coding:utf-8 -*-
"""
安装解压rar文件的插件: pip install unrar
注意: 这个插件需要rarlib的支持.
安装rarlib:
https://www.rarlab.com/rar_add.htm 下载UnRARDLL.exe并安装,然后添加到环境变量中即可.
"""
# 说明:
# 如果不安装UnRARDLL.exe,运行python脚本会报:LookupError: Couldn't find path to unrar library.错误.... | StarcoderdataPython |
5142252 | <gh_stars>0
def sub_gen1(x):
r = yield x
print('subgen1', r)
def gen1(x):
r = yield sub_gen1(x)
print('gen1', r)
g = gen1(3)
g.send(None)
g.send(21)
# g = gen1(3)
# g
# <generator object gen1 at 0x10f9ce450>
# g.send(None)
# <generator object sub_gen1 at 0x10f9ce3d0>
# g.send(21)
# gen1 21
# Trace... | StarcoderdataPython |
6501311 | <reponame>nutanixdev/calm-dsl
from calm.dsl.decompile.render import render_template
from calm.dsl.decompile.task import render_task_template
from calm.dsl.decompile.parallel_task import render_parallel_task_template
from calm.dsl.decompile.variable import render_variable_template
from calm.dsl.builtins import action, A... | StarcoderdataPython |
8060264 | import sys
import pygame
from pygame.locals import *
# init pygame
pygame.init()
DISPLAYSURFACE = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Hello World')
# color constants
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# create text
fontObj = pygame.font.Font('freesansbo... | StarcoderdataPython |
9653711 | # Copyright © 2019 Province of British Columbia
#
# 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 agr... | StarcoderdataPython |
9614165 | <filename>countries/management/commands/_base.py
from pathlib import Path
from django.core import serializers
from django.core.management.base import BaseCommand
__all__ = ['DumperBaseCommand']
class TextIOWrapper(object):
def __init__(self, path, mode, format, is_fake=False):
self.format = format
... | StarcoderdataPython |
41965 | <gh_stars>0
'''
AUTOR: <NAME>
Date: 08/10/2020
WilliamHillURLs class to managed info about William Hill web pages.
'''
import requests
from bs4 import BeautifulSoup
from urlvalidator import validate_url, ValidationError
class WilliamHillURLs:
"""Auxiliar class with data about William Hill Web to ... | StarcoderdataPython |
9751507 | from pathlib import Path
import os, sys
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
# this size is required for embedding
FACE_PIC_SIZE = 160
EMBEDDING_SIZE = 512
#PRETREINED_MODEL_DIR = os.path.join(str(Path.home()), 'pretrained_models')
PRETREINED_MODEL_DIR = "/workspace/pret... | StarcoderdataPython |
9705298 | <reponame>czbiohub/special_ops_crispr_tools
#!/usr/bin/env python3
import sys
if sys.version_info < (3,5):
print("This script requires Python >= 3.5.")
print("Current Python version is {}.".format(sys.version.split()[0]))
sys.exit(-1)
import subprocess, traceback, time, requests
from requests.exceptions ... | StarcoderdataPython |
1778825 | # coding: utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import numpy as np
class Model(nn.Module):
def __init__(self, args):
super(Model, self).__init__()
if args['embedding_pretrained'] is not None... | StarcoderdataPython |
43060 | import os
import csv
import subprocess
import matplotlib.pyplot as plt
from math import ceil
from tqdm import tqdm
from pandas import read_csv
from netCDF4 import Dataset, num2date
from multiprocessing import cpu_count, Process
from .plot import plot_filtered_profiles_data
def download_data(files, storage_path):
... | StarcoderdataPython |
9620605 | from django.core.context_processors import csrf
from django.db.utils import IntegrityError
from django.shortcuts import render_to_response
from django.template import RequestContext
from TwRestApiPlaces.models import *
def test(request):
test_place = None
try:
test_place = Place.objects.create(name = '... | StarcoderdataPython |
12840407 | <reponame>yyang08/swagger-spec-compatibility
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from copy import deepcopy
import mock
import pytest
from swagger_spec_compatibility.spec_utils import load_spec_from_spec_dict
from... | StarcoderdataPython |
133818 | <reponame>CircleLiu/DataWarehouse
import redis
import re
import csv
from itertools import islice
redis_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)
redis_conn = redis.StrictRedis(connection_pool=redis_pool)
def cache():
total_lines = 7911684 * 9
with open('./movies.txt', 'r', errors='ignor... | StarcoderdataPython |
3485809 | <filename>FastEMRIWaveforms/few/amplitude/interp2dcubicspline.py
# Schwarzschild Eccentric amplitude module for Fast EMRI Waveforms
# performed with bicubic splines
# Copyright (C) 2020 <NAME>, <NAME>, <NAME>, <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | StarcoderdataPython |
225866 | import os
import sys
from io import StringIO
from autouri import AutoURI
from caper.cromwell import Cromwell
from caper.cromwell_metadata import CromwellMetadata
from .example_wdl import make_directory_with_failing_wdls, make_directory_with_wdls
def test_on_successful_workflow(tmp_path, cromwell, womtool):
fil... | StarcoderdataPython |
4957466 |
import argparse
import pdb
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""Program description""")
parser.add_argument(
"--input",
required=True,
help="""The input BED file"""
)
parser.add_argument(
... | StarcoderdataPython |
8109747 | <reponame>hsm207/sage
"""
SAT Functions for Boolean Polynomials
These highlevel functions support solving and learning from Boolean polynomial systems. In this
context, "learning" means the construction of new polynomials in the ideal spanned by the original
polynomials.
AUTHOR:
- <NAME> (2012): initial version
Fun... | StarcoderdataPython |
3469020 | """Set version helper
"""
#!/usr/bin/env python
import argparse
import semantic_version
from utils_file import FileContext
from utils_iotedge import get_modules
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('type', choices=['patch', 'minor', 'major', 'set'], help="Update... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.