id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
168333
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
StarcoderdataPython
132570
import tensorflow as tf import sys from models.model import TFModel class TFLinearModel(TFModel): def __init__(self, num_features, alpha=0.001, regularization=0.0): # Inherit all self attributes TFModel.__init__(self, num_features, alpha=alpha) self.inputs['d'] = tf.placeholder(tf.float32, [None, 1]) ...
StarcoderdataPython
3504884
""" Helpers. """ import os import shutil import string import importlib from collections import OrderedDict class ObjectFormatter(string.Formatter): def get_value(self, key, args, kwargs): if len(args) < 1 or not isinstance(args[0], object): raise TypeError() try: val = g...
StarcoderdataPython
294582
<filename>bentorched/vision/detection.py """ Utilities for object detection. """ from typing import List, Union import torch def intersection_over_union( boxes_preds: torch.Tensor, boxes_labels: torch.Tensor, box_format: str = "midpoint", eps: float = 1.0e-6 ) -> float: """ Calculate IOU bet...
StarcoderdataPython
82816
<reponame>danielvvDev/Sqlmap-Reforced2<filename>tamper/plus2concat.py #!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'LICENSE' for copying permission """ import re from lib.core.common import zeroDepthSearch from lib.core.enums import PRIORITY __priority__ = PR...
StarcoderdataPython
3239071
# Python import logging import time import picamera from picamera.array import PiRGBArray from picamera import PiCamera import numpy as np from threading import Thread logging.basicConfig() LOGLEVEL = logging.getLogger().getEffectiveLevel() RESOLUTION = (320, 320) logging.basicConfig() # https://github.com/dtresku...
StarcoderdataPython
11251850
import os import re from flask import Flask, jsonify, render_template, request, url_for from flask_jsglue import JSGlue from cs50 import SQL from helpers import lookup # configure application app = Flask(__name__) JSGlue(app) # ensure responses aren't cached if app.config["DEBUG"]: @app.after_request def aft...
StarcoderdataPython
5034961
<reponame>kids-first/kf-api-dataservice from itertools import chain from sqlalchemy import and_, event from dataservice.extensions import db from dataservice.api.common.model import Base, KfId from dataservice.api.biospecimen.models import Biospecimen from dataservice.api.diagnosis.models import Diagnosis from datase...
StarcoderdataPython
157941
<filename>aries_cloudagent/pdstorage_thcf/local.py from .base import BasePDS from .api import encode import json class LocalPDS(BasePDS): def __init__(self): super().__init__() self.storage = {} self.preview_settings = { "oca_schema_namespace": "pds", "oca_schema_dr...
StarcoderdataPython
11322692
import torch from IPython import display from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) b = torch.zeros(num_outputs, requires_grad=True) X = ...
StarcoderdataPython
215730
<gh_stars>100-1000 # -*- coding: utf-8 -*- #------------------------------------------------------------------------- # Quality Program utilities # -------------------------------------- # # Copyright 2018 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complia...
StarcoderdataPython
1772132
from unittest.mock import MagicMock, patch, PropertyMock from onap_data_provider.resources.tenant_resource import TenantResource from onapsdk.exceptions import ResourceNotFound TENANT_RESOURCE_DATA = {"tenant-id": "Test ID", "tenant-name": "<NAME>"} def test_tenant_resource_tenant(): cloud_region_mock = MagicM...
StarcoderdataPython
3298101
S, T = map(str, input().split()) A, B = map(int, input().split()) U = input() if S == U: A -= 1 else: B -= 1 print(f'{A} {B}')
StarcoderdataPython
3355344
#---------------------------------------------------------------------- # Copyright (c) 2008 Board of Trustees, Princeton University # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, i...
StarcoderdataPython
11208497
from dataclasses import dataclass @dataclass class FeatureExtractorConfig: fs: int fftl: int = 1024 shiftms: int = 5 minf0: float = 50. maxf0: float = 500. mcep_dim: int = 24 mcep_alpha: float = 0.42 @dataclass class McepGMMConfig: param: object n_mix: int = 32 covtype: str = ...
StarcoderdataPython
3452859
<gh_stars>0 import requests def get_image_url(): req = requests.get('https://random.dog/woof.json') res = req.json() return res.get('url', None)
StarcoderdataPython
239643
from typing import List, Tuple, Dict import time from pprint import pprint import lightgbm as lgb import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from catboost_enc import CatBoostEncoder from encoders import CategoryLabels, Tim...
StarcoderdataPython
6685975
import matplotlib # matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import numpy as np from scipy.integrate import solve_ivp from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import scipy.io import time plt.rc("text", usetex=False) plt.rc("font", family="sans-serif", size=12) def f(v, w, a, ...
StarcoderdataPython
190562
<gh_stars>1-10 """insert new fields in user table Revision ID: 948eefcc2e28 Revises: <PASSWORD> Create Date: 2020-02-05 11:00:03.687495 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '948eefcc2e28' down_revision = 'a9c4c2503<PASSWORD>' branch_labels = None dep...
StarcoderdataPython
3272651
"""Test dispatcher. The dispatcher can choose which template to use according to the parameters of workload""" from collections import namedtuple from tvm import autotvm from tvm.autotvm.task import dispatcher, DispatchContext SimpleConfig = namedtuple('SimpleConfig', ('template_key', 'is_fallback')) def test_dispat...
StarcoderdataPython
6533948
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import imp import os.path import shutil import sys import tempfile import unittest from mojom import fileutil class FileUtilTest(unittest.TestCase): def...
StarcoderdataPython
1688640
<gh_stars>0 import pygame from .towerButton import TowerButton HEIGHT_GAP_PX = 4 #Distance from top of background rect WIDTH_GAP_PX = 40 #How "spread out" the tower buttons are from each other IMG_SIZE = (60, 60) #Size of tower buttons BOTTOM_PX = 40 #Area where name and cost are displayed class Menu...
StarcoderdataPython
8138909
import os import ray import torch import torch.optim as optim import yaml from ray import tune from ray.tune.progress_reporter import CLIReporter from ray.tune.stopper import TrialPlateauStopper from torch.utils.data import DataLoader from utils import model_utils, criterion_utils, data_utils def train_AudioGroundi...
StarcoderdataPython
3318771
import os import string import random import cv2 def get_random_string(length): letters = string.ascii_lowercase result_str = ''.join(random.choice(letters) for i in range(length)) return result_str def write_line(line): with open("gt.txt", "a") as f: f.write(line + "\n") imgs_di...
StarcoderdataPython
8173077
from __future__ import division import os import pandas as pd import math import numpy as np from scipy.spatial import ConvexHull import scipy from configparser import ConfigParser def extract_features_wotarget(inifile): config = ConfigParser() configFile = str(inifile) config.read(configFile) csv_dir ...
StarcoderdataPython
11372784
<reponame>weidi-chang/graph_nets # Copyright 2019 <NAME> and <NAME>. 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 # #...
StarcoderdataPython
1747552
<filename>code_utils/decorators/printing.py from functools import wraps __all__ = [ 'print_call', ] def print_call(function): @wraps(function) def wrapper(*func_args, **func_kwargs): print('{} is called from the decorator' \ 'with arguments={} and kwargs={}'.format( fu...
StarcoderdataPython
11207601
<filename>Chapter06/lunar_lander/a3c.py import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import gym import threading import multiprocessing from random import choice from time import sleep from time import time from threading import Lock from utils import * xavier = tf.contrib.layers.xavie...
StarcoderdataPython
4981160
"""Ttk Theme Selector. Although it is a theme selector, you won't notice many changes since there is only a combobox and a frame around. """ import ttk class App(ttk.Frame): def __init__(self): ttk.Frame.__init__(self) self.style = ttk.Style() self._setup_widgets() def ...
StarcoderdataPython
5064048
## @defgroup Methods-Aerodynamics-Common Common # These are methods that are used by several analyses. # @ingroup Methods-Aerodynamics from . import Fidelity_Zero from . import Gas_Dynamics
StarcoderdataPython
391275
<reponame>BlankGodd/monty_hall<filename>monty_hall.py #! /usr/bin/python # Author: @BlankGodd from random import choice wins = 0 loss = 0 for i in range(11): for j in range(21): print() print('Test ',i+1) print() reals = {'a':'car','b':'goat','c' :'goat'} doors = ['a','b','c'] door...
StarcoderdataPython
171283
#Testing script that lives outside of pytest due to DeepForest dependency in a new conda env. PYTHONPATH manually added to root dir for relative paths. import os import pytest import tensorflow import numpy as np from matplotlib import pyplot as plt import geopandas as gpd import pandas as pd import glob import prepa...
StarcoderdataPython
259854
<reponame>vannesspeng/TornadoForum #!/usr/bin/env python # -*- coding:utf-8 -*- # author:pyy # datetime:2018/12/29 10:33 import json from Myforum.Forum.handlers import BaseHandler from Myforum.apps.messages.models import Message from Myforum.apps.users.models import User from Myforum.apps.utils.decorators import authe...
StarcoderdataPython
3535285
<reponame>dmitriyvek/Tracker import base64 import bcrypt from asyncpgsa import PG from sqlalchemy import select, and_, or_, exists, literal_column from tracker.api.errors import APIException from tracker.api.status_codes import StatusEnum from tracker.db.schema import users_table async def check_credentials_duplica...
StarcoderdataPython
11382041
<reponame>wmak/gapipy # flake8: NOQA from .details import DossierDetail, DossierDetailType, DossierDetailsMixin from .accommodation_dossier import AccommodationDossier from .activity_dossier import ActivityDossier from .place_dossier import PlaceDossier from .transport_dossier import TransportDossier from .dossier_feat...
StarcoderdataPython
332693
<reponame>EnSlavingBlair/Coincidences from __future__ import (absolute_import, division, print_function, unicode_literals) import pytest import numpy as np from ...time import Time from ... import units as u from ...constants import c from ..builtin_frames import GCRS from ..earth import Earth...
StarcoderdataPython
349135
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.jvm.subsystems.scala_platform import ScalaPlatform from pants.backend.jvm.subsystems.scoverage_platform import ScoveragePlatform from pants.backend.jvm.targets.exportabl...
StarcoderdataPython
1785780
""" python ReadingComp_Test.py """ import unittest import json import requests class ReadingComp_Test(unittest.TestCase): def test_comprehension(self): payload = { "params" : [ '<NAME>, also known as <NAME>, was a Jewish teacher and reformer of religion who has become the main a...
StarcoderdataPython
3541656
<gh_stars>1-10 """ api_unittest.py Copyright 2015 <NAME> This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the h...
StarcoderdataPython
1865217
from contextlib import contextmanager from collections import defaultdict, namedtuple from copy import copy import warnings from numba.core import (errors, types, typing, ir, funcdesc, rewrites, typeinfer, config, lowering) from numba.parfors.parfor import PreParforPass as _parfor_PreParforPas...
StarcoderdataPython
1783132
<reponame>zmixtv1/cev-Python class serie(object): def __init__(self,nome,valor,ano=2020,temporada=1,duracao=40): self.nome = nome self.valor = valor self.ano = ano self.temporada = temporada self.duracao = duracao def get_nome(self): return self.nome def ge...
StarcoderdataPython
246420
from cassandra.cluster import Cluster import uuid import datetime cluster = Cluster() # Connect to our Cassandra Server Cluster session = cluster.connect('cbd_video_sharing') # Connect to our Keyspace insert_types = {'user': '(email, name, reg_timestamp, username)', 'video': '(id, author, upload_tim...
StarcoderdataPython
1971834
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv import json import os import torch.utils.data as data class MedNLIData(data.Dataset): def __init__(self): self.ids = [] self.samples = [] def __getitem__(self, index): sentence1, sentence2, gold_label = self.samples[index] ...
StarcoderdataPython
1669702
<reponame>terror/Solutions class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split() if len(pattern) != len(s): return 0 if len(set(pattern)) != len(set(s)): return 0 prev = pattern[0] for i in range(1, len(pattern)): if pattern[i] != prev: if s...
StarcoderdataPython
6687742
import argparse import random import ufedmm from simtk import openmm, unit from sys import stdout waters = ['spce', 'tip3p', 'tip4pew', 'tip5p'] parser = argparse.ArgumentParser() parser.add_argument('--water', dest='water', help='the water model', choices=waters, default=None) parser.add_argument('--ff', dest='ff', ...
StarcoderdataPython
8150983
<filename>ctcse_datal.py import glob import os import librosa import numpy as np import time from utils import for_stft_2 from hparam import hparam as hp print('start to prepare data for ctc') rms = lambda y: np.sqrt(np.mean(np.square(y), axis=-1)) zero_audio = np.zeros(3*hp.data.sr) error_num = 0 def ...
StarcoderdataPython
5031608
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """ MakeHuman plugin for estimating the weight of the model using BSA (body surface are) based metrics. **Project Name:** MakeHuman **Product Home Page:** http://www.makehuman.org/ **Code Home Page:** https://bitbucket.org/MakeHuman/makehuman/ **Authors:** ...
StarcoderdataPython
8077115
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: None Do no...
StarcoderdataPython
3552399
<reponame>WuQingYi20/CatchTime<gh_stars>0 import json import csv matrix = [] nameMap = { 0:'无', 1: '书包', 2: '椅子', 3: '长椅子', 4: '新椅子', 5: '讲台', 6:'桌子', 7:'长桌子', 8: '书架', 9:'机房凳子', 10:'盆栽', } data = {"Items":[], "total":0} if __name__ == "__main__": with open('Map1.csv','r', encoding='utf-8') as file...
StarcoderdataPython
9608586
#!/usr/bin/env python3 import fileinput import re import statistics BENCH_NAME = re.compile(r'(\w+)') EST_CYCLES = re.compile(r' +Estimated Cycles: +(\d+) +\((.*)\)') name = '' printed_headers = False ratios = [] for line in fileinput.input(): if match := BENCH_NAME.match(line): name = match[1] if m...
StarcoderdataPython
5001048
<reponame>SubCODERS/xrpl-py """Async methods for obtaining information about the status of the XRP Ledger.""" from xrpl.asyncio.ledger.main import ( get_fee, get_latest_open_ledger_sequence, get_latest_validated_ledger_sequence, ) __all__ = [ "get_latest_validated_ledger_sequence", "get_fee", "...
StarcoderdataPython
1659686
<gh_stars>100-1000 # # Pyserini: Reproducible IR research with sparse and dense representations # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
StarcoderdataPython
3203081
import threading def singleton_wrapper(cls): lock_ = threading.Lock() def make_singleton(*args, **kwargs): if not hasattr(cls, '_instance'): with lock_: if not hasattr(cls, '_instance'): cls._instance = cls(*args, **kwargs) return cls._instance ...
StarcoderdataPython
5003971
"""one room adventure for python command line""" import random class clockobj: def __init__(self): self.min=0 self.hour=9 self.sec=0 def gettime(self): if self.hour<10: stg1="0"+str(self.hour) else: stg1=str(self.hour) if self.min<10: ...
StarcoderdataPython
9683969
<filename>CrawlingImages/gettyImages/code.py from bs4 import BeautifulSoup import time import requests from random import randint from html.parser import HTMLParser import json import shutil import mechanize DATA = [] f = open("data.txt","w") USER_AGENT = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4)...
StarcoderdataPython
307792
# Author: <NAME> # Date: 22 November, 2018 # Description: A file for implementing the Dataset interface of PyTorch import scipy.sparse as sp import numpy as np import pandas as pd import torch from torch.utils.data import Dataset np.random.seed(7) #.train.rating ------------> trainMatrix -------> user_input, item_in...
StarcoderdataPython
241093
from django.urls import path from . import views app_name = "outbreaks" urlpatterns = [ path( "", views.SearchView.as_view(), name="search", ), path( "<uuid:pk>/profile", views.ProfileView.as_view(), name="profile", ), path( "<uuid:pk>/histor...
StarcoderdataPython
1723194
<reponame>nicococo/scRNA<gh_stars>10-100 ################################################### ### ### ### Plot script for experiment on generated data ### ### written by <NAME>, <NAME>, ### ### <NAME> and <NAME> ### ### ### ###################################...
StarcoderdataPython
6580144
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
StarcoderdataPython
250570
from .utils import * from .timeseries import *
StarcoderdataPython
1980671
# @Created Date: 2020-10-23 10:02:23 pm # @Filename: exceptions.py # @Email: <EMAIL> # @Author: <NAME> # @Last Modified: 2020-10-23 10:02:31 pm # @Copyright (c) 2020 MinghuiGroup, Soochow University class WithoutExpectedKeyError(Exception): pass class PossibleConnectionError(Exception): pass class Possibl...
StarcoderdataPython
180921
<gh_stars>0 from seaborn.request_client.intellisense import * class Account_Access_Array(Endpoint): def get(self, account_id): """ This will return all users who have access to the account, only the primary can do this command :param account_id: int of the account_id for the account :retu...
StarcoderdataPython
332740
import pandas as pd from my_functions import drawAll, transformLine, predict from sympy.geometry import Point, Line from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split import progressbar # Set the learning rate and the number of iterations learning_rate = 0.01 nb_epochs...
StarcoderdataPython
3323633
<reponame>koliupy/loldib<gh_stars>0 from getratings.models.ratings import Ratings class NA_Pantheon_Top_Aatrox(Ratings): pass class NA_Pantheon_Top_Ahri(Ratings): pass class NA_Pantheon_Top_Akali(Ratings): pass class NA_Pantheon_Top_Alistar(Ratings): pass class NA_Pantheon_Top_Amumu(Ratings): p...
StarcoderdataPython
101155
import json my_data = { 'device_name': 'rtr1', 'ip_addr': '10.1.1.1', 'username': 'admin', 'password': '<PASSWORD>', } some_list = list(range(10)) my_data['some_list'] = some_list my_data['null_value'] = None my_data['a_bool'] = False #print() #print(some_list) #print() #print(my_data) filename = "...
StarcoderdataPython
6644398
import csv from .importer import Importer from pathlib import Path class CsvImporter(Importer): extension = "*.csv" def import_file(self, filePath): tableName = Path(filePath).stem with open(filePath, newline='') as file: reader = csv.reader(file) columnNames ...
StarcoderdataPython
251366
<reponame>real-digital/esque from typing import Optional import click from esque.cli.options import State, default_options from esque.io.pipeline import PipelineBuilder @click.command("io") @click.option("-i", "--input-uri", help="Input URI", metavar="<input_uri>", required=True) @click.option( "-o", "--output-...
StarcoderdataPython
4865979
<reponame>suminb/korbit from sqlalchemy import Column, Integer, String, DateTime, Numeric, Text from sqlalchemy import create_engine from sqlalchemy import desc from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import IntegrityError from datetime import...
StarcoderdataPython
139513
import logging import time import unittest from multiprocessing import Process from os import kill import snap7 from snap7.server import mainloop logging.basicConfig(level=logging.WARNING) ip = '127.0.0.1' tcpport = 1102 db_number = 1 rack = 1 slot = 1 class TestClient(unittest.TestCase): @classmethod def...
StarcoderdataPython
5093013
<filename>terraform_compliance/steps/steps.py # -*- coding: utf-8 -*- from radish import step, world, custom_type, given, when, then from terraform_compliance.steps import resource_name, encryption_property from terraform_compliance.common.helper import check_sg_rules from terraform_compliance.common.pyhcl_helper impo...
StarcoderdataPython
3302504
<reponame>joaovictor-loureiro/data-science # Exercício 9.5 Crie um programa que inverta a ordem das linhas do arquivo pares. # txt. A primeira linha deve conter o maior número; e a última, o menor. try: arquivo = open('numeros_pares.txt', 'r') numeros = [] for n in arquivo.readlines(): numeros.ap...
StarcoderdataPython
3485936
import pytest import pandas_gbq import pandas as pd from lkmltools.updater.bq_definitions_provider import BqDefinitionsProvider def test_get_definitions(monkeypatch): config = {"definitions": {"project": "myproject", "query": "select * from mytable"}} reader = BqDefinitionsProvider(config) def fake_df(q,...
StarcoderdataPython
134441
<reponame>SamuelePilleri/plaso #!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Microsoft IIS log file event formatter.""" from __future__ import unicode_literals import unittest from plaso.formatters import iis from tests.formatters import test_lib class IISLogFileEventFormatterTest(test_lib.EventF...
StarcoderdataPython
6490720
<gh_stars>100-1000 # # Copyright 2019 <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # This file is part of acados. # # The 2-Clause BSD License # # Redistribution and use in source and binary forms, with or without # modification, ...
StarcoderdataPython
11284037
<gh_stars>1-10 from channels.routing import route from channels import include from mainapp.consumers import chat_connect, chat_disconnect, chat_receive, scrollback_connect, scrollback_disconnect, scrollback_receive chat_routing = [ route("websocket.connect", chat_connect), route("websocket.receive", chat_rece...
StarcoderdataPython
3281801
<filename>src/fogtools/processing/dlabi.py """For downloading ABI """ import argparse import pandas from .. import abi from sattools import log def get_parser(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add...
StarcoderdataPython
4876995
<gh_stars>0 import unittest from pycq.expando import Expando class ExpandoObject(unittest.TestCase): def test_creation(self): obj = Expando(attr1=5, attr2=8) self.assertEqual(5, obj.attr1) self.assertEqual(8, obj.attr2) def test_setting_attribute(self): obj = Expando(attr1=5...
StarcoderdataPython
231727
<filename>trphysx/transformer/attention.py """ ===== Distributed by: <NAME> SCAI Lab (MIT Liscense) - Associated publication: url: https://arxiv.org/abs/2010.03957 doi: github: https://github.com/zabaras/transformer-physx ===== """ import torch import torch.nn as nn from typing import List from .utils import Conv1D fr...
StarcoderdataPython
3568707
from django.utils.encoding import force_str from rest_framework.metadata import SimpleMetadata from netbox.api import ContentTypeField class ContentTypeMetadata(SimpleMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if hasattr(field, 'queryset') and not fiel...
StarcoderdataPython
11294860
# -*- coding: utf-8 -*- from typing import Any, Dict, List, Union, cast from uuid import UUID from eventsourcing.application import Application, ProcessingEvent from eventsourcing.domain import Aggregate, AggregateEvent, LogEvent from eventsourcing.persistence import Recording from albert_demo.domainmodel import Task...
StarcoderdataPython
11311500
from markupsafe import escape from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/hello') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name) @app.route('/user/<username>') def show...
StarcoderdataPython
1666377
from web3.auto import Web3 import time import requests import json def create_ocean_request(query): pass def process_response(response,command): pass def prepare_tx(fun): nonce = w3.eth.getTransactionCount(account.address) query_txn = fun.buildTransaction({ 'gas': 300000, ...
StarcoderdataPython
8128050
# reversi software import subprocess from time import sleep hw = 8 dy = [0, 1, 0, -1, 1, 1, -1, -1] dx = [1, 0, -1, 0, 1, -1, 1, -1] def empty(grid, y, x): return grid[y][x] == -1 or grid[y][x] == 2 def inside(y, x): return 0 <= y < hw and 0 <= x < hw def check(grid, player, y, x): res_grid = [[False...
StarcoderdataPython
12850113
""" stanCode Breakout Project Adapted from <NAME>'s Breakout by <NAME>, <NAME>, <NAME>, and <NAME> YOUR DESCRIPTION HERE """ from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GOval, GRect, GLabel from campy.gui.events.mouse import onmouseclicked, onmousemoved import random # constant BRIC...
StarcoderdataPython
9690711
<gh_stars>0 # This file is part of the Indico plugins. # Copyright (C) 2002 - 2019 CERN # # The Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; # see the LICENSE file for more details. from __future__ import unicode_literals from indico.core.plugins...
StarcoderdataPython
6697427
<gh_stars>1-10 import threading import time import datetime import csv WRITE_MODE = 'w' # 'w' for overwrite, 'a' for append # -----Description----- # This is a threaded class that writes data # to a CSV file every self.writeInterval seconds. # --------------------- class writer(threading.Thread): # Specify ...
StarcoderdataPython
1942302
<reponame>luciantin/prometheus-sidecart-reporter from prometheus_client import Counter, Gauge from prometheus_client import start_http_server import dpkt, pcap, datetime from dpkt.utils import mac_to_str, inet_to_str import subprocess, os, signal import time import socket, requests, json, datetime, pytz # start pro...
StarcoderdataPython
6563879
<filename>src/repository/history_repository.py<gh_stars>0 """ Repository to handle the games watched or played """ from src.repository.abstract_repository import AbstractRepository from src.entity.history import History class HistoryRepository(AbstractRepository): """ Another useless comment """ def get_all(s...
StarcoderdataPython
6479421
import time from unittest.mock import MagicMock import pytest from tkinter import Frame from freezegun import freeze_time from graphics.themes import Theme, DarkTheme from data.observable import Observable from drivers.driver_factory import DriverFactory from graphics.snackbar.recalibration_snackbar import Recalibrat...
StarcoderdataPython
6572001
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt movies_df = pd.read_csv('data.csv') def Distribution_of_Studio_names_BY_Ali(): movies_df = pd.read_csv('data.csv') a = plt.cm.Wistia plt.figure(figsize=(10,5)) count = movies_df['production_company'].value_...
StarcoderdataPython
12838746
<filename>nautobot/extras/admin.py from db_file_storage.form_widgets import DBAdminClearableFileInput from django import forms from django.contrib import admin, messages from django.db import transaction from django.db.models import ProtectedError from .models import CustomField, CustomFieldChoice, FileProxy, JobResul...
StarcoderdataPython
235808
<reponame>demilletech/jwaax-flask<filename>dt_auth/auth_jwaax_provider.py # TBW # This will read the config file and get the stuff import calendar import time import requests import jwt import json __pubkey = [""] __prikey = [""] __domain = [""] __indrak = [""] __stinfo = [{}] def get_site_info(): if __stinfo[0...
StarcoderdataPython
368572
<filename>3/benchmarks.py import numpy as np def griewank(P): return ( 1 + (P**2).sum(axis=1) / 4000 - np.prod( np.cos( P/np.sqrt( np.arange(1, P.shape[-1] + 1) ) ), axis=1 ) ) def rast(P)...
StarcoderdataPython
6488423
import sys from collections import defaultdict n = int(sys.stdin.readline()) d = defaultdict(set) y_list = set() for i in range(n): x, y = list(map(int, (sys.stdin.readline()[:-1]).split(" "))) y_list.add(y) d[y].add(x) for y in sorted(y_list): for x in sorted(d[y]): print(x, y)
StarcoderdataPython
1678450
<filename>Classfication/SVM.py import os import numpy as np import tensorflow as tf tf.python.control_flow_ops = tf import sample_datasets BATCH_SIZE = 100 tf.app.flags.DEFINE_integer('num_epochs', 100, 'Number of training epochs.') tf.app.flags.DEFINE_float('svmC', 1, 'The C parameter of the SVM cost function.') tf...
StarcoderdataPython
123155
import numpy as np import pylab as pl from peri.test import init crbs = [] rads = np.arange(1, 10, 1./5) rads = np.linspace(1, 10, 39) rads = np.logspace(0, 1, 50) s = init.create_single_particle_state(imsize=64, radius=1, sigma=0.05) blocks = s.blocks_particle(0) for rad in rads: print "Radius", rad s.upda...
StarcoderdataPython
5186240
import datetime import re from datetime import datetime import requests from bs4 import BeautifulSoup from scrape.data import GameInformations, GameScore def scrape_game_informations(url: str): if url.__contains__("flashscore.de"): return scrape_game_informations_flashscore(url) if url.__contains__(...
StarcoderdataPython
225406
""" @Time : 2019-1-19 03:08 @Author : TaylorMei @Email : <EMAIL> @Project : iccv @File : base7.py @Function: """ import torch import torch.nn.functional as F from torch import nn from backbone.resnext.resnext101_regular import ResNeXt101 ###################################################...
StarcoderdataPython
97489
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- def neo_2_profile_to_neo_rt_profile(input_neo2_profile_name: str, input_neo2_outputfile_name: str, s_min: float, s_max: float, number_s_points: int): """ input: ------ input_neo2_profile_name: string name of the profile file of neo-2 to be used...
StarcoderdataPython
5034204
<reponame>beshoyAtefZaki/applications<gh_stars>0 from __future__ import unicode_literals from frappe import _ from frappe.desk.moduleview import add_setup_section def get_data(): data =[ { "label": _("Settings"), "icon": "fa fa-wrench", "items": [ { "type": "doctype", "name": "E...
StarcoderdataPython