id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1785401
import dash from dash.exceptions import PreventUpdate import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_bootstrap_components as dbc import utils.dash_reusable_components as drc import dash_table import plotly.express as ex import plotl...
StarcoderdataPython
13757
# coding = utf-8 from abc import ABCMeta, abstractmethod import torch from Putil.torch.indicator.vision.object_detection import box ##@brief 计算iou # @note # @return def _iou(x11, y11, x12, y12, x21, y21, x22, y22): cap, cup = box._cap_cup(x11, y11, x12, y12, x21, y21, x22, y22) return cap / cup def _cap_cup_...
StarcoderdataPython
9638
import os from glob import iglob from concurrent.futures import ThreadPoolExecutor def count_words_file(path): if not os.path.isfile(path): return 0 with open(path) as file: return sum(len(line.split()) for line in file) def count_words_sequential(pattern): return sum(map(count_words_fil...
StarcoderdataPython
3369769
"""itch50_order_event_recorder.py: Order event recorder class for ITCH 5.0""" __author__ = "<NAME>" __email__ = "<EMAIL>" from meatpy.market_event_handler import MarketEventHandler from meatpy.itch50.itch50_market_message import * class ITCH50OrderEventRecorder(MarketEventHandler): def __init__(self): ...
StarcoderdataPython
1644477
""" eletronic structure routines modules """ import sys import importlib import autofile import automol import elstruct from mechanalyzer.inf import thy as tinfo from mechanalyzer.inf import rxn as rinfo from mechanalyzer.inf import spc as sinfo from mechroutines.es._ts import findts from mechroutines.es._routines imp...
StarcoderdataPython
3386582
<filename>azure/durable_functions/models/OrchestratorState.py<gh_stars>1-10 import json from typing import List, Any, Dict class OrchestratorState: def __init__(self, isDone: bool, actions: List[List[Any]], output: Any, error: str = None, ...
StarcoderdataPython
3392536
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import pickle import pandas as pd import os from cgp import * from cgp_config import * from cnn_train import CNN_train if __name__ == '__main__': parser = argparse.ArgumentParser(description='Evolving CAE structures') parser.add_argument('--gpu_n...
StarcoderdataPython
1731768
import json import pandas as pd import csv NUM_PLAYER_LIST = ["6p", "9p"] def transformHand(handsStr): handList = handsStr.split(",") hand1 = handList[0].strip() hand2 = handList[1].strip() hand1Num = hand1[0] hand1Suit = hand1[1] hand2Num = hand2[0] hand2Suit = hand2[1] # Data is ...
StarcoderdataPython
3264781
from grid import Grid import os ''' data = [ '5483143223', '2745854711', '5264556173', '6141336146', '6357385478', '4167524645', '2176841721', '6882881134', '4846848554', '5283751526' ] grid = Grid.create_from_lines(data) while grid.last_flashed_cells_count != (grid.width * grid.height): grid.tick() print(grid....
StarcoderdataPython
3324542
"""Management utilities.""" from fabric.contrib.console import confirm from fabric.api import abort, env, local, settings, task, sudo, cd, lcd, put, run, prefix, get from fabric.contrib.files import exists from etapi.settings import ProdConfig ########## CONFIG local_app_dir = '.' local_config_dir = './config' r...
StarcoderdataPython
1641841
<reponame>bossm0n5t3r/BOJ import sys def sol(): # 데이터 받기 input = sys.stdin.readline board = [list(map(int, input().split())) for _ in range(5)] checked = [[False] * 5 for _ in range(5)] calling_numbers = [] for _ in range(5): calling_numbers += list(map(int, input().split())) # map...
StarcoderdataPython
1756618
<gh_stars>1-10 from dvc.dependency.base import DependencyBase from dvc.output.hdfs import OutputHDFS class DependencyHDFS(DependencyBase, OutputHDFS): pass
StarcoderdataPython
134232
<gh_stars>1-10 """This module will contain class Hash and its related methods.""" from ..repeated_word import Hash import pytest def test_class_exist(): """To test that the class Graph exists.""" assert Hash def test_str_method_empty(): """To test the output of str method.""" h = Hash() assert s...
StarcoderdataPython
135444
<filename>Code/Engine/events.py import pygame from ..constants import * def blit_request(rect, p_surf): signal = pygame.event.Event(update_screen_event, {"rect":rect,"surf":p_surf}) pygame.event.post(signal) def func_request(func): stype = func.pop(0) f = func.pop(0) if stype == ONETIME: ...
StarcoderdataPython
4813840
medida = float(input('Qual o valor em metros: ')) cm = float(medida*100) mm = float(medida*1000) km = float(medida/1000) print('{} metros: \n{:.3f} cm \n{:.3f} mm\n{:.3f} km'.format(medida, cm, mm, km)) '''medida = float(input('qual a distancia em metros:')) cm = medida * 100 mm = medida * 1000 km = medida / 1000 pri...
StarcoderdataPython
4804740
<filename>python/2018.11.25PythonTrain/linear.py import numpy as np import matplotlib.pyplot as plt # 数据可视化 from model import Linear, Multinomial def load_data(): # path = "./data/linear_data.txt" path = "./data/temperature.txt" raw_data = open(path).read().split(",") int_data = np.array(raw_data, dtyp...
StarcoderdataPython
3314766
from fastapi import APIRouter, Body from controllers.pweets_controller import createPweet, readPweet from playhouse.shortcuts import model_to_dict router = APIRouter( prefix="/pweets", tags=["pweets"] ) @router.post('/create') async def create_pweet(request: dict = Body): payload = request data = await...
StarcoderdataPython
1750385
from gii.core import * from gii.core.model import * from gii.qt.helpers import repolishWidget import json from PropertyEditor import FieldEditor, registerSimpleFieldEditorFactory from SearchFieldEditor import SearchFieldEditorBase import os.path ##----------------------------------------------------------------##...
StarcoderdataPython
166284
<gh_stars>1-10 from PreprocessData.all_class_files.StructuredValue import StructuredValue import global_data class ContactPoint(StructuredValue): def __init__(self, additionalType=None, alternateName=None, description=None, disambiguatingDescription=None, identifier=None, image=None, mainEntityOfPage=None, n...
StarcoderdataPython
3335337
<gh_stars>1-10 # -*- coding: utf-8 -*- import xbmc, xbmcgui, xbmcplugin, xbmcaddon, urllib2, urllib, re, string, sys, os, zlib from uuid import uuid4 from random import random,randint from math import floor import hashlib import time import simplejson # Plugin constants __addonname__ = "奇艺视频(QIYI)" __addonid__ = "p...
StarcoderdataPython
4817283
<reponame>292916808/MolCloze<filename>bert/model/embedding/segment.py # !/usr/bin/env python # -*- coding: utf-8 -*- # author: chinshin # datetime: 2020/4/20 15:38 import torch.nn as nn class SegmentEmbedding(nn.Embedding): def __init__(self, embed_size=512): super(SegmentEmbedding, self).__init_...
StarcoderdataPython
1773793
<filename>petisco/base/domain/errors/default_http_error_map.py from petisco.base.domain.errors.domain_error import DomainError from petisco.base.domain.errors.defaults.invalid_value_object import InvalidValueObject from petisco.base.application.controller.http_error import HttpError from petisco.base.domain.errors.def...
StarcoderdataPython
1780077
import numpy as np Imat = np.eye(2) def x_(nqubits, index): """Create an X gate Args: nqubits (int): The number of qubits on a quantum circuit index (int): The index of a qubit that a gate is applied Returns: ndarray : The matrix of an X gate """ matrix = 1 X = np.arra...
StarcoderdataPython
159986
<reponame>jphuart/swatplus-automatic-workflow from peewee import * from .base import OutputBase, BaseModel class Reservoir(OutputBase): area = DoubleField(null=True) precip = DoubleField(null=True) evap = DoubleField(null=True) seep = DoubleField(null=True) flo_stor = DoubleField(null=True) sed_stor = DoubleFie...
StarcoderdataPython
1778222
<reponame>Alex-Greenen/SpectralNeuralAnimation # process data from ProcessData.ProcessData import ProcessData import os # Clear filelist = [ f for f in os.listdir('TrainingData') ] for f in filelist: os.remove(os.path.join('TrainingData', f)) filelist = [ f for f in os.listdir('ValidationData') ] for f in filelist: os...
StarcoderdataPython
1675175
import pytest from olympus.router import UniswapV2Router02 from olympus.consts import ZERO_ACCOUNT class AccountWithClashingNameSpace(UniswapV2Router02): # Router has an on-chain function with this name def WETH(self): pass def test_clashing_namespace_warns(): with pytest.warns( UserWarn...
StarcoderdataPython
3316899
#!/usr/bin/env python3 from Utils import * if __name__ == "__main__": # Your code here! limit = 1000000 for i in range(1, limit): baseSet = set(list(str(i))) okay = True for prefix in range(2, 6 + 1): compareSet = set(list(str(prefix * i))) if not baseSet =...
StarcoderdataPython
3297570
<reponame>Tyler887/console-menu<filename>consolemenu/format/menu_margins.py class MenuMargins(object): """ Class for menu margins. A margin is the area between the maximum specified dimensions (which is usually the width and height of the screen) and the menu border. Args: top (int): The top ma...
StarcoderdataPython
3253905
# -*- coding: utf-8 -*- import os import json import time import urllib import re from bs4 import BeautifulSoup import socks import socket socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 1080) socket.socket = socks.socksocket import requests g_userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit...
StarcoderdataPython
3358052
<reponame>KoalaV2/lifxcli #!/usr/bin/env python3 # coding=utf-8 import sys from lifxlan import BLUE, CYAN, GREEN, LifxLAN, ORANGE, PINK, PURPLE, RED, YELLOW, COLD_WHITE, WARM_WHITE, GOLD def main(color): print("Discovering lights...") lifx = LifxLAN(1) devices = lifx.get_lights() print(f"Found ligh...
StarcoderdataPython
1660600
<filename>tests/unit/seed_tree.py """This gathers information about the random number generator function so that it can be seeded to give any particular series of virtual coin tosses up to a certain length. """ import random FAIR_COIN = lambda: random.randint(0, 1) RANDOM_SEED = random.seed def has_all_sequences(seed...
StarcoderdataPython
1756240
import re import forge # pylint: disable=C0103, invalid-name # pylint: disable=R0201, no-self-use def test_namespace(): """ Keep the namespace clean """ private_ptn = re.compile(r'^\_[a-zA-Z]') assert set(filter(private_ptn.match, forge.__dict__.keys())) == set([ '_config', '_cou...
StarcoderdataPython
9926
# -*- coding: utf-8 -*- import pytest from mock import Mock from bravado_core.exception import SwaggerMappingError from bravado_core.operation import Operation from bravado_core.param import get_param_type_spec from bravado_core.param import Param from bravado_core.spec import Spec @pytest.fixture def body_param_spe...
StarcoderdataPython
95409
import logging from argparse import ArgumentParser, Namespace from pathlib import Path import torch from torch.utils.data import DataLoader from pytorch_lightning import Trainer from module import ConditionalLM logging.basicConfig(level=logging.INFO) def main(args: Namespace): model = ConditionalLM.load_from_c...
StarcoderdataPython
1649405
<gh_stars>0 from datetime import datetime from flask_jwt_extended import get_jwt_identity from database_handler import DbConn from src.users.controller import ( conn, cur) class CourseController: """Course controller interfaces with the database.""" def __init__(self): """Initializes the user contr...
StarcoderdataPython
65233
<gh_stars>10-100 from sanic import Blueprint api_v1 = Blueprint(__name__, None) @api_v1.middleware(attach_to="request") async def bp_mw(request): print("Hello bp") __all__ = ['api_v1']
StarcoderdataPython
93100
import ctypes import json import html2text import logging import pprint import random import requests import sys import time import traceback from DDPClient import DDPClient from multiprocessing import Manager from multiprocessing.dummy import Process from six.moves.urllib import parse from will import settings from ...
StarcoderdataPython
3344331
print("Programa em python para calcular o exercicio 30 da lista.") print("<NAME>") print("675263") print("Arquitetura de Computador II") print("Professor: <NAME>") print()#pular uma linha #Funcoes do programa def menu_func(): print("""Exercicio 30 Opções: (1) = Qual o CPI médio da máquina? (2) = Suponha um Over...
StarcoderdataPython
4840461
<gh_stars>0 from .bin_pal_acs import BinaryPAL_ACS_Sampler from .bin_redistricting import BinaryRedistrictingSampler from .perfect_info import PIUSampler from .random import RandomSampler
StarcoderdataPython
3392534
import hashlib import hmac import time import requests import json from enum import Enum from datetime import timedelta, datetime class CandleInterval(Enum): MINUTE_1 = timedelta(minutes=1) MINUTE_5 = timedelta(minutes=5) HOUR_1 = timedelta(hours=1) DAY_1 = timedelta(days=1) valid_times = 'FILL_OR_K...
StarcoderdataPython
1710393
#!/usr/bin/python # # Copyright 2019 dataJAR Ltd, # # # 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 o...
StarcoderdataPython
1751488
<gh_stars>10-100 from bs4 import BeautifulSoup import time import asyncio import aiohttp from helper.asyncioPoliciesFix import decorator_asyncio_fix import re from helper.html_scraper import Scraper class Bitsearch: def __init__(self): self.BASE_URL = 'https://bitsearch.to' self.LIMIT = None ...
StarcoderdataPython
5583
<reponame>ruohoruotsi/pyACA<filename>pyACA/ToolFreq2Bark.py<gh_stars>10-100 # -*- coding: utf-8 -*- """ helper function: convert Hz to Bark scale Args: fInHz: The frequency to be converted, can be scalar or vector cModel: The name of the model ('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller') ...
StarcoderdataPython
42143
from __future__ import absolute_import, unicode_literals from django.core.management.base import BaseCommand from molo.core.models import ArticlePage class Command(BaseCommand): def handle(self, **options): ArticlePage.objects.all().update( featured_in_latest=False, featured_in_la...
StarcoderdataPython
3214224
<reponame>zeou1/maggot_models<filename>notebooks/114.0-BDP-flow-revisited.py # %% [markdown] # ## from src.hierarchy import signal_flow from src.data import load_metagraph from src.visualization import matrixplot from src.visualization import CLASS_COLOR_DICT from src.io import savefig import os from src.graph import p...
StarcoderdataPython
1649097
import streamlit as st import pandas as pd from modules import (ensemble, utility) import warnings from PIL import Image import plotly.figure_factory as ff warnings.filterwarnings('ignore') ############################# Initial set up of sidebar and upload st.set_page_config(page_title='Open Source Data Science',...
StarcoderdataPython
3375096
import copy import torch from torch import nn from .pe import PositionalEncoding from .encoder_layer import EncoderLayer device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def get_padding_mask(seq: torch.Tensor, pad_idx: int = 0) -> torch.Tensor: """ Mask tokens that are pads (not pad: 1, ...
StarcoderdataPython
1649665
<gh_stars>10-100 from django.apps import AppConfig class VisionBackendConfig(AppConfig): name = 'vision_backend'
StarcoderdataPython
4832049
def html2text(val: str) -> str: ...
StarcoderdataPython
1670718
<reponame>OptMLGroup/DeepBeerInventory-RL from __future__ import print_function from clBeergame import * from utilities import * import numpy as np #from clGeneralParameters import generalParameters import random from config import get_config, update_config import tensorflow as tf config = None #def main(config, be...
StarcoderdataPython
1720954
<gh_stars>0 from preprocess.load_data.data_loader import load_production production_tb = load_production() # 本书刊登内容如下 # 从库中导入SMOTE函数 from imblearn.over_sampling import SMOTE # 设置SMOTE函数参数 # ratio表示的是将不平衡数据中少数类的数据增加至多数类的数据的百分之多少 # (当设置为auto时,表示增加至与多数类的数据量相同;当设置为0.5时,表示增加至50%) # k_neighbors为smote的k参数 # random_state是随机数...
StarcoderdataPython
3278273
<gh_stars>1-10 # -*- coding: utf-8 -*- # @Author: rjezequel # @Date: 2019-12-20 09:18:14 # @Last Modified by: ronanjs # @Last Modified time: 2020-02-07 11:05:55 try: from ansible.module_utils.logger import Logger except ImportError: from module_utils.logger import Logger import requests import pickle impo...
StarcoderdataPython
137841
<gh_stars>1-10 from datastore.shared.util import ( collection_and_id_from_fqid, collection_from_collectionfield, collection_from_fqid, collectionfield_and_fqid_from_fqfield, collectionfield_from_fqid_and_field, field_from_collectionfield, fqfield_from_fqid_and_field, fqid_from_collection...
StarcoderdataPython
3337206
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # <NAME>, U.S. Geological Survey # <NAME>, GNS Science # <NAME>, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) ...
StarcoderdataPython
74710
<filename>stub/py/v2s/scene.py<gh_stars>1-10 import json import redis from util import timed from k8s import update_status # singleton redis client _r = redis.StrictRedis(host="localhost") class SceneStatus: """ Schema and client to scene status. Attributes: self.put(): commit the scene object to s...
StarcoderdataPython
1653362
<filename>scripts/hookup.py #! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2019 the HERA Collaboration # Licensed under the 2-clause BSD license. """ Allows various views on the antenna hookup, as well as handle the hookup cache file. """ from hera_mc import mc, cm_hookup, cm_utils if __na...
StarcoderdataPython
120745
#!/usr/bin/env python """Populate GitHub labels for issue tracker.""" from collections import namedtuple import codecs import yaml import json import sys import os import re import requests import urllib.parse try: from yaml import CLoader as Loader except ImportError: from yaml import Loader __version__ = "1....
StarcoderdataPython
1769698
<gh_stars>0 import base64 import sys with open(sys.argv[1], 'r') as file: data = file.read() for i in range (0, 50): data = base64.b64decode(data) print(data) file.close()
StarcoderdataPython
112505
<reponame>dkirkby/desietcimg """General purpose utilities for imaging analysis. """ import os import re import pathlib import logging import numpy as np import scipy.signal import scipy.stats import scipy.ndimage import fitsio def downsample(data, downsampling, summary=np.sum, allow_trim=False): """Downsample ...
StarcoderdataPython
3274008
<filename>custom_components/purpleair/const.py # pylint: disable=unexpected-keyword-arg """Constants for the Purple Air integration.""" from __future__ import annotations from typing import Final from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT from homeassistant.const import ( CONCENTRATION_MI...
StarcoderdataPython
1767004
<filename>src/scripts/ComputeNorms.py """The WaveBlocks Project Calculate the norms of the different wave packets as well as the sum of all norms. @author: <NAME> @copyright: Copyright (C) 2010, 2011 <NAME> @license: Modified BSD License """ import sys from WaveBlocks import IOManager if __name__ == "__main__": ...
StarcoderdataPython
1783654
# Generated by Django 2.2.4 on 2021-12-01 22:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('submissions', '0010_conf_slug_to_fk_data'), ] operations = [ migrations.RemoveField( model_name='panel', name='conference', ...
StarcoderdataPython
4814331
<reponame>directed-graph/symfs # This library should import all extension protos used by symfs. from types import ModuleType from typing import Any, Callable, Iterable, Iterator, Optional, Union import pathlib from absl import logging from google.protobuf import any_pb2 from google.protobuf import message try: fr...
StarcoderdataPython
4841497
<reponame>INK-USC/LEAN-LIFE no_anchor_word_templates = [ "The word '____' appears in the text", "The phrase '____' appears in the text" ] # REPLACE is automatically replaced in the prompt by either a choice of anchor words if 2 are present, # or by a single anchor word if only one is present one_anchor_word_t...
StarcoderdataPython
3334694
##Citation: https://pythonprogramming.net/combine-classifier-algorithms-nltk-tutorial/?completed=/sklearn-scikit-learn-nltk-tutorial/ import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import nltk.classify.util as util from nltk.classify import NaiveBayesClassifier from nltk.metrics ...
StarcoderdataPython
3357289
""" RenderPipeline Copyright (c) 2014-2016 tobspr <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
StarcoderdataPython
1792691
import telnetlib, re # for validating an Ip-address regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$''' def check(Ip): return re.search(regex, Ip) ...
StarcoderdataPython
4945
""" transforms.py is for shape-preserving functions. """ import numpy as np def shift(values: np.ndarray, periods: int, axis: int, fill_value) -> np.ndarray: new_values = values if periods == 0 or values.size == 0: return new_values.copy() # make sure array sent to np.roll is c_con...
StarcoderdataPython
3377375
<reponame>ualbertabiomed/exo_controller import abc import rospy """ base class for all ALEX ROS nodes """ class ALEXNode(abc, metaclass=abc.ABCMeta): # one callback per node? """ initialize ROS node name: name of the ROS (ALEX) node """ def __init__(self, name): self.name...
StarcoderdataPython
185965
from PyQt5.QtGui import QMatrix4x4, QVector3D import math __all__ = ['ortho_look_at', 'isometric_projection', 'sphere2cart', 'cart2sphere'] def isometric_projection() -> QMatrix4x4: """ Return the isometric perspective projection matrix :return: """ return ortho_look_at(1, 1, 1, ...
StarcoderdataPython
97735
import os from tweepy.auth import OAuthHandler from tweepy.api import API from dotenv import load_dotenv load_dotenv(verbose=True) class TweepyAuth: """ class used to handle app authentication """ consumer_key = os.getenv("API_KEY") consumer_secret = os.getenv("API_SECRET_KEY") access_token = ...
StarcoderdataPython
85223
<reponame>D-PLACE/dplace<filename>dplace_app/loader/glottocode.py # -*- coding: utf-8 -*- import logging from dplace_app.models import Language, LanguageFamily, Society def load_languages(repos): languoids = { l.id: l for l in repos.read_csv('csv', 'glottolog.csv', namedtuples=True)} families, langua...
StarcoderdataPython
62675
<reponame>mitou38/Test-FastAPI<filename>app/api/utils.py<gh_stars>0 import concurrent.futures as futures from typing import Optional, Dict, Any, Type, TypeVar, List from pydantic import BaseModel from api.api_v1.models.tortoise import Person from api.api_v1.storage.initial_data import INIT_DATA ORDERS: Dict[str, str...
StarcoderdataPython
3331895
S = int(input()) # number of stones in heap N = int(input()) # min number of stones in heap, when game ends # player is allowed to do +1, +3 or x2 Plus = [1, 3] Mul = [2] def winner(s, n): win_loose = [-1] * n win_loose[n - 1] = 0 for i in range(n - 2, s - 2, -1): flag = False for k in P...
StarcoderdataPython
50260
<filename>elephant/ref.py import bson import elephant.util class DocRef: @classmethod async def decode(cls, h, args): args = await h.decode(args) return DocRef(*args) def __init__(self, _id, ref=None): if not isinstance(_id, bson.objectid.ObjectId): raise TypeError() if not...
StarcoderdataPython
3364441
<reponame>captainTOKIO/Premchand_Aug2022_fullstack_august_python1 from django.contrib import admin from . models import problem_model # Register your models here. admin.site.register(problem_model)
StarcoderdataPython
1691345
# Generated by Django 2.2.3 on 2019-07-26 23:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
StarcoderdataPython
1776778
#!/usr/bin/python import operator import sys import re import string import os famr = open(sys.argv[1]) fwiki = open(sys.argv[2]) # FIXME: External dependency ftrn = open("/dccstor/multi-parse/amr/trn.wikis") wiki_ht = {} for line in ftrn: if len(line.strip().split('\t')) != 2: continue (n,w) = line.s...
StarcoderdataPython
3227642
from django import forms from notes.demo_web.models import Profile, Note class CreateProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' class CreateNoteForm(forms.ModelForm): class Meta: model = Note fields = '__all__' class EditNoteForm(forms.Mod...
StarcoderdataPython
3298318
<filename>robustness_metrics/projects/revisiting_calibration/figures/imagenet_c.py # coding=utf-8 # Copyright 2021 The Robustness Metrics Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License...
StarcoderdataPython
3394701
<reponame>streampulse/sp from builtins import str from builtins import range import os from functools import reduce #see usgs_sync_setup #import setup and helper funcs app_dir = '/home/aaron/sp' # app_dir = '/home/mike/git/streampulse/server_copy/sp' wrk_dir = app_dir + '/scheduled_scripts/USGS_data_retrieval' os.chd...
StarcoderdataPython
1731675
<filename>bigstream/deform.py<gh_stars>0 import numpy as np import greedypy.greedypy_registration_method as gprm from bigstream import stitch from bigstream import transform import dask.array as da import zarr from numcodecs import Blosc from itertools import product import ClusterWrap WORKER_BUFFER = 8 def deformab...
StarcoderdataPython
3300686
############################################################################### ## ## Copyright 2012 Tavendo GmbH ## ## 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...
StarcoderdataPython
1796966
<filename>pythonProject/MUNDO 3/Aula 21.py<gh_stars>0 print(""" COMANDO HELP(): Pode ser digitado no "Python console", no qual, posteriormente, será colocado o da função que se deseja ter informação. OU pode ser digitado no próprio IDLE da seguinte maneira: help(nome da função) por exemplo: help( print), irá nos dar ...
StarcoderdataPython
1772115
import logging import re import sys import cmdln from project.lib.csv_celery_generator import CsvCeleryGenerator from project.lib.csv_generator import CsvGenerator from project.lib.csv_mp_generator import CsvMpGenerator from project.lib.csv_rx_generator import CsvRxGenerator from project.lib.utils import Utils loggi...
StarcoderdataPython
3274127
<reponame>mrtopf/camper #encoding=utf8 from starflyer import Handler, redirect, asjson from camper import BaseForm, db, BaseHandler, is_admin, logged_in, ensure_barcamp from .base import BarcampBaseHandler, LocationNotFound from wtforms import * from sfext.babel import T import uuid import pprint import datetime impor...
StarcoderdataPython
44628
# Raincoat: pypi package: raincoat==0.1.4 path: raincoat/_acceptance_test.py # noqa
StarcoderdataPython
3201777
#!/usr/bin/python # -*- coding: utf-8 -*- # cython: language_level=3 """ MIT License Copyright (c) 2021-present, Pelfox. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, inclu...
StarcoderdataPython
3237585
import torch from torch import nn, autograd from torch.utils.data import DataLoader, Dataset import numpy as np import random from sklearn import metrics from torch import nn import torch.nn.functional as F import torchtext def evaluate_validation(scores, loss_function, gold): guesses = scores.argmax(dim=1) n_...
StarcoderdataPython
3335514
# Author: <NAME> # License: MIT # Version: 0.1.0 """ Part of VISFBPIC. Contains an example plasma density profile method. """ import numpy as np from scipy.constants import pi def number_density(z): '''For a given value of z-position, return number density n.''' n0 = 1.0e24 ramp_length = 100e-6 platea...
StarcoderdataPython
3255904
<reponame>Blow0/HackerRank-Python-Solutions List = [] n = int(input()) for i in range(n): operation, *parse = input().split() parse = list(map(int, parse)) if(operation == "remove"): List.remove(parse[0]) elif(operation == "pop"): List.pop() elif(operation == "sort"): List.s...
StarcoderdataPython
185300
# Generated by Django 3.1 on 2020-09-16 21:43 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
StarcoderdataPython
14835
from __future__ import absolute_import from __future__ import division from __future__ import print_function import _thread import sys import time from math import exp from random import random from typing import List, Tuple, Set from scipy import spatial import numpy as np import torch from torch import nn from torc...
StarcoderdataPython
159429
# https://www.hackerrank.com/challenges/common-child/problem def longestCommonSubsequence(s1, s2): remove_element = set(s1) - set(s2) new_s1 = "" for element in s1: if element not in remove_element: new_s1 += element s1 = new_s1 memory = [[0] * (len(s2) + 1) for _ in range((le...
StarcoderdataPython
152145
<filename>main.py<gh_stars>1-10 import argparse import os import re import sys from datetime import datetime from re import Pattern from typing import List, Dict, Any, TypeVar, Generator # https://regex101.com/r/sbHlJ5/2. from jinja2 import Template _DOMAIN_REGEX: str = r"^[^:\/@]+\.[^:\/@]+$" _FILE_PATH: str = "doma...
StarcoderdataPython
1703248
<reponame>gregsherrid/earth-spacetime-sampling from text_to_float import text_to_float from sample_from_time import sample_year from sample_from_globe import sample_lat_long import re from IPython import embed def get_brutus_lines(): with open('./data/brutus.txt', 'r') as f: return f.read().split("\n") ...
StarcoderdataPython
3293675
<gh_stars>1-10 from __future__ import division, print_function, absolute_import from numpy.distutils.core import setup, Extension from numpy.distutils import misc_util as np_misc_util import os, sys, copy, glob import versioneer BASE_PATH = 'gufunctools' VERSION_FILE_PATH = os.path.join(BASE_PATH, '_version.py') ...
StarcoderdataPython
22951
<reponame>matrixorz/firefly # coding=utf-8 DEBUG = True TESTING = True SECRET_KEY = 'secret_key for test' # mongodb MONGODB_SETTINGS = { 'db': 'firefly_test', 'username': '', 'password': '', 'host': '127.0.0.1', 'port': 27017 } # redis cache CACHE_TYPE = 'redis' CACHE_REDIS_HOST = '127.0.0.1' CAC...
StarcoderdataPython
53840
#!/usr/bin/env python """Utility made using the PRAW library to get saved Reddit Submissions from a users account.""" import logging.config import praw import smmry_wrapper from account_info import * logging.basicConfig(filename="app.log", filemode="a", format="%(asctime)s - %(filename)s - %(leve...
StarcoderdataPython
132940
from scipy.misc import imsave import cv2 def blur(ai, output_file=None): """ Create simple FDM. Apply Gaussian blur params=(11,11). """ fdm = cv2.GaussianBlur(ai, (11,11), 0) if output_file is not None: imsave(output_file, fdm) return fdm
StarcoderdataPython