content stringlengths 5 1.05M |
|---|
import os
from typing import Dict
from fluid.http import HttpClient
from .repo import GithubRepo
class Github(HttpClient):
def __init__(self, token=None) -> None:
self.token = token or get_token()
@property
def api_url(self):
return "https://api.github.com"
@property
def upload... |
import os
from pm4py.objects.log.importer.xes import importer as xes_importer
from pm4py.algo.discovery.inductive import algorithm as inductive_miner
from pm4py.objects.petri.exporter import exporter as pnml_exporter
from pm4py.visualization.petrinet import visualizer as pn_visualizer
log = xes_importer.apply(os.path.... |
from typing import List
class Board:
CONTINUE = -1
STALEMATE = 0
P_ONE_WIN = 1
P_TWO_WIN = 2
def __init__(self):
self.board = self.col_count = None # Stop the inspections from complaining
self.reset()
@property
def available_columns(self):
... |
import os
import shutil
import winbrew.util
import zipfile
import tarfile
import urllib
import subprocess
class Archive:
"""
Archive describes the type of package to download. Typically, some kind of
compressed file (tar, zip) or a git repository.
"""
@staticmethod
def create(url, work_dir, pa... |
import uuid
from django.utils.functional import cached_property
from django.conf import settings
from .tasks import send_report_task
GOOGLE_ID = settings.GOOGLE_ANALYTICS_ID
class Tracker(object):
valid_anal_types = ('pageview', 'event', 'social', 'screenview', 'transaction', 'item', 'exception', 'timing')
... |
from typing import List
from mathy_core import ExpressionParser, MathExpression, Token, VariableExpression
problem = "4 + 2x"
parser = ExpressionParser()
tokens: List[Token] = parser.tokenize(problem)
expression: MathExpression = parser.parse(problem)
assert len(expression.find_type(VariableExpression)) == 1
|
# -*- encoding: utf-8 -*-
TRAIN_PERIOD = ['2010', '2011', '2012', '2013', '2014', '2015']
VALIDATION_PERIOD = ['2016', '2017']
BACKTEST_PERIOD = ['2018', '2019']
M = 60
T = 28
UP_THRESHOLD = 6
DOWN_THRESHOLD = -6 |
import subprocess
from voxel_globe.tools.subprocessbg import Popen
def findProcess(imageName, filterString):
pid = Popen(['wmic', 'path', 'win32_process', 'where', "Name='%s'" % imageName, 'get', 'CommandLine,ProcessId', '/VALUE'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = pid.communicate()
out=out[0]... |
from django.conf.urls import include, url
from rest_framework import routers
from .views import DynamicSerializerViewSet
router = routers.DefaultRouter()
router.register(r'users-dynamic', DynamicSerializerViewSet)
# router.register(r'users-dynamic-fields', DynamicFieldsSerializerViewSet)
# router.register(r'users-dyn... |
"""AWS CodeArtifact Poetry CLI Definition."""
from typing import Optional
import click
from click import Context
from aws_codeartifact_poetry.commands.login import login
from aws_codeartifact_poetry.helpers.catch_exceptions import catch_exceptions
from aws_codeartifact_poetry.helpers.logging import setup_logging
@... |
/home/runner/.cache/pip/pool/9a/45/66/84570200a54f99fddefdcdaee7fc44afacceb8b1f18723cbf24f70e90b |
class ZoneStats:
def __init__(self, zones_data:dict):
self.zones_secured = zones_data.get('secured', 0)
self.zones_captured = zones_data.get('captured', 0)
self.occupation_time = zones_data.get('occupation', {}).get('duration', {}).get('seconds', 0)
zone_kills = zones_data.get('kills... |
from __future__ import absolute_import, unicode_literals
from celery import Celery
from celery.schedules import crontab
from jeta.archive.ingest import force_sort_by_time, calculate_delta_times
##CELERYBEAT_SCHEDULER = 'redbeat.RedBeatScheduler'
app = Celery(
'jeta.archive',
broker='redis://localhost',
... |
"""
Permissions for the instructor dashboard and associated actions
"""
from bridgekeeper import perms
from bridgekeeper.rules import is_staff
from lms.djangoapps.courseware.rules import HasAccessRule, HasRolesRule
ALLOW_STUDENT_TO_BYPASS_ENTRANCE_EXAM = 'instructor.allow_student_to_bypass_entrance_exam'
ASSIGN_TO_C... |
import serial
import time
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui
# Change the configuration file name
configFileName = 'mmw_pplcount_demo_default.cfg'
CLIport = {}
Dataport = {}
byteBuffer = np.zeros(2**15,dtype = 'uint8')
byteBufferLength = 0;
# ------------------------------------... |
from .legofy import legofy
|
"""
Test cases for the HTTP endpoints of the profile image api.
"""
from contextlib import closing
from unittest import mock
from unittest.mock import patch
import pytest
import datetime # lint-amnesty, pylint: disable=wrong-import-order
from pytz import UTC
from django.urls import reverse
from django.http import Ht... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""
Created on Sep 23, 2016
@author: andrew
"""
import asyncio
import logging
from math import floor
import discord
from discord.errors import NotFound
from discord.ext import commands
import api.avrae.utils.redisIO as redis
from api.avrae.cogs5e.funcs.lookupFuncs import compendium
from api.avrae.utils import checks... |
from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
import os
import re
import sys
import six
from docker.utils.ports import split_port
from jsonschema import Draft4Validator
from jsonschema import FormatChecker
from jsonschema import RefResolver
from jsonschema i... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
alpha, beta = 0.4, 0.5
def f(x1, x2):
return alpha * np.log(x1) + beta * np.log(x2)
p1, p2, m = 1.0, 1.2, 4
def budget_line(x1):
return (m - p1 * x1) / p2
x1star = (alpha / (alpha + beta)) * (m / p1)
x2star = budget_line(x1star)
max... |
import os
import subprocess
import glob
import hashlib
import shutil
from common.basedir import BASEDIR
from selfdrive.swaglog import cloudlog
# OPKR
#android_packages = ("com.mixplorer", "com.opkr.maphack", "com.gmd.hidesoftkeys", "com.google.android.inputmethod.korean", "com.skt.tmap.ku",)
android_packages = ("co... |
################################################################################
# Author:Justin Vankirk
# Username:vankirkj
#
# Assignment:A03
# https://docs.google.com/document/d/1upvTP9Z7BehzY-HqRqI9Uh2F3cD19rZi_MtArv0Tn_M/edit?usp=sharing
#############################################################################... |
# Copyright: (c) 2021, Ryan Gordon
# The MIT License
#
# 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, merge,... |
# Reusable components like navbar/header, footer etc.
# ------------------------------------------------------------
import dash_html_components as html
import dash_bootstrap_components as dbc
header = dbc.Row(children=[
dbc.Col(html.Img(src='/assets/logo.png',
height='30px'),
wid... |
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, root_validator
from application.models.schema.utils import SuccessResponse
from application.utils.api_response import CustomException
class BasePatient(BaseModel):
first_name: str
last_name: str
email: Option... |
##########################################################################
#
# Copyright (c) 2012, John Haddon. All rights reserved.
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that ... |
import numpy
import numpy as np
from sklearn.svm import SVR
#--------------------------------------------------------------------
# Hyperparameters
#--------------------------------------------------------------------
lr = 0.001 # learning rate
#--------------------------------------------------------------------
#... |
import os
import signal
import sys
import time
from abc import ABCMeta
from abc import abstractmethod
from contextlib import contextmanager
from functools import partial
from shutil import rmtree
from types import FrameType
from typing import Iterator
from typing import List
from typing import Optional
from typing impo... |
# Copyright (c) 2008, Kundan Singh. All rights reserved. See LICENSING for details.
# @implements RFC3263 (Locating SIP servers)
'''
Uses DNS to resolve a domain name into SIP servers using NAPTR, SRV and A/AAAA records.
TODO: (1) need to make it multitask compatible or have a separate thread, (3) need to return ... |
# Python program to implement server side of chat room.
import socket
import select
import sys
from thread import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# checks whether sufficient arguments have been provided
if len(sys.argv) !... |
"""
Number letter counts
Problem 17
https://projecteuler.net/problem=17
"""
def sol():
under_ten = get_under_ten()
total_of_one_to_ninety_nine = get_total_of_one_to_ninety_nine(under_ten)
total_of_one_hundred_until_thousand = get_total_of_one_hundred_until_thousand(
under_ten, total_of_one_to_nin... |
#!/usr/bin/python
"""
This example shows how to create an empty Mininet object
(without a topology object) and add nodes to it manually.
"""
from mininet.net import Mininet, MininetWithControlNet
from mininet.node import Controller, RemoteController
from mininet.cli import CLI
from mininet.log import setLogLevel, inf... |
import logging
import amrlib
import penman
import penman.models.noop
import re
from amrlib.alignments.rbw_aligner import RBWAligner
from amrlib.graph_processing.annotator import add_lemmas, load_spacy
from amratom.atomese import is_variable, is_amrset_name
_spacy_model = 'en_core_web_md'
_penman_model = penman.model... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 30 13:19:29 2014
@author: enrico.giampieri2
"""
import unittest
import sympy
from utils import Counter
from utils import variazione
from utils import shift
from utils import WRGnumpy
from CME import CME
if __name__ == '__main__':
unittest.main() |
from functools import reduce
import pandas as pd
import glob
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklea... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from typing import Optional, Sequence
import numpy as np
from fastmri.data.subsample import MaskFunc, RandomMaskFunc
def create_mask_for_m... |
from datetime import timedelta
import pandas.util.testing as tm
from pandas import TimedeltaIndex, timedelta_range, compat, Index, Timedelta
class TestTimedeltaIndex(tm.TestCase):
_multiprocess_can_split_ = True
def test_insert(self):
idx = TimedeltaIndex(['4day', '1day', '2day'], name='idx')
... |
"""
Based on augmented_lstm.py and stacked_bidirectional_lstm.py from AllenNLP 0.8.3
"""
from typing import Optional, Tuple, Type, List, Dict, Any
import torch
from allennlp.nn.util import get_dropout_mask
from modules.stack_rnn_cell import StackRnnCellBase, StackLstmCell
class StackRnn(torch.nn.Module):
"""
... |
'''
Function Name : DirectoryTraversal, DisplayDuplicate
Description : In This Application We Import All Other Modules To Perform Duplicate Files Removing Operation
Function Date : 25 June 2021
Function Author : Prasad Dangare
Input : Get The Directory Name
Output : Delete D... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlgorithmGoodsInfo(object):
def __init__(self):
self._algorithm_goods_id = None
self._gif_file_id = None
self._pic_file_id = None
self._three_dimension = None
... |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../")))
sys.path.insert(0, os.path.abspath(
os.path.join(os.getcwd(), "../../../../FedML")))
from fedml_core.distributed.client.client_manager import ClientManager
class CommunicationManager(ClientManager):
def __init_... |
from django.middleware.csrf import CsrfMiddleware, CsrfViewMiddleware, CsrfResponseMiddleware
from django.views.decorators.csrf import csrf_exempt, csrf_view_exempt, csrf_response_exempt
import warnings
warnings.warn("This import for CSRF functionality is deprecated. Please use django.middleware.csrf for the middlewa... |
# Copyright 2018 DeepMind Technologies Limited.
#
# 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 ag... |
#! usr/bin/python3
import pandas as pd
import re
import numpy as np
import os
import sys
from collections import OrderedDict
parent_path = os.path.realpath(os.pardir)
if sys.platform.startswith('win') or sys.platform.startswith('cygwin'):
seseds_path = os.path.join(parent_path, 'MCM-ICM-2018-Problem-C\\data\\cs... |
# Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from quaternion.numba_wrapper import njit, jit, xrange
def derivative(f, t):
"""Fourth-order finite-dif... |
expected_output = {
'dynamic_nat_entries': '0 entries',
'flow_record': 'Disabled',
'nat_type': 'Static',
'netflow_type': 'NA',
'static_nat_entries': '0 entries',
'total_hw_resource_tcam': '26 of 27648 /0 .09% utilization',
'total_nat_entries': '0 entries'
} |
from django.contrib import admin
from .models import BookAppoinment
# Register your models here.
admin.site.register(BookAppoinment)
|
{
'French': 'fransè',
'Haitian Creole': 'kreyòl ayisyen',
'Haitian French': 'fransè ayisyen',
}
|
class NotSet(object):
"""Sentinel value."""
def __eq__(self, other):
return self is other
def __repr__(self):
return 'NotSet'
class StateNotSet(object):
def __eq__(self, other):
return self is other
def __repr__(self):
return 'NotSet'
def value(self):
... |
from IPython.html.services.contents.filemanager import FileContentsManager
c.ServerApp.jpserver_extensions = {"jupyterlab_hubshare": True}
c.HubShare.file_path_template = "{user}/{path}"
c.HubShare.contents_manager = {
"manager_cls": FileContentsManager,
"kwargs": {"root_dir": "/tmp/"},
}
|
"""Generated client library for run version v1alpha1."""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.run.v1alpha1 import run_v1alpha1_messages as messages
class RunV1alpha1(base... |
import mock
import pyconfig
from unittest.case import SkipTest
from humbledb import Mongo, Document, _version
from humbledb.errors import DatabaseMismatch, ConnectionFailure
from ..util import database_name, ok_, eq_, DBTest, raises
def teardown():
DBTest.connection.drop_database(database_name())
def test_new(... |
B_35_01_11 = {0: {'A': 0.282, 'C': -0.023, 'E': -0.036, 'D': 0.029, 'G': 0.081, 'F': -0.29, 'I': -0.259, 'H': -0.031, 'K': 0.25, 'M': -0.315, 'L': -0.34, 'N': -0.029, 'Q': 0.063, 'P': 0.313, 'S': 0.153, 'R': 0.507, 'T': 0.079, 'W': -0.183, 'V': -0.151, 'Y': -0.102}, 1: {'A': -0.243, 'C': 0.021, 'E': 0.07, 'D': 0.048, '... |
from typing import Dict, Set, List, Tuple
import pkgutil
import sys
import typing
from importlib import import_module, invalidate_caches
from databases import Database
from .migration import Migration
def build_dependants(dependencies: Dict[str, Set[str]]) -> Dict[str, Set[str]]:
"""
Given a dependencies mapp... |
import unittest
from .. api_client import ApcUrl, UrlBadParam, IncompleteUrl
class TestApcUrl(unittest.TestCase):
def test_init(self):
url = "/testing"
u = ApcUrl(url)
self.assertEquals( u.base_url, url)
def test_params_1(self):
u = ApcUrl("/testing/%%key%%")
self.asser... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import re
import urllib2
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect
# {STIX/ID Alias}:{type}-{GUID}
_STIX_ID_REGEX = r"[a-z][\w\d-]+:[a-z]+-[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}"
_OBJECT_ID_MATCHER = re.compile("%s$" % _STIX_ID_REGEX, re.IGNORECASE)
_URL_... |
"""
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p... |
#!/usr/bin/env python3
import numpy as np
import pyboof as pb
from pyboof.swing import visualize_matches
# Load two images
image0 = pb.load_single_band("../data/example/stitch/cave_01.jpg", np.uint8)
image1 = pb.load_single_band("../data/example/stitch/cave_02.jpg", np.uint8)
# Set up the SURF fast hessian feature ... |
# Testing raytracing functions against lenstools
import tensorflow as tf
import numpy as np
from numpy.testing import assert_allclose
from scipy.interpolate import InterpolatedUnivariateSpline as iuspline
from scipy.ndimage import fourier_gaussian
import flowpm
import flowpm.constants as constants
import lenstools as l... |
from scipy.optimize import minimize
import matplotlib.pyplot as plt
import numpy as np
import logging
import os.path
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
def fit_tophat(x, y, verify=False):
"""
Fit the x and y data to a tophat function, returning:
base_level - the y-value... |
from google.appengine.ext import db
# Database
# font db
class EnFamily(db.Model):
# width = x A width / cap height
# x height = x height / cap height
# m serif = serif length of m 500% chrome screen - font-size 20px
# h_stem_horizontal_balance = H horizontal height / H stem width
# o_stroke_axis ... |
import os
import sys
import urllib2
import urlparse
import json
import base64
import time
from boto.s3.key import Key
import boto.s3
import logging
from selenium import webdriver
logger = logging.getLogger('sitetest')
def test_screenshots(set, credentials, options, test_category_id, batch_id, max_test_count=20, ver... |
"""
A python module that generates uni-variate and bi-variate analysis graphs for
exploratory data analysis. Specifically, the module contains functions to
graph histograms for numeric data, bar plots for categorical data, a
correlation matrix heat map, and a scatter pair plot. The graphs produced
are added into the fi... |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 226171178
"""
"""
random actions, total chaos
"""
board = gamma_new(3, 3, 2, 3)
assert board is... |
import logging
import os
import sys
from kolibri.core.logger.csv_export import classes_info
from kolibri.core.logger.csv_export import csv_file_generator
from kolibri.core.tasks.management.commands.base import AsyncCommand
logger = logging.getLogger(__name__)
class Command(AsyncCommand):
def add_arguments(self,... |
# coding: utf-8
import ast
from functools import partial, wraps
from json import JSONDecodeError
from django.conf import settings
from django.core.exceptions import EmptyResultSet
from django.db import models
from django.db.models import Avg, Count, F, Max, Min, Q, QuerySet, StdDev, Sum, Variance, functions
from rest_... |
from math import sqrt
import sys
import scipy.stats
import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt
sys.path.append('/home/silvio/git/track-ml-1/utils')
from tracktop import *
original_tracks = sys.argv[1]
reconstructed_tracks = sys.argv[2]
dfOriginal = pd.read_csv(original_tr... |
from locust import HttpLocust, TaskSet, task
import bs4
import random
import sys, os
class WebsiteTasks(TaskSet):
def on_start(self):
res = self.client.get("/runestone/default/user/login")
pq = bs4.BeautifulSoup(res.content, features="lxml")
# Get the csrf key for successful submission
... |
from django.core.urlresolvers import reverse
from django.test import TestCase
class AccountsDeleteViewTestCase(TestCase):
fixtures = ['users_views_testdata.yaml']
def test_delete_non_existent_user(self):
url = reverse('del', args=[99])
resp = self.client.get(url, follow=True)
self.as... |
import numpy as np
import matplotlib.pyplot as plt
# The following helper functions simplify the SPEIS data import from MPT files
def get_boundaries(highest_freq, lowest_freq, f):
if (np.count_nonzero(f[0] >= highest_freq) > 0):
cutoff_start = np.where(f[0] >= highest_freq)[0][-1]
else:
cutof... |
"""
返回数据的基类
create by judy 2018/10/22
"""
import datetime
import enum
import io
import json
import os
import threading
from abc import ABCMeta, abstractmethod
import pytz
from commonbaby.helpers import helper_crypto, helper_str
from datacontract.idowndataset import Task
from datacontract.outputdata import (EStandardD... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''main.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Aug 2018
License: MIT - see the LICENSE file for the full text.
This is the main file for the authnzerver, a simple authorization and
authentication server backed by SQLite and Tornado for use with the lcc-server.
... |
from .elements.element_base import ElementBase
from .elements.list import List
from .elements.value_element_base import ValueElementBase
from .elements.missing.missing_element_base import MissingElementBase
from .elements.missing.missing_list import MissingList
from .elements.missing.missing_value_element_base import M... |
import pickle as pkl
plotname = 'DentateGyrus'
from scvi.dataset.MouseBrain import DentateGyrus10X, DentateGyrusC1
from scvi.dataset.dataset import GeneExpressionDataset
dataset1= DentateGyrus10X()
dataset1.subsample_genes(dataset1.nb_genes)
dataset2 = DentateGyrusC1()
dataset2.subsample_genes(dataset2.nb_genes)
gene_... |
import requests
import random
def handle(st):
r = requests.get("http://api.open-notify.org/astros.json")
result = r.json()
index = random.randint(0, len(result["people"])-1)
name = result["people"][index]["name"]
print (name + " is in space")
|
# from django.forms import ModelForm
from .models import ClockIn, SetUp
from django import forms
# from django_bootstrap5.widgets import RadioSelectButtonGroup
from django.forms import ModelForm
class ClockInForm(forms.Form):
def __init__(self, user, *args, **kwargs):
# 动态的选项
self._user = user
... |
import os
import sys
import argparse
from azureml.core.workspace import Workspace
from azureml.core import Experiment, Datastore, RunConfiguration
from azureml.train.estimator import Estimator
parser = argparse.ArgumentParser()
parser.add_argument('experiment', help='Azure ML experiment name')
parser.add_argument('--... |
#!/usr/bin/env python
import sys
import os
import re
import numpy
from PIL import Image
import StringIO
# you need to install this library yourself
# recent versions handle bigtiff too...
import tifffile
"""
Extract a pyramidal TIFF with JPEG tiled storage into a tree of
separate JPEG files as expected by Zoomify.
... |
from django.contrib import admin
from . models import Videos, Comment
# Register your models here.
admin.site.register(Videos)
admin.site.register(Comment)
|
# myproject/apps/core/admin.py
from django.conf import settings
def get_multilingual_field_names(field_name):
lang_code_underscored = settings.LANGUAGE_CODE.replace("-",
"_")
field_names = [f"{field_name}_{lang_code_underscored}"]
for lang_code, lang_name in ... |
# -*- coding: utf-8 -*-
# Python Libraries
import MySQLdb
import json
import io
import datetime
import re
# Importing other code
from classes import *
def saveJson(json_name, objects_list, encoder_class):
with io.open(''+json_name+'.json', 'w', encoding='utf-8') as jsonTemp:
jsonTemp.write(unicode(json.... |
import random
import numpy as np
from kerastuner.tuners import Hyperband
from sklearn.model_selection import RandomizedSearchCV
class Model:
def __init__(
self, X_train, X_test, y_train, y_test,
metric, metric_sign, cv
):
self.metric = metric
self.metric_sign = metric_sign
... |
"""
Spatial helper files
"""
__version__ = '0.2'
import math
import numpy as np
import pysal.lib.cg.sphere as sphere
def geointerpolate(point0, point1, proportion):
"""Interpolate on great sphere (world coords)
Arguments:
point0 {list} -- (lng,lat) of first point
point1 {list} -- (lng,lat)... |
# -*- coding: utf-8 -*-
from symbol_table import SymbolTable
TYPES = ['inteiro', 'flutuante']
OPERATIONS = ['=', '<>', '>', '<', '>=', '<=', '&&', '||']
success = True
class Analyzer():
def __init__(self):
self.symboltable = SymbolTable()
success = True
def scan_tree(self, node):
currentStatus = sel... |
DATA = [
{'timestamp': 100000000, 'momentary': -79.89229196784386, 'shortterm': -88.642904601760861, 'global': float('-inf'),
'window': -90.861392097924423, 'range': 0},
{'timestamp': 200000000, 'momentary': -66.953377330406298, 'shortterm': -75.703989964323284,
'global': float('-inf'), 'window': -77.... |
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from tuiuiu.tuiuiuembeds.views import chooser
urlpatterns = [
url(r'^chooser/$', chooser.chooser, name='chooser'),
url(r'^chooser/upload/$', chooser.chooser_upload, name='chooser_upload'),
]
|
""" API for Pioneer Network Receivers. """
# pylint: disable=logging-fstring-interpolation,broad-except
import logging
import traceback
import socket
import telnetlib
import time
import random
from threading import Thread, Event, Lock
_LOGGER = logging.getLogger(__name__)
MAX_VOLUME = 185
MAX_VOLUME_ZONEX = 81
MAX... |
#
# ______ ____ ______ ____ _____ ____ _____ __ __
# | ___ \ / ___ \ | ___ \ / ___ \ | ___ \ / ___ \ / _____\ | | / /
# | |__| / | | | | | |__| / | | | | | | | | | | | | | | | |/ /
# | \ | | | | | ___ \ | | | | | | | | | | | | | | | /
... |
import datetime
import io
import os
import re
import subprocess
import warnings
from collections import namedtuple
from decimal import Decimal
from pathlib import Path
import six
from PyPDF2 import PdfFileMerger
from reportlab.pdfgen import canvas
class DoctorUnicodeDecodeError(UnicodeDecodeError):
def __init__(... |
if not 1121 + 100 < 1920 & 1010 + 80 < 1080:
print("aa")
|
from django.db import models
from django.utils.encoding import smart_text
from django.utils.encoding import python_2_unicode_compatible
from django.urls import reverse
from django.utils.text import slugify
from redactor.fields import RedactorField
@python_2_unicode_compatible
class Topic(models.Model):
title = m... |
import re
import requests
class InvalidIDError(Exception):
pass
class OrgIDGuide():
def __init__(self):
self._request_cache = {}
self._org_id_re = re.compile(r'([^-]+-[^-]+)-(.+)')
self._dac_channel_code_re = re.compile(r'\d{5}')
self._dac_donor_code_re = re.compile(r'([A-Z]... |
from pytest import fixture
from app import factory
@fixture(scope="function")
def test_app():
app = factory.create_app("testing")
with app.app_context():
yield app
|
# Generated by Django 3.2a1 on 2021-03-08 19:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('geodata', '0004_auto_20210302_2017'),
]
operations = [
migrations.AlterField(
model_name='checksumfile',
name='name'... |
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def traverse(node, low, high):
if not node:
return True
if node.val <= low or node.val >= high:
return False
... |
class ShapesList:
def __init__(self):
self.shapes = []
print("In init")
def add(self, s):
print(s)
self.shapes.append(s)
def areas(self):
return [shapes.area() for shapes in self.shapes]
class Triangle:
def __init__(self, b, h):
self.base = ... |
import os
import numpy as np
import tensorflow as tf
import math
from PIL import Image
#import pdb
F = tf.app.flags.FLAGS
"""
Save tensorflow model
Parameters:
* checkpoint_dir - name of the directory where model is to be saved
* sess - current tensorflow session
* saver - tensorflow saver
"""
def save_model(checkpo... |
from unittest import TestCase
import numpy.testing as npt
from itertools import zip_longest
from distancematrix.consumer.contextmanager import GeneralStaticManager
class TestGeneralStaticManager(TestCase):
def test_does_not_return_empty_contexts(self):
r = [range(1, 5), range(0, 0), range(5, 10)]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.