text
string
size
int64
token_count
int64
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os from base import BaseObject from base import CryptoBase from base import FileIO from datadb2.core.dmo import BaseDB2Client class BuildDb2Url(BaseObject): """ Create a DB2 connection """ __config_path = 'resources/config/db2/schemas.yml' def __in...
2,044
629
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Deep Clustering modeller class """ from .. import torch_imported if torch_imported: import torch import torch.nn as nn import numpy as np class TransformerDeepClustering(nn.Module): """ Transformer Class for deep clustering """ def __init__(s...
3,462
1,083
""" 67 - Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo. """ while True: n = int(input('Informe um número para ver sua tabuada: ')) if n < 0: break print('-' * 13) ...
431
162
from django.shortcuts import render from django.http import HttpResponse from .models import Image,Category,Location def gallery_today(request): gallery = Image.objects.all() return render(request, 'all-galleries/today-gallery.html', {"gallery": gallery}) def search_results(request): if 'category' in...
1,569
461
from typing import Dict from StructNoSQL import TableDataModel, BaseField, MapModel class BaseTableModel(TableDataModel): type = BaseField(field_type=str, required=False) fieldOne = BaseField(field_type=str, required=False) fieldTwo = BaseField(field_type=str, required=False) class ContainerModel(MapM...
843
247
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program 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; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
3,301
1,054
# Generated by Django 2.2.5 on 2019-12-14 15:11 import django.utils.timezone from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0009_auto_20191211_2107'), ] operations = [ migrations.RemoveField( model_name='subjec...
1,303
392
# -*- coding=utf-8 -*- import pygame from bf_form import BFForm from bf_button import BFButton from globals import LanguageConfigParser, LanguageLib class SelectLanguageForm(BFForm): def __init__(self, screen, after_close): super(SelectLanguageForm, self).__init__(screen, after_close) def select_langu...
1,666
539
# -*- coding: utf-8 -*- """ Created on Thu Oct 4 14:09:44 2018 @author: VeNoMzZxHD """ import tkinter from tkinter.filedialog import askopenfilename from collections import Counter import re import string #Returns string of text file def readFile(): ''' tkinter.Tk().withdraw() inputfilename = askopenfil...
3,084
974
#!/usr/bin/env python # **************************************** # ############# # IMPORTS # ############# # standard python packages import ConfigParser, copy, inspect, logging, os, sys from Node import Node if not os.path.abspath( __file__ + "/../../../lib/iapyx/src" ) in sys.path : sys.path.append( os.path.ab...
9,826
3,204
from freezegame.sprite import Sprite class Ladder(Sprite): def __init__(self, x, y, state): Sprite.__init__(self, x, y, [0, 0, 32, 32], state, 'tileSet', [0, 160, 32, 32], state.batch, state.ladder_group)
219
98
from django.db import models from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.core.blocks import StructBlock, CharBlock from wagtail.core.fields import StreamField from wagtail.core.models import Page from wagtail.images.edit_handlers import ImageChooserPanel from wagtailmarkdown.block...
2,656
771
from utility.sweetie import serve serve()
44
15
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-atomic-ID-enumeration-5-NS" class NistschemaSvIvAtomicIdEnumeration5Type(Enum): BA = "ba" CA = "ca" EFOR = "efor" HREGISTRY_AS_ON_WORK_U = "hregistry.as.on-work.u" ITS_INCL...
985
360
#!/usr/bin/env python3 # pylint: disable=no-self-use """Test unit.""" import unittest class TestCase(unittest.TestCase): """Main class.""" def test_send_post(self): """Call incorrect send_post, get None.""" # import requests from umbr_api._http_requests import send_post response = ...
889
270
''' this file creates the objects used to access the scrobbling service api No actual creds should be stored here! This module will be imported and used by the main code ''' import os import sys import pylast try: API_KEY = os.environ["LASTFM_API_KEY"] API_SECRET = os.environ["LASTFM_API_SECRET"] ex...
2,127
739
import os import urwid from .globalBase import * from .urwidHelper import * from .tool import * #import dc from .myutil import * class DlgFind(cDialog): def __init__(self, onExit=None): super().__init__() self.onExit = onExit self.widgetFileList = mListBox(urwid.SimpleFocusListWalker(btn...
4,802
1,995
# runs t-tests over the null hypothesis # avg_gini if (priority == "newer") == avg_gini if (priority == "more active") import csv import numpy as np from scipy.stats import ttest_ind from scipy.special import stdtr def readCsvFile(fileName): ''' (string) => list of dicts Read the file called fileName a...
8,595
2,475
''' Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. ''' class Solution: def runningSum(self, nums: List[int]) -> List[int]: res = list() for i in range(len(nums)): res.append(sum(nums[:(i+1)])) ...
350
123
# -*- coding: utf-8 -*- import imported import foo.bar print(imported.__doc__)
81
33
# Copyright 2014 Alistair Muldal <alistair.muldal@pharm.ox.ac.uk> # This program 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, either version 3 of the License, or # (at your option) any later version. # Th...
9,576
3,106
#!/usr/bin/env python3 # 脚本 by affggh # Apcache 2.0 import os import sys import shutil import zipfile import subprocess import platform import requests if os.name == 'nt': import tkinter as tk if os.name == 'posix': from mttkinter import mtTkinter as tk # While Load some need thread funcion on Linux it wi...
30,949
12,013
from .helpers import * from .decorators import *
49
15
import sys sys.path.append("..") from gym_snake.envs.node import Node from gym_snake.envs.snake_env import action_to_vector from gym_snake.envs.snake_env import SnakeAction from gym_snake.envs.snake_env import SnakeCellState from gym_snake.envs.snake_env import rotate_action_clockwise from gym_snake.envs.snake...
3,010
902
import discord from discord.ext import commands import asyncio import logging import sys import requests import datetime from bs4 import BeautifulSoup from util import * from wowapi import WowApi, WowApiException, WowApiConfigException from killpoints import KillPoints from math import ceil base_wow_progress = "http:/...
22,070
8,998
# -*- coding: utf-8 -*- """Module for reading and parsing values from Fingrid APIs.""" # Copyright (c) TUT Tampere University of Technology 2015-2018. # This software has been developed in Procem-project funded by Business Finland. # This code is licensed under the MIT license. # See the LICENSE.txt in the project roo...
10,974
3,116
# script to generate an overview file of all measurentoverview files import os import sys def main(result_folder): ######### Main routine erg_path = result_folder fobj = open(erg_path+'overview.txt','w') #liste mit Werten value_list =['Datum','Geo_loc','Geo_T1sl1hor','Geo_T1sl1ver','Geo_T1sl5hor','Geo_T1sl5ve...
1,222
595
#!/usr/bin/env python3 import pytest import autosnapgene as snap def test_getters(parse_and_write): for dna in parse_and_write('flag_tag.prot'): assert dna.sequence == 'DYKDDDDK' assert dna.protein_sequence == 'DYKDDDDK' def test_setters(): dna = snap.SnapGene() dna.protein_sequence = 'DY...
328
130
from typing import Set, List from inspectable import Inspectable from interactable import Interactable from items import Batteries, Hammer from usable import Usable class IceBlock(Inspectable, Interactable): def __init__(self): super().__init__() self.name = 'ice block' self.description ...
1,514
416
print("aprendiendo git") a=12 print("ya quedó") print("actualizacion 1") print("catualizacion 2")
97
39
import argparse from pathlib import Path if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--frames-path", type=str) parser.add_argument("--output-path", type=str) args = parser.parse_args() frame_paths = [p for p in Path(args.frames_path).iterdir()] with open(...
463
159
import _thread import sqlalchemy from app.document import bp from flask_login import login_required, current_user from flask import render_template, redirect, url_for, request, send_file, flash, jsonify from flask import current_app from app.document.general import create_document, check_and_remove_document, save_image...
26,979
8,702
""" This module defines a packet structure (composed of: canari, payload, payload_size, and eventually an extra payload). You'll find a 'pack' functions allowing you to create a packet from a payload (btyes object) you want to send, and an 'unpack' function that can extract a payload from a packet (as a bytes object to...
4,898
1,501
""" API interfaces for swagger operations. """ from typing import ( Any, Iterable, Mapping, Tuple, ) from marshmallow import Schema from marshmallow.fields import Field from microcosm_flask.swagger.parameters import Parameters from microcosm_flask.swagger.schemas import Schemas def build_schema(sch...
1,095
347
import sys import struct if(len(sys.argv) != 5): print("Usage: python converter.py <num_pixels_x> <num_pixels_y> <input file> <output file>\n") else: num_pixels_x = int(sys.argv[1]) num_pixels_y = int(sys.argv[2]) print(num_pixels_x) has_alpha_channel = False infile = open(sys.argv[3], "rb") ...
1,286
519
# import require package import os def remove_content(directory): for file in os.scandir(directory): print(file.path) os.remove(file.path) print("Old images has been deleted") upload_dir = './uploads' remove_content(upload_dir) images_dir = './static/images' remove_content(images_dir)
319
100
""" Fit step for gross alignment and scale. """ from opencmiss.utils.zinc.field import assignFieldParameters, createFieldsDisplacementGradients from opencmiss.utils.zinc.general import ChangeManager from opencmiss.zinc.field import Field, FieldFindMeshLocation from opencmiss.zinc.optimisation import Optimisation from ...
15,271
4,243
from abc import ABCMeta, abstractmethod from typing import Any class AbsProcessor(metaclass=ABCMeta): def __init__(self) -> None: pass @abstractmethod def __call__(self, logger, name, event_dict) -> Any: raise NotImplementedError
261
76
import numpy as np import matplotlib.pyplot as plt import pandas as pd blue = (0, 0, 1.0) green = (0, 0.8, 0) red = (1.0, 0, 0) red_alpha = (1.0, 0, 0, 0.001) gray = (0.7, 0.7, 0.7) results = [[],[], ["RandomForestRegressor-K=1",3.527128,2.820386,0.706743,0.063868,0.009973,0.286104,0.420639], ["RandomForestRegressor-...
2,965
2,028
#!/usr/bin/python # Created by: Jose G. Fernandez Trincado # Date: 2013 June 28 # Program: This program correct the imagen .fit (Science) by Syntethic Flat # 1 m Reflector telescope, National Astronomical Observatory of Venezuela # Mode f/5, 21 arcmin x 21 arcmin # Project: Omega Centauri, Tidal Tails. # The program ...
4,029
1,755
from typing import TYPE_CHECKING from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.sql import func from abing.db.base_class import Base if TYPE_CHECKING: from .arm import Arm # noqa: F401 class Feature(Base): __tablename_...
829
264
mlevel = 1 elevel = 1 mclass_bonus_a = 20 eclass_bonus_a = 0 mclass_bonus_b = 60 eclass_bonus_b = 0 mclass_power = 3 eclass_power = 2 def damage_exp(): return (31 + elevel + eclass_bonus_a - mlevel - mclass_bonus_a) / mclass_power def defeat_exp(mode=1): return (elevel * eclass_power + eclass_bonus_b) - ((mle...
555
249
import requests import json from pymongo import MongoClient, collection client = MongoClient("mongodb://localhost:27017") database = client["temp"] states_districts = database["states_districts"] states_districts.remove({}) headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537....
1,315
461
import tensorflow as tf def xavier_init(size): in_dim = size[0] xavier_stddev = 1. / tf.sqrt(in_dim / 2.) # return tf.random_normal(shape=size, stddev=xavier_stddev) return xavier_stddev def conv(x, w, b, stride, name): with tf.variable_scope('conv'): tf.summary.histogram('we...
3,989
1,568
import numpy as np # import matplotlib.pyplot as plt # import pylab import re import itertools import json import collections import multiprocessing as mp import random import sys #sys.path.append("./src/") #from proto import io as protoio #from utils.multiprocessor_cpu import MultiProcessorCPU ''' some general pre/p...
12,488
4,139
# print("Hello World!") # sum = 2 + 2 # print(sum) # for i in range(10,-10,-1): # if i % 2 == 0: # print(i) # else: # pass # while(1): # val = input("Enter ") # print(val)
207
92
# -*- coding: utf-8 -*- """User views.""" from flask import Blueprint, render_template, jsonify from flask_login import login_required from super_nft.extensions import csrf_protect datasprint_bp = Blueprint("datasprint", __name__, url_prefix="/datasprint", static_folder="../static") @csrf_protect.exempt @datasprint_b...
476
161
''' Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1.250,00, calcule um aumento de 10% Para os inferiores ou iguais, o aumento é de 15%. ''' salario = float(input('Digite o salário: R$ ')) if salario < 0: print('Valor inválido!') else: ...
548
224
def linhas(cor, txt): if pintar in cores: print(cores[pintar]) print(txt) cores = {'vermelho': '\033[31m', 'azul': '\033[34m', 'amarelo': '\033[33m', 'branco': '\033[30m', 'roxo': '\033[35m', 'verde': '\033[32m', 'ciano': '\033[36m', 'limp...
658
285
# Listing_20-2.py # Copyright Warren & Csrter Sande, 2013 # Released under MIT license http://www.opensource.org/licenses/mit-license.php # Version $version ---------------------------- # Adding an event handler for the button import sys from PyQt4 import QtCore, QtGui, uic form_class = uic.loadUiType("...
992
341
from serial_comminication import * from utils.decorators import Override __author__ = 'Danyang' class SerialAPIStub(SerialAPI): @Override(SerialAPI) def __init__(self): super(SerialAPIStub, self).__init__(production=False) @Override(SerialAPI) def command_put(self, function, parameter): ...
1,072
371
from typing import Dict from botocore.paginate import Paginator class ListBundles(Paginator): def paginate(self, PaginationConfig: Dict = None) -> Dict: """ Creates an iterator that will paginate through responses from :py:meth:`Mobile.Client.list_bundles`. See also: `AWS API Documentation...
5,259
1,353
# Best : O(n + k) # Avg : O(n + k) # Worst O(n + k) # Space worst : O(k) - CAN GET VERY BIG BIG # k - range of values in array # Take every number in arr then add += 1 to index of that number in temporary arrays, then # for every index in temporary arrays add to final_arr that amount of that index number of # how bi...
1,550
554
import os import random import re import numpy as np np.set_printoptions(precision=3, suppress=True) import sys; sys.path.append("../../..") from job_table import JobTable def get_logfile_paths_helper(directory_name): logfile_paths = [] for root, _, file_names in os.walk(directory_name): if len(file...
5,881
2,067
""" Move Zeroes - https://leetcode.com/problems/move-zeroes/ Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] ...
883
315
from django.contrib.auth import login as django_login from django.contrib.auth import logout as django_logout from django.http import HttpResponseRedirect from django.shortcuts import resolve_url from django.conf import settings from .backends import StormpathIdSiteBackend ID_SITE_STATUS_AUTHENTICATED = 'AUTHENTICAT...
1,503
510
# https://leetcode.com/problems/perfect-squares/description/ # dp alg, time complexity: O(n^2) class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ dp = [n for _ in range(n+1)] dp[0] = 0 for i in range(1, n+1): j = 1...
445
176
# Programa para sorteio from tkinter import * '''import PySimpleGUI as sg''' ''' #Layout layout = [ [sg.Text('Nome:'), sg.Input()], [sg.Button('OK')] ] #Janela janela = sg.Window('Janela teste', layout) #Interação eventos, valores = janela.Read() #Mensagem print(f'Olá {valores[0]}, obrigado por usar PySimple...
1,416
579
""" @author: magician @file: __init__.py.py @date: 2020/9/7 """ from flask import Flask from flask_tutorial.flask_sqlite3.flask_sqlite3 import SQLite3 app = Flask(__name__) app.config.from_pyfile('the-config.cfg') db = SQLite3(app) @app.route('/') def show_all(): """ show_all @return: """ # ...
481
184
"""Transformando um string de numeros, em uma lista com conjunto de numeros separads por \n""" matrix = "1 2 3 4\n4 5 6 5\n7 8 9 6\n8 7 6 7" print(matrix) matrix = matrix.split("\n") print(matrix) matrix2 = [] for n in range(len(matrix)): matrix[n] = matrix[n].split() matrix[n] = list(map(int, matrix[n])) # E...
516
202
from A_1_Add_columns_participant_info_multiprocessing_new import * from A_2_Merge_new_logs import * from B_1_Add_columns_user_performance_multiprocessing_new import * from B_2_Merge_new_logs_with_user_groups import * from C_1_Post_processing_log_new import * from C_2_Merge_new_logs_post_processed import * from D_1_Reca...
517
201
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='xl-helper', version='1.0.5', description='XL Deploy helper', long_description='This tool helps with installation and upgrade of XL Deploy and plugins', author='Mike Kotsur', author_email='mkotsur@xebialabs.com', ...
599
201
# -*- coding: utf-8 -*- from collections import defaultdict from PyPDF2 import PdfFileReader from PyPDF2.pdf import PageObject, ContentStream, TextStringObject, u_, i, b_ def is_continuation(content, item): if content.operations[item - 1][1] == b_("Tm"): # Search previous "Tm" for bef in range(-2, -15, -1): ...
3,520
1,457
from setuptools import setup, find_packages setup( name = "django-netpromoterscore", version = '0.0.2', description = "Model, Tests, and API for collecting promoter score from users.", author = "Austin Brennan", author_email = "ab@epantry.com", url = "https://github.com/epantry/django-netpromo...
493
157
import flask class Configuration: def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(Configuration, cls).__new__(cls) return cls.instance recipient = None resource_id = None artifact_id = None contract = None custom_dsc = None use_custom_d...
731
216
from pynemo.core.base.abstract.property import Property class StringProperty(Property): @classmethod def validate(cls, v): return str(v) @classmethod def to_cypher(cls, v): return repr(str(v))
228
73
import logging import sys from pathlib import Path import time from folio_uuid.folio_namespaces import FOLIONamespaces class FolderStructure: def __init__( self, base_path: Path, object_type: FOLIONamespaces, migration_task_name: str, iteration_identifier: str, add...
6,299
1,964
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
6,064
1,907
from django.test import TestCase from ladder.models import Player, Result, League, Season from django.db.models import Avg class PlayerModelTest(TestCase): def test_player_stats(self): """ Tests a player stats is calculated correctly. """ # fresh player test player = Player...
2,782
825
"""Google OpenID Connect identity provider.""" from uuid import UUID from fastapi import Depends, status, Request from pydantic import BaseModel from .base import IdPRouter, oauth from ..http import get_edgedb_pool from ..models import IdPClient, Identity as BaseIdentity, Href, User from ..orm import ExtendedComputa...
6,779
2,225
"""Import processors from 3rd party sources.""" import contextlib import sys import pkg_resources from ._misc import parameters @parameters( jsonschema={ "type": "object", "properties": { "imports": {"type": "array", "items": {"type": "string"}}, "from_": {"type": "strin...
1,192
337
# # @lc app=leetcode.cn id=412 lang=python3 # # [412] Fizz Buzz # # Accepted # 8/8 cases passed (48 ms) # Your runtime beats 76.37 % of python3 submissions # Your memory usage beats 25 % of python3 submissions (14.5 MB) # @lc code=start class Solution: def fizzBuzz(self, n: int): result = list() f...
656
235
import pandas as pd import numpy as np from sklearn.model_selection import check_cv from sklearn.exceptions import NotFittedError from sklearn.base import clone, is_classifier from robusta.importance import get_importance from robusta.crossval import crossval from .base import _Selector # Original: sklearn.feature_...
5,875
1,646
import torch import torch.nn as nn import torch_optimizer as optim import pandas as pd # customized libs import criterions import models import datasets def get_model(conf): net = getattr(models, conf.Model.base) return net(**conf.Model.params) def get_loss(conf): conf_loss = conf.Loss.base_loss as...
1,875
637
import graphene from fuzzywuzzy import process from falmer.search.types import SearchQuery from falmer.search.utils import get_falmer_results_for_term, get_msl_results_for_term, \ SearchTermResponseData def get_item_id(item): model = item.__class__.__name__ if hasattr(item, '__class__') else 'MSL' if mod...
1,733
532
#Shape of heart: def for_heart(): """printing shape of'heart' using for loop""" for row in range(6): for col in range(7): if row-col==2 or row+col==8 or col%3!=0 and row==0 or col%3==0 and row==1: print("*",end=" ") else: print(" ",end=" "...
700
254
from core import add from core import sub def test_add(): """Check that `add()` works as expected""" assert add(2, 3) == 5 def test_add_z(): """Check that `add()` works as expected""" assert add(2, 3, 1) == 6 def test_sub(): """Check that `sub()` works as expected""" asse...
338
124
from __future__ import annotations from setuptools import setup setup()
73
20
#9. Façaumam função que receba a altura e o raio de um cilindro circular e retorne o volume #do cilindro. O volume de um cilindro circular é calculado por meio da seguinte fórmula: #V =pi*raio^2 x altura, onde pi = 3.141592. def volCilindro(raio,altura): return 3.1415926535*pow(raio,2)*altura r=float(input("Inform...
434
192
import requests from bs4 import BeautifulSoup from sachima import conf class Publisher(object): @classmethod def get_csrf_token(self, html): soup = BeautifulSoup(html, "html.parser") csrf = soup.find(id="csrf_token").attrs["value"] return csrf @classmethod def to_superset(sel...
1,714
493
import tkinter class Main(tkinter.Frame): def __init__(self, parent): super().__init__(parent) self.parent = parent self.pack() self.checkValue = tkinter.StringVar() self.checkGuest = tkinter.Radiobutton(self, text="Guest", variable=self.checkValue, value="Guest", ...
3,254
1,006
# !/usr/bin/env python # -*- coding: utf-8 -*- import sys urlpatterns = [ ] DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'statictemplate', ], DATABASES={ 'default': { 'ENGINE': '...
2,190
675
x = input() z = input() splitter = [x[i:] for i in range(len(x))] found_splitter = False next_z = "" for i in range(1, len(x) + 1): if z[:i] in splitter: found_splitter = True next_z = z[i:] if next_z[: len(x)] == x: break if i == len(z): break if next_z == "": ...
585
212
import urllib.request url = "https://google.com" data = urllib.request.urlopen(url) print(data) print(data.read())
117
45
from django.conf.urls.defaults import patterns, url from datawinners.blue import view from datawinners.blue.view import new_xform_submission_post, edit_xform_submission_post, get_attachment, attachment_download, guest_survey, public_survey from datawinners.blue.view import ProjectUpload, ProjectUpdate from datawinners....
1,592
592
print('hello man') print('hello man') print('hello man') print('hello man') print('hello man')
95
31
# # Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
4,013
1,270
ROUTE = '/push' PORT = 4242 IMAGE_NAME = 'globidocker/github-hook' import docker cli = docker.Client() from lib.git import clone_tmp def on_push(data, logger): url = data['repository']['html_url'] logger.info('Cloning repository: "{}"...'.format(url)) with clone_tmp(url) as repo: logger.info(...
481
167
#!/usr/bin/env python3 # Solver test suite runner script, used for # * regression tests (default) # * test-init runs (with --test-init option) # * performance evaluation (with --performance option) # # 1. Regression tests (the default) # - runs set of projects and compares physical results and solver stats # - meant t...
12,403
4,099
from torch.utils.data import Dataset class Anechoic(Dataset): def __init__(self, root, ttv, download=False, transform=None, target_transform=None, columns=None, output_path=None): from pathlib import Path import os ttvs = ['train', 'test', 'validate'] assert ttv ...
4,815
1,425
import logging import datetime import pathlib import pytz import requests import pandas as pd DATA_ROOT = pathlib.Path(__file__).parent.parent / "data" _logger = logging.getLogger(__name__) class CovidTrackingDataUpdater(object): """Updates the covid tracking data.""" HISTORICAL_STATE_DATA_URL = "http://covi...
1,410
474
from chatty import utils from aiohttp import web from chatty.auth.models import User async def registration(request): auth_data = await request.json() if not await utils.validation_credentials(auth_data): return web.json_response({"message": "Invalid credentials"}, status=400) await User.create(...
1,100
321
import os, sys import imp from authorizenet import apicontractsv1 from authorizenet.apicontrollers import * constants = imp.load_source('modulename', 'constants.py') def delete_customer_profile(customerProfileId): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLogi...
1,220
315
# Copyright 2021 IBM Corp. # SPDX-License-Identifier: Apache-2.0 from pyspark.sql.dataframe import DataFrame from py4j.java_collections import MapConverter class IndexBuilder: """ Helper class for building indexes :param sparkSession: SparkSession object :param uri: the URI of the dataset / the ident...
3,659
945
from kafka.consumer import KafkaConsumer from json import loads from mongoengine import * from matilda.data_pipeline import object_model consumer = KafkaConsumer( 'numtest', # kafka topic bootstrap_servers=['localhost:9092'], # same as our producer # It handles where the consumer restarts reading after...
1,837
538
from graph import Graph def bfs(graph, source, destination): if not (graph.contains(source) and graph.contains(destination)): return float("inf") distances = dict() visited = dict() for vertex in graph.vertices(): distances[vertex] = float("inf") visited[vertex]...
746
237
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Claim Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ from pydantic.validators import bytes_validator # noqa: F401 from .. import fhirtypes # noqa: F401 from .. import claim def impl_claim_1...
55,584
20,296
import argparse import os.path import sys sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import pymia.deeplearning.logging as log import tensorflow as tf import pc.configuration.config as cfg import pc.data.handler as hdlr import pc.data.split as split import pc.model....
2,708
785
from nipype.interfaces.utility import Function def topup_scan_params(pe_direction='y', te=0.025, epi_factor=37): import numpy as np import os import tempfile scan_param_array = np.zeros((2, 4)) scan_param_array[0, ['x', 'y', 'z'].index(pe_direction)] = 1 scan_param_array[1, ['x', 'y', 'z'].in...
1,586
589
import os import pickle from deployConfig import workDir import sys env_fp = f"{workDir}/env.pickle" def add_to_env(varname, path): with open(env_fp, "rb") as fh: envvars = pickle.load(fh) if varname in envvars.keys(): if path not in envvars[varname]: envvars[varname].append(path)...
1,317
531