id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
49148 | import json
from flask import Flask
from flask import render_template
import csv
import os
import pandas as pd
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
APP_STATIC = os.path.join(APP_ROOT, 'static')
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', name='abc')
... | StarcoderdataPython |
1711076 | <reponame>all-of-us/raw-data-repository<gh_stars>10-100
"""remove primary key from biobank_order_identifier_history
Revision ID: 7d63fbc6d9ca
Revises: <PASSWORD>
Create Date: 2019-08-20 10:33:02.458709
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
b... | StarcoderdataPython |
54788 | <reponame>sprotg/animal-avatar-generator<filename>src/animal_avatar/shapes/patterns.py
from animal_avatar.utils.colors import darken
PATTERNS = (
lambda color:
f'<path fill="{darken(color, -30)}" '
'd="M156 387.1c-57.8-12.3-96.7-42-96.7-107 0-9.4.8-18.6 2.4-27.6 '
'19.1 3.4 39.3 17 53.6 38.1a105 105 0 ... | StarcoderdataPython |
3366906 | <gh_stars>0
import os
# Say it is TEST environment
TESTING = True
# Statement for enabling the development environment
DEBUG = True
# Define the application directory (like doing a pwd)
BASE_DIR = os.path.abspath(os.path.dirname("config.py"))
# Define the database - we are working with
# SQLite for this example
# S... | StarcoderdataPython |
123626 | <filename>Back-End/Python/Basics/Part -1 - Functional/01 - Variables-Memory/01var_memory.py
my_var = [1, 2, 3, 4]
my_num = 10
print(id(my_num))
print(hex(my_num))
# REFERENCE COUNTING
import ctypes
def ref_count(address):
return ctypes.c_long.from_address(address).value
print(ref_count(id(my_var)))
# >>> 1
i... | StarcoderdataPython |
141923 | <reponame>IMBINGO95/FairMOT<filename>utils_BINGO/Imgs_Related.py
import cv2
import numpy as np
import time
import re
import shutil
import matplotlib.pyplot as plt
import os
import json
import codecs
import random
import time
RED = (0, 0, 255)
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)
CYAN = (255, 255, 0)
YELLOW = (0, 2... | StarcoderdataPython |
58585 |
# Extrahiert die Transaktionen aus dem Mempool
def getTxnsFromPool(MasterObj):
rwo = list()
for i in MasterObj.mempool: rwo.append(i); MasterObj.mempool.remove(i); print('Transaction {} selected'.format(i.getTxHash()))
return rwo
# Gibt die Höhe aller Gebühren welche verwendet werden an
def getTra... | StarcoderdataPython |
13119 | <reponame>gruzzlymug/ddg-2018<gh_stars>1-10
import os
import psutil
import subprocess
import threading
import sys
from threading import Timer
import select
from player_abstract import AbstractPlayer
class PlainPlayer(AbstractPlayer):
def __init__(self, socket_file, working_dir, local_dir=None,
p... | StarcoderdataPython |
3346874 | """
This script is used to test if mypy understands that the Nullable type is always False-y.
"""
from __future__ import annotations
from dataclasses import dataclass
from dataclasses_jsonschema.type_defs import Nullable
@dataclass
class Example:
name: Nullable[str | None] = None
example = Example("sienna")
... | StarcoderdataPython |
3251476 | <reponame>safelix/dino
import os
import pathlib
import torch
import torchvision
import torchvision.datasets as datasets
cwd = pathlib.Path().resolve()
path_to_data = cwd.joinpath('../../data')
path_to_data.mkdir(exist_ok=True)
mnist_trainset = datasets.MNIST(root=path_to_data,
downl... | StarcoderdataPython |
1623777 | <gh_stars>0
from sklearn.decomposition import PCA
import torch
import numpy as np
import utils
import torch.sparse
import pdb
'''
Classes for two linear models.
Linear model: PCA, used to compared with trained supervised models learned from kahip partitions.
Linear model: random projections, used to comp... | StarcoderdataPython |
3217398 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 28 16:11:52 2018
Functions for LARFP_lumen_segmentation_CGV.py
@author: clauvasq
"""
# import packages
import numpy as np
import matplotlib.pyplot as plt
import skimage.io as io
io.use_plugin('tifffile')
from skimage.filters import threshold_otsu
fr... | StarcoderdataPython |
3258416 | import logging
from bentoml.utils.log import configure_logging
def test_configure_logging_default():
configure_logging()
bentoml_logger = logging.getLogger("bentoml")
assert bentoml_logger.level == logging.INFO
assert bentoml_logger.propagate is False
assert len(bentoml_logger.handlers) == 2
... | StarcoderdataPython |
18945 | """Commands module common setup."""
from importlib import import_module
from typing import Sequence
def available_commands():
"""Index available commands."""
return [
{"name": "help", "summary": "Print available commands"},
{"name": "provision", "summary": "Provision an agent"},
{"nam... | StarcoderdataPython |
134843 | <gh_stars>1-10
from typing import Optional
from spark_auto_mapper_fhir.classproperty import genericclassproperty
from spark_auto_mapper_fhir.extensions.extension_base import ExtensionBase
from spark_auto_mapper_fhir.extensions.us_core.ethnicity_item import EthnicityItem
from spark_auto_mapper_fhir.fhir_types.list impo... | StarcoderdataPython |
1704462 | """
This module contains a class for discrete
1-dimensional exponential families. The main
uses for this class are exact (post-selection)
hypothesis tests and confidence intervals.
"""
import numpy as np
import warnings
from ..truncated import find_root
def crit_func(test_statistic, left_cut, right_cu... | StarcoderdataPython |
1754955 | <reponame>DewMaple/opencv-learning<gh_stars>0
import argparse
import cv2
import imutils
from utils import find_image
class Stitcher:
def stitch(self, images, key_points):
image_1 = cv2.imread(images[0])
image_2 = cv2.imread(images[1])
sift = cv2.xfeatures2d.SIFT_create()
kp1, des... | StarcoderdataPython |
151440 | # Required for Python to search this directory for module files
# We only export public API here.
from .commitmessage import CommitMessage
from .detection import find_checkout_root, default_scm, detect_scm_system
from .git import Git, AmbiguousCommitError
from .scm import SCM, AuthenticationError, CheckoutNeedsUpdate
... | StarcoderdataPython |
4807649 | """ ShowOspfv3SummaryPrefix.py
IOSXE parser for the following show command:
* show ospfv3 summary-prefix
"""
# python
import re
# metaparser
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Schema, Any, Or, Optional, Use, Default
# ==========================================... | StarcoderdataPython |
5379 | <filename>leaderboard-server/leaderboard-server.py
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
import simplejson as json
from leaderboard.leaderboard import Leaderboard
import uwsgidecorators
import signalfx
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors... | StarcoderdataPython |
3287685 | <filename>Warmup-1/missing_char.py
# MISSING_CHAR
def missing_char(str, n):
return str[:n] + str[n+1:] | StarcoderdataPython |
176089 | class Solution:
def rob(self, num):
ls = [[0, 0]]
for e in num:
ls.append([max(ls[-1][0], ls[-1][1]), ls[-1][0] + e])
return max(ls[-1])
| StarcoderdataPython |
1777671 | <filename>attacks/methods/refinement_tricks.py<gh_stars>10-100
"""
- UNUSED in current submission -
Various ideas for refining an adversarial example by modifying the pixels in certain patterns.
NOTE:
- BiasedBoundaryAttack contains these patterns, and supersedes this implementation.
TODO: Add Salt&pepper noise, or ... | StarcoderdataPython |
4827498 | <gh_stars>0
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import pandas as pd
import skimage.io as io
import numpy as np
import matplotlib.pyplot as plt
# Load data
class LandmarksDataset(Dataset):
"""Landmarks dataset."""
def __init__(self, csv_file, root_dir, transfo... | StarcoderdataPython |
1609124 | <gh_stars>100-1000
#dummy layer for splitting the model into multiple evaluations
import numpy
import theano
import denet.common.logging as logging
from denet.layer import AbstractLayer
class SplitLayer(AbstractLayer):
type_name = "split"
def __init__(self, layers, json_param={}):
super(... | StarcoderdataPython |
27421 | from .. app.pyefi.ttyp import ttyP
ttyP(0, "0 - ttyP test")
ttyP(1, "1 - header")
ttyP(2, "2 - bold")
ttyP(3, "3 - okblue")
ttyP(4, "4 - okgreen")
ttyP(5, "5 - underline")
ttyP(6, "6 - warning")
ttyP(7, "7 - fail")
| StarcoderdataPython |
6638 | <filename>netbox/extras/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _
from dcim.models import DeviceRole, DeviceType, Platform, Regi... | StarcoderdataPython |
139532 | import os
import tqdm
import torch
import numpy as np
from lib.helpers.save_helper import load_checkpoint
from lib.helpers.decode_helper import extract_dets_from_outputs
from lib.helpers.decode_helper import decode_detections
class Tester(object):
def __init__(self, cfg, model, data_loader, logger):
self.... | StarcoderdataPython |
3313860 | """Event topics."""
import enum
class RobotEventTopics(str, enum.Enum):
"""All robot-server event topics."""
HARDWARE_EVENTS = "hardware_events"
| StarcoderdataPython |
3253494 | from django.test import TestCase
class UserTests(TestCase):
# testing load of donate page
def test_donate_page_load(self):
response = self.client.get('/donate/')
self.assertEqual(response.status_code, 200)
# testing load of relevant templates to donate page
def test_donate_page_templ... | StarcoderdataPython |
1783618 | <reponame>wotsushi/competitive-programming
from functools import reduce
L, A, B, M = map(int, input().split())
MOD = M
class ModInt:
def __init__(self, x):
self.x = x % MOD
def __str__(self):
return str(self.x)
__repr__ = __str__
def __add__(self, other):
return (
... | StarcoderdataPython |
1692821 | # pip3 install blynk-library-python
# sudo pip3 install adafruit-circuitpython-shtc3
#from __future__ import print_function
import BlynkLib
import time
#import busio
#import board
#import adafruit_shtc3
import RPi.GPIO as GPIO
#time.sleep(40)
BLYNK_AUTH = '<KEY>'
blynk = BlynkLib.Blynk(BLYNK_AUTH, server='blynk.hon... | StarcoderdataPython |
42833 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Defines a class for the COMPAS dataset."""
import pandas as pd
import numpy as np
from .base_wrapper import BasePerformanceDatasetWrapper
from tempeh.constants import FeatureType, Tasks, DataTypes, ClassVars, CompasDatase... | StarcoderdataPython |
185847 | """Produce a greys cmap."""
from pyiem.plot.use_agg import plt
def main():
"""Go Main Go."""
cmap = plt.get_cmap("Greys_r")
for i in range(256):
c = cmap(i / 255.0)
print("%s %.0f %.0f %.0f" % (i, c[0] * 255, c[1] * 255, c[2] * 255))
if __name__ == "__main__":
main()
| StarcoderdataPython |
8981 | <reponame>Ramsha04/kits19-2d-reproduce
import os
from os.path import join, isdir
from pathlib import Path
from collections import defaultdict
from tqdm import tqdm
import nibabel as nib
import numpy as np
import json
from .resample import resample_patient
from .custom_augmentations import resize_data_and_seg, crop_to_... | StarcoderdataPython |
3375287 | <gh_stars>1-10
import numpy as np
# b|b|b
# -----
# b|b|b
# -----
# b|b|b
def printBoard(game):
for i in range(3):
for j in range(3):
if i is 0:
#print("Printing first row")
if j == 0 or j ==1:
print(game[i][j].decode() + str("|"), end = "")
elif j == 2:
print(game[i][j].decode())
elif i... | StarcoderdataPython |
1664436 | # -*- coding: utf-8 -*-
# Copyright (c) 2020 Kumagai group.
import numpy as np
from pydefect.analyzer.defect_charge_distribution import RadialDist
from pymatgen import Structure, Lattice, Spin
from pymatgen.io.vasp import Chgcar
def test():
structure = Structure(Lattice.cubic(3), ["H"], [[0, 0, 0]])
data = ... | StarcoderdataPython |
1671535 | import hashlib
from datetime import datetime
class Marvel:
def __init__(self, private_key, public_key):
self.private_key = private_key
self.public_key = public_key
def get_auth_data(self):
timestamp = datetime.now().timestamp()
formatted_string = f'{timestamp}{self.private_key... | StarcoderdataPython |
121798 | from setuptools import setup
with open('README.md') as readme_file:
readme = readme_file.read()
setup(
name='malwarefeeds',
version='0.1.0',
description='An aggregator for malware feeds.',
long_description=readme,
packages=['malwarefeeds'],
url='https://github.com/neriberto/malw... | StarcoderdataPython |
1726134 | # Adding a Line Feature to a Vector Layer
# https://github.com/GeospatialPython/Learn/raw/master/paths.zip
vectorLyr = QgsVectorLayer('/qgis_data/paths/paths.shp', 'Paths' , "ogr")
vectorLyr.isValid()
vpr = vectorLyr.dataProvider()
points = []
points.append(QgsPoint(430841.61703,5589485.34838))
points.append(QgsPoi... | StarcoderdataPython |
17811 | <reponame>jacobtobias/s3parq<filename>tests/test_publish_parq.py
import pytest
from mock import patch
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import boto3
from string import ascii_lowercase
import random
from dfmock import DFMock
import s3parq.publish_parq as parq
import s3fs
from moto imp... | StarcoderdataPython |
4816091 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import hashlib
import pathlib
import tempfile
from io import StringIO
from sys import getsizeof
from django.conf import settings
from django.contrib.auth.models import User
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
from ... | StarcoderdataPython |
3281471 | from evaluator.music_demixing import MusicDemixingPredictor
import numpy as np
print("Calculating scores for local run...")
submission = MusicDemixingPredictor(model_name='tdf+demucs0.5')
scores = submission.scoring()
scores = np.array([list(score.values()) for score in scores.values()])
print(np.mean(scores, 0), np.... | StarcoderdataPython |
4837570 | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright (c) 2018, 9t9it and Contributors
# See license.txt
from __future__ import unicode_literals
from frappe.utils import getdate
import unittest
from toolz import pluck
from park_management.park_management.report.item_consumption_report.helpers \
import generate_intervals... | StarcoderdataPython |
108798 | <reponame>dacosta2213/cfdi<filename>cfdi/cfdi/doctype/cfdi/cfdi.py
# -*- coding: utf-8 -*-
# Copyright (c) 2015, C0D1G0 B1NAR10 and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils.fi... | StarcoderdataPython |
3271625 | <filename>spiders/cnjsj.py
from datetime import datetime
from urllib.parse import urlencode
import gevent
import requests
from bs4 import BeautifulSoup
from gevent.queue import Queue
from config import *
# 代理ip
proxy = ""
# 获取数据输出路径
path_ = version_control('new')
# 记录最大任务数量
max_len = 0
# 记录任务实时进度
count = 0
# 任务队... | StarcoderdataPython |
1614678 | <filename>utilities/get_system.py
# -*- coding: utf-8 -*-
# (C) Copyright 2019 Hewlett Packard Enterprise Development LP.
# 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.... | StarcoderdataPython |
183070 | <gh_stars>10-100
import shlex
from prompt_toolkit.completion import Completer, Completion
class CommandCompleter(Completer):
"""Manage completion suggestions to the CLI."""
def __init__(self, client):
"""Create a CLI commands completer based on the client object."""
self.client = client
... | StarcoderdataPython |
65079 | """model.py"""
import torch
import torch.nn as nn
# import torch.nn.functional as F
import torch.nn.init as init
from torch.autograd import Variable
def reparametrize(mu, logvar):
std = logvar.div(2).exp()
eps = Variable(std.data.new(std.size()).normal_())
return mu + std * eps
class View(nn.Module):
... | StarcoderdataPython |
2127 | <filename>csat/django/fields.py<gh_stars>0
from lxml import etree
from django import forms
from django.db import models
class XMLFileField(models.FileField):
def __init__(self, *args, **kwargs):
self.schema = kwargs.pop('schema')
super(XMLFileField, self).__init__(*args, **kwargs)
def clean(... | StarcoderdataPython |
192212 | import functools
from flask import (
request, g, redirect, url_for,
flash, render_template,
Blueprint, session
)
from werkzeug.security import check_password_hash, generate_password_hash
from blog.model import User
from blog.db import db_session
bp = Blueprint('auth', __name__, url_prefix='/auth')
@bp.ro... | StarcoderdataPython |
104373 | # -*- coding: utf-8 -*-
"""Sanity checks for testing."""
import unittest
class TestSanity(unittest.TestCase):
"""A trivial test case."""
def test_sanity(self):
"""Run a trivial test."""
self.assertIsNone(None)
| StarcoderdataPython |
1645678 | # https://github.com/Wireframe-Magazine/Wireframe56
# Wireframe #56:
import pgzrun
import pickle
editorState = True
editorEnabled = True
if editorState:
WIDTH = 1000
gameState = count = 0
editItem = "blank"
editorMessage = ""
editorMessageCount = 0
blockTypes = [
Actor('blank', center=(900, 250)),
Act... | StarcoderdataPython |
1670875 | <filename>pyapp/__init__.py<gh_stars>0
from .pyapp import PyApp # noqa
# Package version
# Follows semantics versioning (https://semver.org/)
__version__ = "0.1.0-dev0"
| StarcoderdataPython |
3360115 | import base64
from docker.errors import NotFound
from armada_backend import docker_client
from armada_backend.api_run import Run
from armada_backend.api_stop import Stop
from armada_backend.models.services import get_services_by_ship
from armada_backend.utils import shorten_container_id
from armada_command import arm... | StarcoderdataPython |
3278522 | <reponame>dfint/dfrus
from collections import namedtuple
from enum import IntEnum, Enum, auto
class Cond(IntEnum):
"""Condition codes"""
(o, no, b, nb, e, ne, be, a, s, ns, p, np, l, nl, le, g) = range(16)
nae = b
not_above_equal = nae
c = b
ae = nb
nc = nb
z = e
zer... | StarcoderdataPython |
4816424 | from django.test import TestCase
from .models import Location,Category,Image
# Create your tests here.
class LocationTestClass(TestCase):
# Set up method
def setUp(self):
self.kigali= Location(name = 'kigali')
# Testing instance
def test_instance(self):
self.assertTrue(isinstance(... | StarcoderdataPython |
145314 | <reponame>ShameekConyers/covid-socio-economic-inquiry
import pandas as pd
import requests
import io
import os
import json
import plotly.express as px
import plotly.figure_factory as ff
import numpy as np
import pathlib
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
pd.options.plotting.b... | StarcoderdataPython |
6961 | # -*- coding: utf-8-unix -*-
import platform
######################################################################
# Platform specific headers
######################################################################
if platform.system() == 'Linux':
src = """
typedef bool BOOL;
"""
#############################... | StarcoderdataPython |
4833067 | import unittest
import torch
from torch.nn import functional as F
from torch.testing._internal.common_utils import TestCase, run_tests
from torch.testing import FileCheck
import io
@unittest.skipUnless(torch.is_vulkan_available(),
"Vulkan backend must be available for these tests.")
class TestVul... | StarcoderdataPython |
1665276 | import sklearn
from sklearn import preprocessing
from sklearn.impute import SimpleImputer
from sklearn.decomposition import PCA
import pandas as pd
import numpy as np
#replace question marks with np.nan type
def replace_question_marks(df):
try:
df = df.replace({'?' : np.nan})
print("Replaced all '?... | StarcoderdataPython |
3258990 | DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "app_test",
"USER": "go",
"PASSWORD": "go",
"HOST": "localhost",
}
}
CACHES = {
'default': {
'BACKEND': 'django_pylibmc.memcached.PyLibMCCache',
'LOCATION': 'localh... | StarcoderdataPython |
3345037 | #-------------------------------------------------------------------------------
#
# http utilities
#
# Author: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2018 EOX IT Services GmbH
#
# Permission is hereby granted, free of charge, to any person ob... | StarcoderdataPython |
3266167 | <reponame>amitbend/Restplus_Skeleton<gh_stars>1-10
# Flask settings
FLASK_DEBUG = True # Do not use debug mode in production
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False | StarcoderdataPython |
3211673 | import pandas
from sklearn.tree import DecisionTreeClassifier
# training of the supervised learning algorithm
def trainingDecisionTree():
names = ['PCA1', 'PCA2', 'PCA3', 'PCA4', 'class']
dataset = pandas.read_csv('.\\csv\\pcaData.csv', names=names)
array = dataset.values
X = array[:,0:4]
Y = arra... | StarcoderdataPython |
134678 | # Generated by Django 3.1.4 on 2020-12-09 14:25
from django.conf import settings
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
import paperclip.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('cont... | StarcoderdataPython |
29596 | """
Created on 9 Aug 2016
@author: <NAME> (<EMAIL>)
"""
import _csv
import sys
# --------------------------------------------------------------------------------------------------------------------
class Histogram(object):
"""
classdocs
"""
__HEADER_BIN = ".bin"
__HEADER_COUNT = ".count"
... | StarcoderdataPython |
1680791 | # Copyright 2019 The Matrix.org Foundation CIC
#
# 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 agre... | StarcoderdataPython |
1792125 | <gh_stars>1-10
#!/usr/bin/env python
__author__ = '<NAME>'
import unittest
from mock import Mock
from pyon.util.unit_test import PyonTestCase
from pyon.util.int_test import IonIntegrationTestCase
from nose.plugins.attrib import attr
from pyon.core.exception import BadRequest, NotFound
from pyon.public import RT, I... | StarcoderdataPython |
136819 | import datetime
def _beforeDawn( hour ):
EARLY = 5
return hour < EARLY
def nextDaylightDate():
today = datetime.date.today()
hour = datetime.datetime.today().hour
if _beforeDawn( hour ):
return today
else:
return today + datetime.timedelta( 1 )
| StarcoderdataPython |
197015 | <filename>src/station.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
import artikcloud
from artikcloud.rest import ApiException
from smbus import SMBus
import Adafruit_BMP.BMP085 as BMP085 # Actually using it for BMP180 here
import Adafruit_BBIO.GPIO as GPIO
import requests
import g... | StarcoderdataPython |
8849 | <gh_stars>0
from python_clean_architecture.shared import use_case as uc
from python_clean_architecture.shared import response_object as res
class OrderDataGetUseCase(uc.UseCase):
def __init__(self, repo):
self.repo = repo
def execute(self, request_object):
#if not request_object:
... | StarcoderdataPython |
1623937 | """Example GNN for QM9"""
import json
import tensorflow as tf
from datetime import datetime
from pathlib import Path
from gnn import GNN, get_dataset_from_files
from gnn.initial import PadInitializer
from gnn.message_passing import FeedForwardMessage
from gnn.readout import GatedReadout
from gnn.update import GRUUpdat... | StarcoderdataPython |
1752388 | <reponame>highfestiva/life
# Author: <NAME>
# Copyright (c) 2002-2009, Righteous Games
import os
import sys
vcver = 10
NMAKE = "bin/nmake.exe"
VCBUILD = "vcpackages/vcbuild.exe"
NETBUILD = r'C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe'
pause_on_error = False
def _getosname():
if sys.platform == "w... | StarcoderdataPython |
1799443 | from datetime import datetime
from pytz import timezone, utc
from authz.config import Config
def now(name=Config.TIMEZONE):
tz = timezone(name)
return datetime.utcnow().replace(tzinfo=utc).astimezone(tz).replace(
microsecond=0, tzinfo=None)
| StarcoderdataPython |
1650332 | <reponame>shaandesai1/AIMS
from data.datasets import dataset_mnist, dataset_boston, dataset_california, dataset_mini_mnist
def get_datasets(args):
print('Dataset: \t {}'.format(args.dataset.upper()))
if args.dataset == 'mnist':
args.n_features = 784
args.n_classes = 10
dataset_train,... | StarcoderdataPython |
3394443 | <reponame>Arachnid/tweetengine<filename>src/tweetengine/i18n.py<gh_stars>1-10
""" load the message catalogs and provide them as ztk utilities."""
import os
from zope.interface import implements
from zope.component import getSiteManager
from zope.i18n.interfaces import (
ITranslationDomain,
INegotiator,
)
from z... | StarcoderdataPython |
1692202 | <gh_stars>1-10
def xm_version():
return {
"major": 2,
"minor": 1,
"alter": 5,
"build": 0,
}
| StarcoderdataPython |
170515 | <gh_stars>0
def read_spreadsheet():
file_name = "Data/day2.txt"
file = open(file_name, "r")
spreadsheet = []
for line in file:
line = list(map(int, line.split()))
spreadsheet.append(line)
return spreadsheet
def checksum(spreadsheet):
total = 0
... | StarcoderdataPython |
3256058 | <filename>kokobot/cogs/random.py
import asyncio
import logging
import random as rng
import typing
import discord
from discord.ext import commands
from discord.ext.commands.errors import BadArgument
logger = logging.getLogger('discord.kokobot.random')
emoji_bank = {
':regional_indicator_j:': '\U0001F1EF',
':re... | StarcoderdataPython |
3298892 | <reponame>LiteID/LiteID.github.io
import sys
import re
if len(sys.argv) != 2:
print "Usage:\n\tpython \"navigation-menu-gen.py\" <filename>"
exit(1)
f = open(sys.argv[1], 'r')
file = f.read()
f.close()
f = open(sys.argv[1], 'w')
try:
f.write(file.split('menu: | ')[0]+'menu: | \n')
for m in re.finditer(r"\n[#]+[ ]... | StarcoderdataPython |
162499 | <gh_stars>1-10
import numpy
def is_positive_semidefinite(matrix: numpy.array) -> bool:
"""Check whether a matrix is positive semi-definite or not
Attempt to compute the Cholesky decomposition of the matrix, if this fails
then the matrix is not positive semidefinite.
Parameters
----------
mat... | StarcoderdataPython |
14727 | import getpass
# prompt user without echoing output
print getpass.getpass()
print getpass.getpass(prompt="Custom Prompt:")
print "user login name:", getpass.getuser()
| StarcoderdataPython |
3372399 | """Модуль получения абстрактных моделей, содержащихся в уведомлениях приложения."""
from typing import Type
from django.apps import apps
from .mailing import AbstractMailing
from .notification import AbstractNotice, AbstractNotification
from ..settings import notifications_settings
class Notice(AbstractNotice):
... | StarcoderdataPython |
1623966 | Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example ... | StarcoderdataPython |
75106 | ALL = 'All servers'
def caller_check(servers = ALL):
def func_wrapper(func):
# TODO: To be implemented. Could get current_app and check it. Useful for anything?
return func
return func_wrapper
| StarcoderdataPython |
1750033 | <reponame>Gordonei/pyepd
# PyEPD
# <NAME> (<EMAIL>)
# November 2017
import numpy
from PIL import Image
from contextlib import contextmanager
@contextmanager
def acquire_and_normalise(filename, display_panel_controller, background_colour=-1, rotate_count=0):
"""
Reads in input image, and converts to correct ... | StarcoderdataPython |
106766 | <reponame>diCagri/content
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import json
import requests
import os
import os.path
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
# remove proxy if not set to true in params
if no... | StarcoderdataPython |
1709263 | <gh_stars>0
# Copyright 2014 Google Inc. All Rights Reserved.
"""Command for getting target pools."""
from googlecloudsdk.compute.lib import base_classes
class GetTargetPools(base_classes.RegionalGetter):
"""Get target pools."""
@staticmethod
def Args(parser):
base_classes.RegionalGetter.Args(parser)
b... | StarcoderdataPython |
1762884 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Main dialog to welcome users."""
import json
import os.path
from typing import List
from botbuilder.dialogs import Dialog
from botbuilder.core import (
TurnContext,
ConversationState,
UserState,
BotTelemetr... | StarcoderdataPython |
1627004 | <gh_stars>0
# -*- coding: utf-8 -*-
import torch
import matplotlib.pyplot as plt
import os.path as osp
def visualize_batch(
batch, labels=None, save_dir='', figname='figure', ncols=4, figsize=(4, 4)
):
"""Visualise training batch
batch (torch.Tensor): images of shape (B, C, H, W)
"""
nrows = batc... | StarcoderdataPython |
192320 | import os
import shutil
import numpy as np
from util import log_util
log = log_util.get_logger("file process")
def create_blank_file(file_name):
'''
create a blank file
:param file_name:
:return:
'''
with open(file_name, 'w') as wt:
wt.write("")
log.debug("blank file %s crea... | StarcoderdataPython |
1778495 | #!/usr/bin/env python
"""
##############################################
Testing Package Reliability Growth Data Module
##############################################
"""
# -*- coding: utf-8 -*-
#
# rtk.testing.growth.Growth.py is part of The RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 <NAME> an... | StarcoderdataPython |
164305 | <gh_stars>0
def dibujo (base,altura):
dibujo=print("x"*base)
for fila in range (altura):
print("x"+" "*(base-2)+"x")
dibujo=print("x"*base)
dibujo(7,5)
| StarcoderdataPython |
92752 | """Fractal definitions
Credit: https://elc.github.io/posts/plotting-fractals-step-by-step-with-python
"""
from dataclasses import dataclass
@dataclass
class Params:
"""Holds Fractal definitions suitable for L-System construction"""
name: str
axiom: str
rules: dict
iterations: int
angle: int
... | StarcoderdataPython |
1731805 | from datetime import datetime, timedelta
from cal_setup import get_calendar_service
def main( color):
# mark the entire day as a special event
service = get_calendar_service()
d = datetime.now().date()
tmr = d +timedelta(days=1)
start = d.isoformat()
end = datetime(tmr.year, tmr.month, tmr.da... | StarcoderdataPython |
1792581 | #!/usr/bin/env python
import socket
try:
from cStringIO import StringIO
except ImportError, e:
from StringIO import StringIO
from struct import unpack
from __init__ import dumps, loads
def _bintoint(data):
return unpack("<i", data)[0]
def _sendobj(self, obj):
"""
Atomically send a BSON message.
"""
data = dum... | StarcoderdataPython |
1605891 | <reponame>drawjk705/us-pls
from dataclasses import dataclass, field
from us_pls._logger.configure_logger import DEFAULT_LOG_FILE
DEFAULT_DATA_DIR = "data"
@dataclass
class Config:
year: int
data_dir: str = field(default=DEFAULT_DATA_DIR)
log_file: str = field(default=DEFAULT_LOG_FILE)
should_overwri... | StarcoderdataPython |
154744 | <filename>deep-learning-for-image-processing-master/tensorflow_classification/Test2_alexnet/read_pth.py
import torch
import numpy as np
import tensorflow as tf
def rename_var(pth_path, new_ckpt_path, num_classes):
pytorch_dict = torch.load(pth_path)
with tf.Graph().as_default(), tf.compat.v1.Session().as_def... | StarcoderdataPython |
3028 | import pytest
from plenum.server.view_change.view_changer import ViewChanger
from stp_core.common.log import getlogger
from plenum.test.pool_transactions.helper import start_not_added_node, add_started_node
logger = getlogger()
@pytest.fixture(scope="module", autouse=True)
def tconf(tconf):
old_vc_timeout = tc... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.