id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3257051 | <gh_stars>1000+
from anchore_engine.subsys import logger
logger.enable_test_logging()
def test_sync_fail(test_data_env, run_legacy_sync_for_feeds):
# No such feed
result = run_legacy_sync_for_feeds(["nvd"])
assert len(result) == 0
result = run_legacy_sync_for_feeds(["vulnerabilities", "packages", "n... | StarcoderdataPython |
3211631 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
implement random proxy / random user agent
Copyright (C) <NAME> 2018-2019
Copyright (C) Allen (<NAME>) Xie 2019
stocksight is released under the Apache 2.0 license. See
LICENSE for the full license text.
"""
#https://github.com/hellysmile/fake-useragent implement r... | StarcoderdataPython |
3243115 | <reponame>MotiMatika/self-py
def M_1():
items=input("please type what do you want to buy: ")
splittedItems=items.split(',')
print("your items are : ",splittedItems)
M_1() | StarcoderdataPython |
3233791 | import copy
import warnings
from collections import OrderedDict
import pytest
from tri_struct import Struct
from tri_declarative import (
EMPTY,
LAST,
Namespace,
Refinable,
RefinableObject,
Shortcut,
assert_kwargs_empty,
class_shortcut,
dispatch,
flatten,
full_function_name... | StarcoderdataPython |
1762045 | <filename>src/onegov/election_day/views/election/statistics.py
from onegov.ballot import Election
from onegov.core.security import Public
from onegov.election_day import ElectionDayApp
from onegov.election_day.layouts import ElectionLayout
@ElectionDayApp.html(
model=Election,
name='statistics',
template=... | StarcoderdataPython |
4817418 | from copy import deepcopy
from datetime import datetime
import click
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None
DEFAULT_ANDROMONEY_FILENAME = "AndroMoney - AndroMoney.csv"
DEFAULT_MOZE_FILENAME = "MOZE.csv"
MOZE_HEADER = [
# Required
"帳戶",
"幣別",
# Required
... | StarcoderdataPython |
1657891 | <reponame>kevinychen/nikoli-puzzle-solver
from solvers.utils import *
class MinesweeperSolver(AbstractSolver):
def __init__(self, pzprv3):
matched = match('pzprv3/mines/(\\d+)/(\\d+)/(.*)/', pzprv3)
self.height = int(matched.group(1))
self.width = int(matched.group(2))
self.grid =... | StarcoderdataPython |
92448 | <reponame>shawnduong/manimations
def functionName(p_1, p_2, p_3, ..., p_n):
Instructions...
return o_1, o_2, o_3, ..., o_m
v_1, v_2, v_3, ..., v_m = functionName(i_1, i_2, i_3, i_n)
| StarcoderdataPython |
1697593 | <gh_stars>10-100
import torch
import torch.nn as nn
import torchvision
def Conv1(in_planes, places, stride=2):
return nn.Sequential(
nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
... | StarcoderdataPython |
4156 | import os, sys
class Object:
## @name constructor
def __init__(self, V):
self.value = V
self.nest = []
def box(self, that):
if isinstance(that, Object): return that
if isinstance(that, str): return S(that)
raise TypeError(['box', type(that), that])
## @name d... | StarcoderdataPython |
3345651 | <reponame>trodge/declarative-resource-client-library
# Copyright 2021 Google LLC. 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... | StarcoderdataPython |
91073 | #!/usr/bin/env python
# coding: utf-8
# # Import Base Packages
# In[ ]:
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
# # Interface function to feature engineering data
# In[ ]:
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import Standard... | StarcoderdataPython |
3261698 | <gh_stars>0
'''
Given a string containing digits from 2-9 inclusive,
return all possible letter combinations
that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons)
is given below. Note that 1 does not map to any letters.
'''
class Solution:... | StarcoderdataPython |
1710365 | nome = str(input('Digite um nome: ')).strip()
print('Maiúsculas:', nome.upper())
print('Minúsculas:', nome.lower())
dividido = nome.split()
print('A quantidade de letras ao todo é:', len(nome) - nome.count(' '))
print('A quantidade de letras do primeiro nome é: ', len(dividido[0]))
| StarcoderdataPython |
1738786 | # proxy module
from __future__ import absolute_import
from codetools.execution.demo.expression_context_demo import *
| StarcoderdataPython |
4822695 | #!/usr/bin/env python3
import collections
from collections import namedtuple
from datetime import datetime
import os
import re
import sys
from pathlib import Path
import jinja2
VersionRange = namedtuple('VersionRange', 'min max')
class SupportPackage(object):
def __init__(self,
module_version,
... | StarcoderdataPython |
1754492 | <filename>rllib/policy/q_function_policy/epsilon_greedy.py
"""Epsilon Greedy Policy."""
import torch
from rllib.util.neural_networks import get_batch_size
from .abstract_q_function_policy import AbstractQFunctionPolicy
class EpsGreedy(AbstractQFunctionPolicy):
"""Implementation of Epsilon Greedy Policy.
A... | StarcoderdataPython |
182823 | <reponame>makelove/OpenCV-Python-Tutorial<filename>ch23-图像变换/23.1.4 为什么拉普拉斯算子是高通滤波器.py
# -*- coding: utf-8 -*-
# @Time : 2017/7/13 上午11:18
# @Author : play4fun
# @File : 23.1.4 为什么拉普拉斯算子是高通滤波器.py
# @Software: PyCharm
"""
23.1.4 为什么拉普拉斯算子是高通滤波器.py:
从图像中我们就可以看出每一个算子允 些信号。从 些信息中我 们就可以知 些是 HPF 是 LPF
"""
impor... | StarcoderdataPython |
1762486 | <reponame>ariahahn/MetaPathways_Python.3.0
#!/usr/bin/python -w
import socket, re, sys
from os import _exit
import re
from libs.python_modules.utils.sysutil import getstatusoutput
from multiprocessing import Process
import time
class PythonCyc:
_organism = 'meta'
soc = None
def... | StarcoderdataPython |
1780888 | <filename>config/common/sim/ode_solver.py<gh_stars>1000+
# Copyright 2020 Makani Technologies 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/LICEN... | StarcoderdataPython |
162536 | <reponame>arthtyagi/gettit
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
class Todo(models.Model):
title = models.CharField(max_length=30)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content= models.CharField(max_length=450,blank=True)
created... | StarcoderdataPython |
199006 | import requests
from bs4 import BeautifulSoup
import fnmatch
def get_wsa_entry():
"""Returns a tuple containing the Windows Subsystem for Android link and its file name (used to check for
updates) """
store_id = "9p3395vx91nr"
api_url = "https://store.rg-adguard.net/api/GetFiles"
data = {
... | StarcoderdataPython |
3344904 | import torch
import torch.nn as nn
from torch.nn import Conv3d, ConvTranspose3d, BatchNorm3d, MaxPool3d, AvgPool1d, Dropout3d
from torch.nn import ReLU, Sigmoid
#############
# UTILS #
#############
def print_model(model):
"""
Print model and parameters per layer to debug.
@param model: torch.model
... | StarcoderdataPython |
41366 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class EntityBasicInfo(object):
def __init__(self):
self._address_desc = None
self._category_code = None
self._city = None
self._contact_number = None
self._entit... | StarcoderdataPython |
1768949 | <reponame>jdschleicher/CumulusCI
import json
import unittest
from unittest import mock
import responses
import yaml
from tempfile import TemporaryDirectory
from pathlib import Path
import pytest
from cumulusci.tasks.bulkdata import GenerateMapping
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.... | StarcoderdataPython |
41336 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from typing import List
from itertools import product
def sum_of_square_mod_m( nums:tuple, mod_m ):
return ( sum( map( lambda x: x**2, nums) ) % mod_m )
def maximize_function_value( list_of_list:List , mod_m):
count_of_list = len( list_... | StarcoderdataPython |
34734 | from django.urls import path, include
from .views import CompanyAPIView
# urlpatterns = [
# path("",include(router.urls)),
# ] | StarcoderdataPython |
3381431 | import json
import logging
import ntpath
import os
import random
import re
import string
import traceback
from io import StringIO
from urllib.parse import urljoin
from django import template
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.... | StarcoderdataPython |
3316031 | """
Copyright (c) 2021, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
from argparse import Namespace
import logging
import torch
import json
import numpy
import math
from... | StarcoderdataPython |
4840893 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 01 16:19:44 2015
@author: <NAME>
"""
import os.path
import sys, StringIO
import antimony
import roadrunner
import tellurium as te
import zipfile
import tempfile
import re
try:
import phrasedml
except ImportError as e:
roadrunner.Logger.log(roadrunner.Logger.LOG_W... | StarcoderdataPython |
4834149 | from mako.template import Template
import os
import importlib.resources as resources
def genRobotCode(projectType, config):
if projectType == "Simple":
with resources.path(__name__, "templates") as path:
with open(os.path.join(path, "Simple", "Robot.java.mako"), "r") as template:
... | StarcoderdataPython |
1671686 | import os
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Font
# mapping from index to letter
letters = [
"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"
]
# needed information about excel workbook... | StarcoderdataPython |
792 | <filename>tensorflow/contrib/data/python/kernel_tests/optimization/map_and_filter_fusion_test.py
# 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... | StarcoderdataPython |
3254969 | #!/usr/bin/env python
from kubernetes.client.rest import ApiException
from kubernetes import client, config
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.CoreV1Api()
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
namespa... | StarcoderdataPython |
3366398 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 15:27:51 2019
@author: teja
"""
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
self.tail = None
self.len = 0
def push(... | StarcoderdataPython |
1686659 | <reponame>phyuthinzarmg/python-exercises
class Scene(object):
2
3 def enter(self):
4 pass
5
6
7 class Engine(object):
8
9 def __init__(self, scene_map):
10 pass
11
12 def play(self):
13 pass
14
15 class Death(Scene):
16
17 def enter(self):
18 pass
19
20 class CentralCorridor(Scene):
21
22 def enter(self):
23 pass
24
25... | StarcoderdataPython |
84439 | # encoding: utf-8
import json
import yaml
import click
import googleanalytics as ga
from googleanalytics import utils
from .common import cli
# TODO: the blueprint stuff can probably be simplified so that
# it's little more than just a call to ga.describe
def from_blueprint(scope, src):
description = yaml.load(... | StarcoderdataPython |
3395662 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
# This script opens an existing model in onnx format and attempts to
# mo... | StarcoderdataPython |
3225567 | from discord import Guild
from discord.errors import NotFound
from contextlib import suppress
from src.utils import channel_to_dict, member_to_dict, role_to_dict, user_to_dict, guild_to_dict
class Pools:
def __init__(self, bot):
self.nonexistant = []
self.bot = bot
async def get_all_emoji(s... | StarcoderdataPython |
3362773 | <gh_stars>0
""" ExtendedUser class file """
class ExtendedUser:
""" Extends user with more capacities: redirects attr to user """
def __init__(self, user, messenger, dispatcher, database):
self.user = user
self.messenger = messenger
self.dispatcher = dispatcher
self.database = ... | StarcoderdataPython |
3284692 | import inspect
from enum import Enum
from typing import Any, Type, TypeVar, Union
T = TypeVar("T")
_PRIMITIVES = (bool, int, float, str, type(None))
class Null:
"""Null marker"""
class ObjectMapper:
@staticmethod
def tree_to_object(tree: object, annotation: Type[T]) -> T:
"""Loads JSON-like str... | StarcoderdataPython |
1792860 | <reponame>rembish/f<filename>fit/messages/__init__.py<gh_stars>1-10
from re import match
from fit.record import TIMESTAMP_FIELD_NUM, TIMESTAMP_MASK, \
TIMESTAMP_FIELD_NAME
from fit.record.fields import Fields
from fit.types import Type
from fit.types.array import Array
from fit.types.dynamic import Dynamic
from fi... | StarcoderdataPython |
131092 |
# Code from Chapter 16 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by <NAME> (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no warranty... | StarcoderdataPython |
3295563 | <reponame>kvetab/bio_embeddings
from bio_embeddings.extract.light_attention.light_attention_annotation_extractor import (
LightAttentionAnnotationExtractor,
)
from bio_embeddings.extract.light_attention.light_attention_model import LightAttention
__all__ = ["LightAttentionAnnotationExtractor", "LightAttention"]
| StarcoderdataPython |
143606 | <gh_stars>0
# run the facial keypoints classes to train a neural network
# rupert small, august 2015
#
from numpy import *
from fk_class_definitions import *
# initialise
data = genfromtxt('training.csv',delimiter=',')
y_vals = data[:,0:30]/96.0
x_vals = data[:,30:]/255.0
inlayer = shape(x_vals)[1]
outlayer = shape(... | StarcoderdataPython |
1655396 | <gh_stars>0
import pyglet
import numpy as np
import matplotlib.pyplot as plt
import pickle
import time
from libs.game_rules import TITLE, SIZE, LOW, HM_EPISODES, EPS_DECAY, BLACK_ARC_DIAMETER, RED_ARC_DIAMETER, EPSILON, MAX_MOVE, VELOCITY, PENALTY, MOVE_PENALTY, REWARD, LEARNING_RATE, DISCOUNT, MAX_POS, ACTION_SPACE
fr... | StarcoderdataPython |
3392851 | <gh_stars>0
# -*- coding: utf-8 -*-
from flask import make_response
from application import exception
from application.model.legacy.model import User, UserRole, Role
from application.util import permission
from application.util.database import session_scope
from application.views.base_api import BaseNeedLoginAPI, ApiR... | StarcoderdataPython |
174765 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import scipy.ndimage
from config import config
class FlawDetector(nn.Module):
""" The FC Discriminator proposed in paper:
'Guided Collaborative Training for Pixel-wise Semi-Supervised Learning'
"""
n... | StarcoderdataPython |
3337359 | """
Title: MCNP_Dataset.py
Author: <NAME>
"""
# ---------------------------------------------------------------------------- #
# Module Imports #
# ---------------------------------------------------------------------------- #
import sys
import num... | StarcoderdataPython |
3245704 | <filename>nunchuck.py<gh_stars>0
##########################################
## Python module to read a Wii nunchuck ##
## ##
## Written by Jason - @Boeeerb ##
## <EMAIL> ##
##########################################
##
## v0.1 03/05/14 - Initital release
#... | StarcoderdataPython |
1668923 | from .pywrapfst import * # noqa
__version__ = '0.1.0' | StarcoderdataPython |
3328474 | <filename>majority_judgment/urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from majority_judgment import views
urlpatterns = [
path(r'charts/results-<int:election_id>.png', views.chart_results, name='results'),
]
| StarcoderdataPython |
182091 | import unittest
import os
import datetime as dt
import netCDF4
import numpy as np
from forest import (eida50, satellite, navigate)
from forest.exceptions import FileNotFound, IndexNotFound
class TestLocator(unittest.TestCase):
def setUp(self):
self.paths = []
self.pattern = "test-eida50*.nc"
... | StarcoderdataPython |
1662589 | # Copyright © 2020 IBM
#
# 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, softwa... | StarcoderdataPython |
161490 | <reponame>waynewu6250/ChatBoxer<gh_stars>1-10
# Generated by Django 2.1.7 on 2019-03-27 02:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dialogue', '0002_auto_20190327_0251'),
]
operations = [
migrations.AddField(
model... | StarcoderdataPython |
3329314 | # -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TaxReportTest(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_tem... | StarcoderdataPython |
3328927 | #!/usr/bin/python3
# slice
# 1.
a = 'hello world'
b = a[0]
c = a[10]
print(b, c) # h d
# 2.
b = a[-1]
c = a[-2]
d = a[-3]
print(b, c, d) # d l r
# 3.
b = a[0:3]
c = a[1:3]
print(b, c) # hel el
# 4.
b = a[:2]
c = a[1:]
d = a[:]
print(b) # he
print(c) # ello world
print(d) # hello world
... | StarcoderdataPython |
1666723 | import itertools
import argparse
import gym
from gym.spaces import Discrete
class Env(gym.Env):
def __init__(self, num_states):
super().__init__()
self.iterator = None
self.num_states = num_states
self.observation_space = Discrete(num_states)
self.action_space = Discrete(2... | StarcoderdataPython |
1673496 | <reponame>Lowess/CrowdTruth-core
from setuptools import setup, find_packages
# import os
# import sys
setup(
name='crowdtruth-fork',
version='2.1.1',
description=
"Disagreement based metrics for the processing and evaluation of crowdsourced annotations",
long_description=
("CrowdTruth is an app... | StarcoderdataPython |
1634647 | #!/usr/bin/env python
"""
_File_t_
Unit tests for the WMBS File class.
"""
import logging
import threading
import unittest
from Utils.PythonVersion import PY3
from WMCore.DAOFactory import DAOFactory
from WMCore.DataStructs.File import File as WMFile
from WMCore.DataStructs.Run import Run
from WMCore.WMBS.File impo... | StarcoderdataPython |
180476 | #coding:utf-8
#把wikititle
import os
import sys, getopt
reload(sys)
sys.setdefaultencoding('utf-8')
maxLength = 10000
def is_chinese(uchar):
"""判断一个unicode是否是汉字"""
if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
return True
else:
return False
#这个脚本将读取wikiTitle
#每一行:先分掉' ' 再做strip
#再取全是汉字的... | StarcoderdataPython |
196518 | <gh_stars>1-10
# Licensed under a MIT licence - see file `license`
import numpy as np
from scipy.stats import multivariate_normal
import pytest
@pytest.fixture()
def example3_3():
image = np.ma.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]],
... | StarcoderdataPython |
164516 | <filename>scripts/make_logo_from_msa.py
#!/usr/bin/env python3
import sys
from pathlib import Path
path_root = Path(__file__).parents[1]
sys.path.append(str(path_root))
import argparse
from monomer_aligner import make_logo
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('fasta', t... | StarcoderdataPython |
3230965 | <reponame>heston/firebase-live-data<gh_stars>1-10
import os.path
import logging
import sys
# Add the module path
module_path = os.path.abspath(os.path.join(
os.path.dirname(__file__),
'..'
))
sys.path.insert(0, module_path)
logging.basicConfig(
format='[%(asctime)s] %(levelname)s %(name)s: %(message)s',
... | StarcoderdataPython |
1792051 | DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root@localhost/deeplab'
SQLALCHEMY_TRACK_MODIFICATIONS = True
SEND_FILE_MAX_AGE_DEFAULT = 0
TOKEN_SECRET = 'secret'
REGISTER_SECRET_CODE = 'uuu'
url = 'http://localhost:5000'
UPLOAD_FOLDER = './app/templates/img/upload' | StarcoderdataPython |
111656 | #!/usr/bin/env python3
import argparse
import os
import re
import difflib
class DiffGroup:
def __init__(self, group_type, diff, test_names=None):
self.group_type = group_type
self.diff = diff
if test_names:
self.test_names = set(test_names)
else:
self.test_... | StarcoderdataPython |
1678111 | <gh_stars>0
from typing import Dict, Tuple, Union
import numpy as np
class ContinuousPolicy:
"""
stores the policy of an infinite horizon agent.
"""
def __init__(self, policy: Dict[int, Union[int, np.ndarray]], num_actions: int):
"""
Parameters
----------
policy : Di... | StarcoderdataPython |
1703379 | <reponame>mattkjames7/PyMess<gh_stars>0
import numpy as np
def RemoveAxisLabels(ax,axis='x'):
'''
This function will remove the tick labels from a specific plot axis.
Inputs:
ax: pyplot.Axes instance
axis: 'x' or 'y' string indicating which axis to remove labels
from
'''
if axis == 'y':
lbl = ax.get_y... | StarcoderdataPython |
3236919 | <reponame>2nd47/stat-txt
# XML Parsing
import xml.etree.ElementTree as ET
# NLP data analysis
import nltk
nltk.download()
from nltk.corpus import stopwords
# Interact with user machine
from enum import Enum
import re
import sys
from sys import argv
import os
# INCLUDE HOW MANY WISHES WERE MADE
# INCLUDE LONGEST STRE... | StarcoderdataPython |
197047 | """Copyright 2011 The University of Michigan
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 writi... | StarcoderdataPython |
1761138 | <filename>src/ufc-2.0.5/src/utils/python/ufc_utils/form.py
# Code generation format strings for UFC (Unified Form-assembly Code) v. 2.0.5.
# This code is released into the public domain.
#
# The FEniCS Project (http://www.fenicsproject.org/) 2006-2011.
form_combined = """\
/// This class defines the interface for the ... | StarcoderdataPython |
3360895 | <reponame>GindaChen/MLOS<filename>source/Mlos.Python/mlos/Mlos/SDK/MlosSmartComponentRuntimeAttributes.py
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
from collections import namedtuple
def MlosSmartComponentRuntimeAttributes(smart_component_name, attribute_names):
assert '... | StarcoderdataPython |
3205699 | <filename>setup.py
from setuptools import setup
try:
long_desc = open("README.md").read()
except:
print("Skipping README.md for long description as it was not found")
long_desc = None
setup(
name="certbot-iconik-phpipam",
version="0.1.0",
description="phpipam DNS authentication plugin for Cer... | StarcoderdataPython |
3256937 | # Generated by Django 2.1.2 on 2018-11-11 19:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Game', '0008_notification'),
]
operations = [
migrations.AddField(
model_name='notification',
name='times',
... | StarcoderdataPython |
3282797 | """ANTLR3 runtime package"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must r... | StarcoderdataPython |
1624859 | <reponame>michaelpetit/networkperformance<filename>networkperformance/networkperformance.py
#!/usr/bin/env python3
# Author: <NAME>
# Date: May 2018
# <EMAIL>
# Copywrite: MIT Commons
########################################################################################################################
import datetim... | StarcoderdataPython |
1639141 | <reponame>bdice/openpathsampling
from .sql_backend import *
import pytest
class TestSQLStorageBackend(object):
def setup(self):
self._delete_tmp_files()
self.database = self._default_database
self.database.debug = True
self.schema = {
'samples': [('replica', 'int'),
... | StarcoderdataPython |
55544 | <reponame>coco-in-bluemoon/baekjoon-online-judge
def draw_z(size, position, target):
if size == 1:
return (position == target, 1)
base_r, base_c = position
half_size = size // 2
counter = 0
matched = False
if (target[0] >= (base_r + size)) or (target[1] >= (base_c + size)):
cou... | StarcoderdataPython |
1770903 | <reponame>arm61/scippneutron<filename>python/src/scippneutron/data_streaming/_consumer_type.py
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
from enum import Enum
class ConsumerType(Enum):
"""
Picklable way of instructing the mp.Process to
const... | StarcoderdataPython |
1755283 | __author__ = 'kelvin'
| StarcoderdataPython |
3356203 | import os
import time
import subprocess
from PyObjCTools import AppHelper
from AppKit import *
from encoder import Encoder, not_found_msg # Creates timelapse video
from recorder import Recorder # Takes screenshots
# Configuration
start_recording = False # Start recording on launch
encode = True # Create video af... | StarcoderdataPython |
87938 | from rest_framework import serializers
from members.models import Member
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = Member
fields = ('id', 'username', 'name')
# def create(self, validated_data):
# user = User(
# email=validated_da... | StarcoderdataPython |
1693207 | """
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.36
工具: python == 3.7.3
"""
"""
思路:
用set()函数排除重复元素
结果:
执行用时 : 52 ms, 在所有 Python3 提交中击败了94.57%的用户
内存消耗 : 18.6 MB, 在所有 Python3 提交中击败了83.08%的用户
"""
class Solution:
def containsDuplicate(self, nums):
if len... | StarcoderdataPython |
45944 | <reponame>cdragoiu/particle_physics
import math, ROOT, sys
from PlotStyle import *
# estimate systematics -----------------------------------------------------------------------------
def GetSys(basePath, baseRunType, sysPath, sysRunType, N, ybin):
if 'ele' in baseRunType:
data = 'DoubleElectron'
elif ... | StarcoderdataPython |
134686 | import matplotlib.pyplot as plt
import os
import pandas as pd
import geopandas as gpd
import numpy as np
import networkx as nx
def map_setup(n_communities, area, small_network=False):
# directory of data
areas = ['London', 'UK']
if area not in areas:
raise ValueError("Invalid area name. Expect... | StarcoderdataPython |
1617875 | <filename>src/abg_python/tests/test_function_utils.py
from ..function_utils import *
import numpy as np
def test_filter_kwargs():
def func(foo=1,bar=2):
return foo + bar
kwargs = {
'foo':2,
'bar':3,
'cat':None,
'dog':1
}
good,bad = filter_kwargs(func,kwar... | StarcoderdataPython |
118412 | import socket
import serial
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
from datetime import datetime
import pywinusb.hid as hid
from time import sleep
import time
serial = serial.Serial(
port='COM4',
baudrate=9600,
bytesize=8,
... | StarcoderdataPython |
3361666 | #! /usr/bin/python
# Note: this program requires the Banyan data structure library.
# https://pypi.python.org/pypi/Banyan
import argparse
import ast
import banyan
import collections
import dircache
import errno
import os
import re
import subprocess
import sys
import tempfile
class Fingerprint(list):
def __init__... | StarcoderdataPython |
10454 | <filename>tests/unit/test_juju.py
import os
import tempfile
import mock
from . import utils
from hotsos.core.config import setup_config
from hotsos.core.ycheck.scenarios import YScenarioChecker
from hotsos.core.issues.utils import KnownBugsStore, IssuesStore
from hotsos.plugin_extensions.juju import summary
JOURNAL... | StarcoderdataPython |
24989 | import os.path
from scipy.optimize import fsolve
import math
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import utils_Florian as utils
def equations(p, t_peak, t_half):
x, y = p
return (0.5 * (math.exp(-x * t_peak) - math.exp(-y * t_peak)) - (math.exp(-x * t_half) - math.exp... | StarcoderdataPython |
130681 | '''
./common/lib/xmodule/xmodule/modulestore
'''
from django.http import Http404
from xmodule.modulestore.django import modulestore
def get_course_by_id(course_key, depth=0):
"""
Given a course id, return the corresponding course descriptor.
If such a course does not exist, raises a 404.
depth: Th... | StarcoderdataPython |
3395063 | <reponame>guitarmind/HPA-competition-solutions
import os, sys
#os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="1"
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import skimage.io
from skimage.transform import resize
from imgaug import augmenters as iaa
from tq... | StarcoderdataPython |
2751 | <gh_stars>1-10
from copy import copy
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, cast
from pypika import Table
from pypika.terms import Criterion
from tortoise.exceptions import FieldError, OperationalError
from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstanc... | StarcoderdataPython |
4838217 | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
course_col = collections.defaultdict(list)
for realate in prerequisites:
nex, pre = realate[0], realate[1]
course_col[ pre ].append(nex)
checked = [Fals... | StarcoderdataPython |
4809137 | <reponame>sensorai/sensorai<filename>sensorai/cell_extension.py
def run_if(line, cell=None):
'''Execute current line/cell if line evaluates to True.'''
if not eval(line):
return
get_ipython().ex(cell)
def load_ipython_extension(shell):
'''Registers the run_if magic when the extension loads.'''
... | StarcoderdataPython |
1747894 | from ..client import DSClient
class DSDevice(object):
ID_FIELD = "id"
def __init__(self, client: DSClient, device_id, device_name, *args, **kwargs):
self._client = client
self._id = device_id
self._name = device_name
def __str__(self):
return '<{type} {id} "{name}">'.form... | StarcoderdataPython |
1648637 | <filename>pytorch_optimizer/__init__.py
# pylint: disable=unused-import
from pytorch_optimizer.adabelief import AdaBelief
from pytorch_optimizer.adabound import AdaBound
from pytorch_optimizer.adahessian import AdaHessian
from pytorch_optimizer.adamp import AdamP
from pytorch_optimizer.agc import agc
from pytorch_optim... | StarcoderdataPython |
102316 | <gh_stars>0
def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
... | StarcoderdataPython |
1637056 | <filename>deepsurv/datasets.py
from math import log, exp
import numpy as np
class SimulatedData:
def __init__(self, hr_ratio,
average_death = 5,
censor_mode = 'end_time', end_time = 15, observed_p = None,
num_features = 10, num_var = 2,
treatment_group = False):
"""
... | StarcoderdataPython |
111944 | import docker
docker_socket = 'tcp://172.17.42.1:4243'
client = docker.client.Client(base_url=docker_socket)
slave_image = 'datalad/buildslave:nd80-1'
container = client.create_container(slave_image)
client.start(container['Id'])
# Optionally examine the logs of the master
client.stop(container['Id'])
client.wait(conta... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.