content
stringlengths
0
894k
type
stringclasses
2 values
import time to_year = time.strftime("%Y", time.localtime()) # 返回单一用户信息,传入的是user实例 def single_counselors_to_dict_with_user(item, year=to_year): lic = [] for i in item.counselors_workload_user: if i.year == year: lic.append( { 'id': item.id, ...
python
# 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. import os from typing import List FPP_DIR = os.environ.get("FPP_DIR") or "~/.cache/fpp" PICKLE_FILE = ".pickle" SELECTION_PICKLE = ".selection...
python
import tkinter as tk if __name__ == '__main__': master = tk.Tk() dict_entries = { 'item 1': int, 'item 2': str, } master.title('Hello World!') i = 0 dict_tk_entry = {} for key, val in dict_entries.items(): tk.Label(master, text=str(key)).grid(row=i) dict_...
python
import base64 import os import numpy import sys import traceback from database import Database import queue import threading import os from time import sleep import pymysql import json class MysqlDatabase(Database): def __init__(self, crypto, db_path='localhost', db_name='iotdatabase', db_password='abc123', db_use...
python
import unittest import asyncio from pathlib import Path import glob import datetime import os #Third Party Imports from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import scoped_session, sessionmaker import pandas as pd #Loca...
python
from threading import Timer class Delayed(object): """ Does a delayed Lua function call """ def __init__(self, seconds, lua_function, lua, start=True): """ :param seconds: Number of seconds to wait :param lua_function: The Lua function to execute :param lua: The Lua ru...
python
import argparse import chainer import chainer.functions as F import chainer.links as L from chainer import training from chainer.training import extensions from einconv import Einconv NUM_CLASSES = 10 # Network definition class MLP(chainer.Chain): def __init__(self, graph, shapes, initializer=None): s...
python
""" The :mod:`sklearn.preprocessing` module includes scaling, centering, normalization, binarization methods. """ from ._function_transformer import FunctionTransformer from ._data import Binarizer from ._data import KernelCenterer from ._data import MinMaxScaler from ._data import MaxAbsScaler from ._data...
python
import Foundation import objc from PyObjCTools.TestSupport import TestCase, min_os_level class TestNSRegularExpression(TestCase): @min_os_level("10.7") def testConstants10_7(self): self.assertEqual(Foundation.NSRegularExpressionCaseInsensitive, 1 << 0) self.assertEqual( Foundation....
python
from .dispatcher import CommandDispatcher, CommandDispatchError, UnknownCommandError from .command import Command from .call_match import CallMatch, CallMatchFail from .call_matcher import CallMatcher from .command import TooManyArguments from .syntax_tree.literal import MissingLiteral, MismatchedLiteral, MismatchedLi...
python
import json from django.test.utils import override_settings from hc.api.models import Channel from hc.test import BaseTestCase from mock import patch @override_settings(ZENDESK_CLIENT_ID="t1", ZENDESK_CLIENT_SECRET="s1") class AddZendeskTestCase(BaseTestCase): url = "/integrations/add_zendesk/" def test_ins...
python
import argparse from utils import load_data, init_model, train_model, save_model, is_cuda_available def str2bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else...
python
import sys, os, traceback, itertools from os import walk import json import subprocess32 as subprocess from shutil import copyfile import hashlib as h from common import * import uuid MAX_TASKS_PER_PROBLEM = 20 TOTAL_SMT = 0 TOTAL_PROBLEM = 0 TOTAL_TASK = 0 TOTAL_NO_TASK = 0 from haikunator import Haikunator hai...
python
from itertools import permutations def scrambled_letters_and_hash(inp, pwd): if not isinstance(pwd, list): pwd = list(pwd) for inst in inp: parts = inst.split() nums = [int(a) for a in parts if a.isdigit()] if parts[0] == 'swap': if parts[1] == 'position': ...
python
'''Collection of methods used for aquiring data for training and testing. ''' import os import numpy as np import pandas as pd def get_local_files(base_path): '''Gets a list of files in the specified directory and all sub-directories. Args: base_path (string): The base directory to search for files...
python
import os import subprocess def signfind(x): if x<0: return '-' else: return '+' def main(): avgnoise=subprocess.check_output('soundmeter --collect --seconds 3 | grep avg',shell=True) strbuff=str(avgnoise) print(strbuff) print('*********************') noisevolprev=int(str...
python
from app import db class File(db.Model): id = db.Column(db.Integer, primary_key=True) file_hash = db.Column(db.String(64), index=True, unique=True) block_hash = db.Column(db.String(64)) block_index = db.Column(db.Integer) txn_index = db.Column(db.Integer)
python
import time import subprocess import os import sys import RPi.GPIO as GPIO from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor ROTATION_COUNT = 3600 # Raspberry Pi PGIO ports LED_GREEN = 0 LED_RED = 0 STEPPER = 0 SWITCH = 0 LASER = 0 state = State.Ready class State: Read...
python
import aiohttp import aiofiles import asyncio import os async def download_html(session: aiohttp.ClientSession, url: str): # Get http async with session.get(url, ssl=False) as res: filename = f'output/{os.path.basename(url)}.html' # Async write to file, using url as filename async with...
python
# Copyright (c) 2013 Red Hat, Inc. # # 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 to in writ...
python
from machine import Pin l=Pin(0,Pin.OUT) l.high() l.low() l.value() l.value(1) l.value(0) #按钮 #GPIO 1 和 按钮 和 GND相连 b=Pin(1,Pin.OUT) b.value(1) b.value() #按钮按下 b.value() # 应用 按钮按下灯亮 while 1: if b.value(): l.value(1) else: l.value(0)
python
#!/user/bin/env python # -*- coding: utf-8 -*- from opensourcetest.builtin.autoParamInjection import AutoInjection class Login(AutoInjection): def __init__(self): super(Login, self).__init__(self.__class__.__name__) if __name__ == '__main__': ...
python
# my cnctoolbox script! # c = compiler t = gcodetools grbl = self.grbl import math thickness = 1 steps = 20 gcodes = [] gcodes.append("M3") gcodes.append("S0") gcodes.append("G0X0Y0") gcodes.append("F500") gcodes.append("G1") self.new_job() def spiral(cx, cy, r1, r2, windings, direction): gcode = [] s...
python
# -*- coding: utf-8 -*- import pytest @pytest.fixture def vsphere_host(): from ati.terraform import vsphere_host return vsphere_host @pytest.fixture def vsphere_resource(): return { "type": "vsphere_virtual_machine", "primary": { "id": "12345678", "attributes": { ...
python
from typing import List, Optional, Tuple import requests from NotionPy import constants from NotionPy.utils import parse_into_dict, parse_into_json class Query: """ class that retrieves data from page or database with option to get it json or dict like data """ TOKEN = None def __init__(se...
python
# Handcrafted _version.py to fix # https://github.com/conda-forge/ambertools-feedstock/issues/35 import json import sys version_json = """ { "date": "2020-02-26T10:02:00+0100", "dirty": false, "error": null, "full-revisionid": "aa15556ab201b53f99cf36394470c341526b69ed", "version": "3.2.0+27" } """ # END VERSION...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import autoslug.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Constituency', fields=[ ...
python
from django.contrib import admin from .models import ObjectViewed,UserSession admin.site.register(ObjectViewed) admin.site.register(UserSession)
python
from collections import defaultdict from logging import getLogger from typing import Dict, Mapping from ordered_set import OrderedSet from squares.tyrell.spec import Type, TyrellSpec logger = getLogger('squares.conditions') class ConditionTable: def __init__(self) -> None: self.graphs = defaultdict(la...
python
""" When running in term-mode (import `pwn` rather than `pwnlib`, stdout is a TTY and not running in a REPL), we can do proper indentation where lines too long to fit on a screen are split into multiple individually indented lines. Too see the difference try running with:: $ python indented.py and $ python -i i...
python
#!/usr/bin/env python import datetime import os import cv2 import time import rospy import numpy as np from bolt_msgs.msg import Control from std_msgs.msg import Int32 from sensor_msgs.msg import Image import sys sys.path.append('../neural_net/') import const from image_converter import ImageConverter from drive_ru...
python
''' MIT License Copyright (c) 2019 Arshdeep Bahga and Vijay Madisetti 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, mo...
python
import io import json import torch from torchvision import models import torchvision.transforms as transforms import numpy as np from PIL import Image imagenet_class_index = json.load(open('imagenet_class_index.json')) model = models.densenet121(pretrained=True) model.eval() def transform_image(image_path): tra...
python
""" Configure file for hypoDD interface """ import os import numpy as np class Config(object): def __init__(self): # 1. format input self.fsta_in = 'input/HYPO.sta' self.fsta_out = 'input/station.dat' self.fpha_in = 'input/merge.pha' self.fpha_out = 'input/phase.dat' self.dep_corr = 5 # avoi...
python
def plot(self, game): """ matplotlib plot representation of the resource game """ # Create figure and axes fig, ax = plt.subplots() pc = self.player_cover(strategies) colors = mcolors.cnames.keys() for i in range(self.r_m): width = 10 height = len(pc[i])*10 + 4 x, y = (15...
python
# -*- coding: utf-8 -*- """ Created on Thu Jan 28 15:08:07 2021 @author: saadl """ import inspect import itertools import os import sys import unittest import numpy as np from tqdm import tqdm currentdir = os.path.dirname(os.path.abspath( inspect.getfile(inspect.currentframe()))) parentdir = os....
python
__copyright__ = \ """ Copyright &copyright © (c) 2019 The Board of Trustees of Purdue University and the Purdue Research Foundation. All rights reserved. This software is covered by US patents and copyright. This source code is to be used for academic research purposes only, and no commercial use is allowed. For any ...
python
# sorting algorithm -> mergesort # About mergesort: Best case O(n log n), Average case O(n log n), Worst case O(n log n) # @author unobatbayar # Thanks to HackerRank's mergesort tutorial title = 'Welcome to Mergesort Algorithm!' print(title + '\n' + 'Enter unsorted data set: ') user_input = input() array = user_inpu...
python
from neo4j_engine import Neo4JEngine from os import path import pandas as pd import numpy as np import pathlib from utils import parse_data, extract_gpa_data, merge_gpa_data from tqdm import tqdm # not official courses, but need to be taken into account special_prereqs = ['THREE YEARS OF HIGH SCHOOL MATHEMATICS', 'ON...
python
import json import datetime from collections import defaultdict from itertools import groupby from odoo import api, fields, models, _ from odoo.exceptions import AccessError, UserError from odoo.tools import date_utils, float_compare, float_round, float_is_zero class ReportBomStructure(models.AbstractModel): _inh...
python
# Common shapes for the aafigure package. # # (C) 2009 Chris Liechti <cliechti@gmx.net> # # This is open source software under the BSD license. See LICENSE.txt for more # details. # # This intentionally is no doc comment to make it easier to include the module # in Sphinx ``.. automodule::`` import math def point(obj...
python
import json from collections import OrderedDict from keycloak.admin import KeycloakAdminBase __all__ = ('Users',) class Users(KeycloakAdminBase): _paths = { 'collection': '/auth/admin/realms/{realm}/users' } _realm_name = None def __init__(self, realm_name, *args, **kwargs): self._...
python
import requests import json from .helper import Helper class Tasks(Helper): def __init__(self, base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination): super().__init__(base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination) def empty_tasks_trash(self, project...
python
from .util import * class __THMTeam(object): def get_teams(self) -> list: """ Returns all teams :return: List containing all teams """ return http_get(self.session, '/api/all-teams')
python
import dht11 import RPi.GPIO as GPIO import time from datetime import date, datetime from pathlib import Path import math import pickle import numpy as np sleep_time_high = 0.5 model_filename = r'/home/pi/code/raspi/4/models/zing_brightness_v0.pkl' # motor pins motor_in1 = 11 motor_in2 = 13 motor_in3 = 15 motor_i...
python
import datetime from decimal import Decimal import pytest from leasing.enums import ContactType, InvoiceState, InvoiceType from leasing.models import Invoice, ReceivableType from leasing.models.invoice import InvoiceSet @pytest.mark.django_db def test_create_credit_invoice_full(django_db_setup, lease_factory, conta...
python
import json def is_string_or_unicode(s): """ Determine whether or not this object is a string or unicode. :param s: object :return: bool """ return isinstance(s, basestring) def is_json(s): """ Determine whether or not this object can be converted into JSON. :param s: object ...
python
from errno import ENOENT class InvalidArchiveError(Exception): """Raised when libarchive can't open a file""" def __init__(self, fn, msg, *args, **kw): msg = ("Error with archive %s. You probably need to delete and re-download " "or re-create this file. Message from libarchive was:\n\...
python
import sqlalchemy as sql import sqlalchemy.sql.functions as db_func from schools3.config.data import db_tables from sqlalchemy.dialects.postgresql import aggregate_order_by def get_student_data(grade_bounds): metadata = sql.MetaData() all_snapshots = db_tables.clean_all_snapshots_table hs_grade_gpa = get...
python
import sys sys.path.append("../") from appJar import gui with gui("FRAME DEMO", "250x150", bg='yellow') as app: with app.frame("LEFT", row=0, column=0, bg='blue', sticky='NEW', stretch='COLUMN'): app.label("Label on the left 1", bg='red') app.label("Label on the left 2", bg='orange') app....
python
""" Copyright 2018 Skyscanner 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 or agreed to in writing, software dis...
python
from mojo.roboFont import CurrentGlyph from plum import Plum Plum(CurrentGlyph()).toggle()
python
from collections import OrderedDict from sympy import symbols, Range from sympy import Tuple from sympde.topology import Mapping from sympde.topology import ScalarFunction from sympde.topology import SymbolicExpr from sympde.topology.space import element_of from sympde.topolo...
python
import unittest from unittest import mock from stapy.sta.post import Post from stapy.sta.entity import Entity from stapy.sta.request import Request import stapy.sta.entities as ent class PostMock(object): def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = sta...
python
# Create your views here. from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.forms import ModelForm, modelformset_factory from django.urls import reverse from .models import Tweets, StreamFilters from Mining.twitter_miner import T...
python
import math def quadratic(a, b, c): DT=b*b-4*a*c if DT<0: print('此方程无解') else : return (math.sqrt(DT)-b)/(2*a),(-math.sqrt(DT)-b/(2*a)) print(quadratic(1,3,2))
python
import sqlite3 conn = sqlite3.connect(":memory:") cur = conn.cursor() cur.execute("create table stocks (symbol text, shares integer, price real)") conn.commit()
python
# -*- coding: utf-8 -*- """ How do plugins work? There are a few patterns we use to "register" plugins with the core app. Entry Points 1. Plugins can use entry_points in the setup, pointing to "pioreactor.plugins" 2. Automations are defined by a subclassing the respective XXXAutomationContrib. There is a hook i...
python
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.urls import include, path from django.contrib.auth import views as auth_views from django.contrib import admin urlpatterns = [ path('', lambda request: HttpResponse("Hello World", content_type="text/plain"))...
python
""" Bulky data structures for assertion in pyteomics test suites. """ import numpy as np from copy import deepcopy import sys from pyteomics.auxiliary import basestring # http://stackoverflow.com/q/14246983/1258041 class ComparableArray(np.ndarray): def __eq__(self, other): if not isinstance(other, np.nd...
python
from exemplo1 import Soma, Dividir Soma(2,2) Dividir(2,0)
python
# File: main.py # Author: Lorè Francesco # Program to build a simplified and proof-of-concept software application # for managing an electronic table reservation book for a restaurant in the evening of a specific day. # The software is composed of a user interface and business logic part # written in Pyth...
python
import os from setuptools import setup root_dir_path = os.path.dirname(os.path.abspath(__file__)) try: import pypandoc long_description = pypandoc.convert("README.md", "rst") except(IOError, ImportError): long_description = open(os.path.join(root_dir_path, "README.md")).read() with open(os.path.join(root...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 25 18:11:31 2019 @author: franchesoni """ import numpy as np import os import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import from matplotlib import cm from matplotlib import rc,...
python
import logging import pytest from config import NOMICS_API_KEY from nomics import Nomics @pytest.fixture def nomics(): return Nomics(NOMICS_API_KEY) def test_get_markets(nomics): data = nomics.Markets.get_markets(exchange = 'binance') assert isinstance(data, list) assert len(data) > 0 def test_get_m...
python
from abc import ABC, abstractmethod import time import yaml from koala.typing import * from koala import utils from koala.server import rpc_meta def _get_registered_services() -> Dict[str, str]: all_types = rpc_meta.get_all_impl_types() return {i[0]: i[1].__qualname__ for i in all_types} class KoalaConfig(A...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-06-14 10:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dataset', '0013_motionfile_is_hidden'), ] operations = [ migrations.CreateMo...
python
# # PySNMP MIB module UCD-DLMOD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UCD-DLMOD-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:28:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
python
""" # @Time : 2020/8/28 # @Author : Jimou Chen """ import scrapy from bs4 import BeautifulSoup from testScrapy.items import TestscrapyItem class CommentSpider(scrapy.Spider): name = 'comment_spider' start_urls = ['https://book.douban.com/subject/35092383/annotation'] custom_settings = { "US...
python
x = 20 print(x)
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayPayApplepayTransactionauthtokenCreateModel(object): def __init__(self): self._device_identifier = None self._provisioning_bundle_identifier = None self._provisioning...
python
import sys from calm.dsl.constants import CACHE from calm.dsl.decompile.render import render_template from calm.dsl.store import Cache from calm.dsl.log import get_logging_handle from calm.dsl.decompile.ref_dependency import get_package_name LOG = get_logging_handle(__name__) def render_ahv_vm_disk(cls, boot_config...
python
""" Class FuzzyData """ import numpy as np from kernelfuzzy.fuzzyset import FuzzySet from kernelfuzzy.memberships import gaussmf class FuzzyData: _data = None # I dont know if we want to keep this _fuzzydata = None _epistemic_values = None # only for epistemic fuzzy sets ...
python
"""Convergence diagnostics and model validation""" import numpy as np from .stats import autocorr, autocov, statfunc from copy import copy __all__ = ['geweke', 'gelman_rubin', 'effective_n'] @statfunc def geweke(x, first=.1, last=.5, intervals=20): """Return z-scores for convergence diagnostics. Compare th...
python
import keras.backend as k from keras.models import load_model from keras.engine.topology import Input from keras.engine.training import Model from keras.layers.convolutional import Conv2D from keras.layers.core import Activation, Dense, Flatten from keras.layers.merge import Add from keras.layers.normalization import ...
python
#!/usr/bin/env python3 import scrape_common as sc print('TG') d = sc.download('https://www.tg.ch/news/fachdossier-coronavirus.html/10552') sc.timestamp() d = d.replace('&nbsp;', ' ') # 2020-03-25 """ <li>Anzahl bestätigter Fälle: 96</li> <p><em>Stand 25.3.20</em></p> """ # 2020-04-03 """ <div class...
python
from abc import ABCMeta, abstractmethod class RedditWikiClass(object): __metaclass__ = ABCMeta @abstractmethod def create_from_wiki(self, row, **kwargs): pass @abstractmethod def get_id(self): pass
python
""" Run training/inference in background process via CLI. """ import abc import attr import os import subprocess as sub import tempfile import time from datetime import datetime from typing import Any, Callable, Dict, List, Optional, Text, Tuple from PySide2 import QtWidgets from sleap import Labels, Video, LabeledFr...
python
import requests from xml.etree import ElementTree import collections from dateutil.parser import parse Episode = collections.namedtuple('Episode', 'title link pubdate') def main(): dom = get_xml_dom('https://talkpython.fm/rss') episodes = get_episodes(dom) for idx, e in enumerate(episodes[:5]): ...
python
from typing import Any, Dict, Generic, Optional, Type, Union from flair.data import Corpus from numpy import typing as nptyping from typing_extensions import Literal from embeddings.data.data_loader import ( ConllFlairCorpusDataLoader, DataLoader, PickleFlairCorpusDataLoader, ) from embeddings.data.datase...
python
# This has been shanked off of the Electrum codebase in order to get # pubkey_to_address(), which supports bech32 addresses. It is MIT licensed, but # only pieces of it are copied and assembled here. import hashlib from enum import IntEnum from typing import Union from electrum import constants from electrum import ...
python
import csv import urllib import subprocess import sys import os from datetime import datetime, timedelta # Get args if str(sys.argv[1]).isalnum(): source = sys.argv[1] sources = {'comb' : 'comb_ats', 'jpl' : 'jpl_ats', 'sopac' : 'sopac_ats'} src = str(sources[source]) if os.path.exists(src+'.jso...
python
# manually build and launch your instances # remember that the ip field deals with a private ip def _get_parameter(node_id, private_ip, min_key, max_key): p = {"id": node_id, "ip": private_ip, "min_key": min_key, "max_key": max_key} return p def create_instances_parameters(): """ first = _get_param...
python
from typing import List, Union, Callable, Tuple from thinc.types import Ints2d from thinc.api import Model, registry from ..tokens import Doc @registry.layers("spacy.FeatureExtractor.v1") def FeatureExtractor(columns: List[Union[int, str]]) -> Model[List[Doc], List[Ints2d]]: return Model("extract_features", forw...
python
from sqlalchemy import Column, Integer, String from sqlalchemy.orm.exc import NoResultFound from modules.db import BaseModel, Model, session_factory class Session(BaseModel, Model): __tablename__ = 'bookmark_sessions' id = Column(Integer, primary_key=True) account_id = Column(Integer) sessi...
python
############### Our Blackjack House Rules ##################### ## The deck is unlimited in size. ## There are no jokers. ## The Jack/Queen/King all count as 10. ## The the Ace can count as 11 or 1. ## Use the following list as the deck of cards: ## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] ## The cards i...
python
''' ClearSky Version 2 Created by Marissa Klein, Wellesley College 2022 Intended use is getting evening forecast for the next week ''' import requests import json from geopy.geocoders import Nominatim class ClearSky: def __init__(self): pass def locationGet(self,loc): ...
python
# -*- coding: utf-8 -*- from apiclient import discovery from httplib2 import Http from maya import parse, when, get_localzone from pytz import all_timezones from util import set_http class GoogleAPI: """Interface to the Google API. See the documentation for subclasses for more detailed information. """...
python
import torch import torch.nn as nn import torch.nn.functional as F from itertools import cycle from time import clock as tick import numpy as np from experiments.launcher.config import DatasetConfig from src.eval.utils_eval import evaluate_data_classifier, evaluate_domain_classifier from src.plotting.utils_plotting imp...
python
from unittest import TestCase, skip from unittest.mock import Mock, patch from tests import _run from tests import * _jobs = jobs from porerefiner import models, jobs, fsevents from porerefiner.fsevents import PoreRefinerFSEventHandler as Handler from hypothesis import given, strategies as strat, example, seed, se...
python
""" Compare the results provided by the different solvers """ from tqdm import tqdm import pickle from sys import path path.append("..") path.append("solvers/") import settings from solvers.solver import SimulatedAnnealingSolver, RandomSolver from solvers.uncertainty_solver import UncertaintySimulatedAnnealingSolver...
python
# Manipulação do Arquivo def abrir(path): """ Tenta abrir o arquivo no caminho que recebe. Caso não encontre o arquivo, Cria um arquivo com o nome no caminho especificado. :param path: Local onde o arquivo está ou será criado. """ try: a = open(path, 'tr') return False exce...
python
__________________________________________________________________________________________________ Runtime: 388 ms Memory Usage: 18.5 MB class Solution: def maxLevelSum(self, root: TreeNode) -> int: mapping = {} self.helper(mapping, root, 1) max_val, max_level = -9999999, 0 for level...
python
import socket import dns import dns.resolver from .logbase import LogBase from threading import Lock from typing import Dict, List, Any from datetime import timedelta TTL_HOURS = 12 class Resolver(LogBase): def __init__(self, time): self.cache: Dict[str, Any] = {} self.overrides: Dict[str, List[...
python
# -*- coding: utf-8 -*- import json import sys import argparse import numpy import bpy import bmesh # These are the RGB values that JMol uses to color atoms JMOL_COLORING = { "H": [255, 255, 255], "He": [217, 255, 255], "Li": [204, 128, 255], "Be": [194, 255, 0], "B": [255, 181, 181], "C": [...
python
import pytest from argus.db.db_types import NodeDescription, NemesisStatus, NemesisRunInfo from pydantic import ValidationError from dataclasses import asdict from collections import namedtuple from time import time def test_node_description(): node = NodeDescription(name="test", ip="1.1.1.1", shards=10) asse...
python
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from genera_tablas import Club from genera_tablas import Jugador import json # se importa información del archivo configuracion from configuracion import cadena_base_datos # se genera en enlace al gestor de base de # datos # para el ejempl...
python
from dagster import job, lambda_solid, pipeline, repository @lambda_solid def do_something(): return 1 @pipeline(name="extra") def extra_pipeline(): do_something() @job def extra_job(): do_something() @repository def extra(): return {"pipelines": {"extra": extra_pipeline}, "jobs": {"extra_job": ...
python
import requests from datetime import datetime from elasticsearch import Elasticsearch es = Elasticsearch(host='0.0.0.0',port=9201) r = requests.get(url).json()['res']['res'] actions = [] for i,e in enumerate(r): actions.append( { "_index": "dummy", "_type": "dum", "_id...
python
from .replacer import replace_text
python