text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- from src import icons, __version__ from src.actions import HOST_URL from src.actions.configure import ConfigureWorkflowAction from src.actions.help import HelpWorkflowAction from src.actions.index import IndexWorkflowAction from src.actions.projects import ProjectWorkflowAction from src.actions....
1,920
542
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import classification_report, confusion_matrix from mlxtend.plotting import plot_decision_regions # from sklearn import datasets from pandas.plotti...
1,262
523
from itertools import count from _pandigital_tools import is_pandigital def pand_products(): """ Returns the sum of all numbers n which have a factorization a * b = n such that a, b, n are (cumulatively) 1 through 9 pandigital. """ total = set() for a in range(2, 100): for b in count(...
547
194
from django.db import models from openstates.data.models import Bill class LegacyBillMapping(models.Model): legacy_id = models.CharField(max_length=20, primary_key=True) bill = models.ForeignKey( Bill, related_name="legacy_mapping", on_delete=models.CASCADE )
282
90
import datetime import logging from collections import defaultdict, namedtuple from django.conf import settings from django.template.loader import render_to_string from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from django_prbac.models import Grant, Role, UserRole from corehq...
14,594
4,472
def extended_euclidean_algorithm(a, b): # Initial s = 1 s = 1 list_s = [] list_t = [] # Algorithm while b > 0: # Find the remainder of a, b r = a % b if r > 0: # The t expression t = (r - (a * s)) // b list_t.append(t) list...
802
277
from ..le_apcf_command_pkt import LE_APCF_Command from struct import pack, unpack from enum import IntEnum """ This pare base on spec <<Android BT HCI Requirement for BLE feature>> v0.52 Advertisement Package Content filter """ class APCF_Service_Data(LE_APCF_Command): def __init__(self): # TODO generate...
435
142
""" DocumentNGramSymWinGraph.py Created on May 23, 2017, 4:56 PM """ import networkx as nx import pygraphviz as pgv import matplotlib.pyplot as plt from networkx.drawing.nx_agraph import graphviz_layout from DocumentNGramGraph import DocumentNGramGraph class DocumentNGramSymWinGraph(DocumentNGramGraph): #...
1,468
425
from __future__ import print_function from troposphere import ( Template, Parameter, Ref, Condition, Equals, And, Or, Not, If ) from troposphere import ec2 parameters = { "One": Parameter( "One", Type="String", ), "Two": Parameter( "Two", Type="String", ), "Thr...
2,212
721
class Student(object): # __init__是一个特殊方法用于在创建对象时进行初始化操作 # 通过这个方法我们可以为学生对象绑定name和age两个属性 def __init__(self, name, age): self.name = name self.age = age def study(self, course_name): print('%s正在学习%s.' % (self.name, course_name)) # PEP 8要求标识符的名字用全小写多个单词用下划线连接 # 但是部分程序员和公司...
768
444
# (c) Copyright IBM Corporation 2020. # LICENSE: Apache License 2.0 (Apache-2.0) # http://www.apache.org/licenses/LICENSE-2.0 import logging from lrtc_lib.data_access import single_dataset_loader from lrtc_lib.data_access.processors.dataset_part import DatasetPart from lrtc_lib.oracle_data_access import gold_labels_...
1,108
376
"""Convert lowered IR basic blocks to MATCH query strings.""" from collections import deque import six from .blocks import Filter, MarkLocation, QueryRoot, Recurse, Traverse from .expressions import TrueLiteral from .helpers import get_only_element_from_collection, validate_safe_string def _get_vertex_location_name(loc...
8,019
2,857
from PokerRL.game.games import StandardLeduc from PokerRL.game.games import BigLeduc from PokerRL.eval.rl_br.RLBRArgs import RLBRArgs from PokerRL.eval.lbr.LBRArgs import LBRArgs from PokerRL.game.bet_sets import POT_ONLY from DeepCFR.EvalAgentDeepCFR import EvalAgentDeepCFR from DeepCFR.TrainingProfile import Training...
3,286
794
import sqlite3 from enum import Enum import random __all__ = ['state_mgr', 'game_state', 'next_state'] class game_state (Enum): NEW_GAME = 0 WAITING_FOR_HOST = 1 HOST_CHOOSING = 2 GUEST_GUESSING = 3 GUEST_CHOOSING = 4 HOST_GUESSING = 5 def next_state(s): if s == game_state.WAITING_FOR_H...
8,436
2,459
"""Tests for callables."""
27
9
''' A compatibility layer for DSS C-API that mimics the official OpenDSS COM interface. Copyright (c) 2016-2019 Paulo Meira ''' from __future__ import absolute_import from .IDSS import IDSS
191
65
from .component import Component, using_scope import tensorflow.compat.v1 as tf tf.disable_v2_behavior() class EmbeddingLayer(Component): def __init__(self, input_size, output_size, name='embedding'): Component.__init__(self, name=name) self.input_size = input_size self.output_size = out...
693
212
from hydrocarbon_problem.env.types_ import Observation, Done, Stream, Column
76
21
''' Copyright (C) 2021 CG Cookie http://cgcookie.com hello@cgcookie.com Created by Jonathan Denning, Jonathan Williamson 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 ...
12,955
4,015
import numpy as np import pytest from pandas import ( DataFrame, Series, concat, ) import pandas._testing as tm @pytest.mark.parametrize("func", ["cov", "corr"]) def test_ewm_pairwise_cov_corr(func, frame): result = getattr(frame.ewm(span=10, min_periods=5), func)() result = result.loc[(slice(Non...
11,414
4,402
# TODO finish implementing query import math from pyspark import SparkContext # from genex.cluster import sim_between_seq from brainex.op.query_op import sim_between_seq from brainex.parse import strip_function, remove_trailing_zeros from .classes import Sequence from brainex.database import genexengine def query(...
6,895
2,167
import sys import time from typing import List import asyncio import ccxt.async_support as ccxt # import ccxt import itertools from enum import Enum class Color(Enum): GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' RESET = '\033[0m' def colorize(s, color: Color): #...
4,161
1,405
WIDTH = 20 HEIGHT = 14 TITLE = 'Click Ninja' BACKGROUND = 'board' def destroy(s): sound('swoosh') if s.name == 'taco': score(50) else: score(5) # draw a splatting image at the center position of the image image('redsplat', center=s.event_pos, size=2).fade(1.0) s.fade(0.25) def ...
1,497
601
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Callable, Dict import torch import torch.nn as nn from nni.retiarii import model_wrapper from nni.retiarii.nn.pytorch import NasBench201Cell __all__ = ['NasBench201'] OPS_WITH_STRIDE = { 'none': lambda C_in, C_out, st...
7,166
2,727
#!/usr/bin/env python3 import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='dialog_py', version='1.0a1', description='Python API for cdialog/linux dialog', long_description=long_de...
1,195
374
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest import nose from nose.tools import * from whoswho import who, config from nameparser.config.titles import TITLES as NAMEPARSER_TITLES class TestMatch(unittest.TestCase): def setUp(self): self.name = 'Robert Evan Liebowitz...
8,334
3,046
import json from flask import request from flask_restful import Resource, abort, reqparse from models.User import User """ POST Creates a new resource. GET Retrieves a resource. PUT Updates an existing resource. DELETE Deletes a resource. """ class UserEndpoint(Resource)...
2,012
572
from django.forms import forms class Form(forms.Form): def get_value(self, name): self.is_valid() # making sure we tried to clean the data before accessing it if self.is_bound and name in self.cleaned_data: return self.cleaned_data[name] field = self[name] ...
450
150
#!/usr/bin/python # Title: ROR/XOR/NOT encoder # File: rorxornotencode.py # Author: Guillaume Kaddouch # SLAE-681 import sys ror = lambda val, r_bits, max_bits: \ ((val & (2**max_bits-1)) >> r_bits%max_bits) | \ (val << (max_bits-(r_bits%max_bits)) & (2**max_bits-1)) shellcode = ( "\x31\xc0\x50\x68\x6e\x2f\...
1,172
545
import datetime from enum import Enum from typing import Any, Callable, Dict, List, Optional, Type, TypeVar, Union, cast import attr import ciso8601 import structlog from attr import converters from . import enums from .utils import as_json_dict, to_snake_case logger = structlog.get_logger() class Omitted(Enum): ...
9,292
2,754
from library import config, ini, lang, log, performance, periphery, queue from asyncio import get_event_loop from threading import Thread, Event from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtWidgets import QTreeWidgetItem # noinspection PyPep8Naming class Signal(QObject): """ PyQt signals for correct...
9,739
3,079
DEPTH = 3 # Action class Action: top = [1, 0, 0, 0] bottom = [0, 1, 0, 0] left = [0, 0, 1, 0] right = [0, 0, 0, 1] actlist = [(-1, 0), (1, 0), (0, -1), (0, 1)] mapAct = { actlist[0]: top, actlist[1]: bottom, actlist[2]: left, actlist[3]: right } def go(s...
3,959
1,270
#!/usr/bin/pyton # Title: # Author: # Additional Authors: # Filename: # Description: # Version: # Date: # Last Modified: # Location_of_the_Video: # Meta_data_for_YouTube: # Web_Site_For_Video: # Start Your Code Here #EOF
224
91
def read_csv(root, file_name, keys): with open('{root}private_static/csv/{file_name}.csv'.format(root=root, file_name=file_name)) as file: data = file.read() lines = data.split("\n") return [dict(zip(keys, line.split(','))) for i, line in enumerate(lines) if i != 0]
289
103
# coding=utf-8 from parser.client import * from parser.client.ResponseItem import * with (Path(__file__).resolve().parent / "config.json").open("rt") as siteConfigFile: SITE_CONFIG = json.load(siteConfigFile) class MasterService(Client): class Link: main = "https://steering.com.ua/" login =...
7,202
2,090
# -*- coding: utf-8 -*- ''' Copyright 2012 Rodrigo Pinheiro Matias <rodrigopmatias@gmail.com> 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 r...
7,320
3,753
import pygame from pygame.locals import * import resourceManager class TextObject(pygame.sprite.Sprite): def __init__(self,pos,fontSize,fontcolor,textstring): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.position = pos self.message = textstring self.color = fon...
1,562
485
from datetime import datetime from jsonschema_serialize_fork import NO_DEFAULT from pyramid.security import effective_principals from pyramid.threadlocal import get_current_request from string import ( digits, ascii_uppercase, ) import random import uuid from snovault.schema_utils import server_default A...
2,268
723
from flask import Flask #from config import Config import config app = Flask(__name__) #app.config.from_object(Config) app.config.from_object(config) #from app import routes from app import gettoken
200
61
"""Todo module."""
19
8
#!/usr/bin/python3.7 ######################################################################################## # pvt_collector/pipe.py - Represents a pipe within the system. # # Author: Ben Winchester # Copyright: Ben Winchester, 2021 ######################################################################################...
680
181
import unittest import os import json import requests import requests_mock from ioapi import api_url, IOService, AuthorizationError, UnexpectedResponseCodeError class APIAccountStateTestCase(unittest.TestCase): def setUp(self): self.service = IOService() @requests_mock.mock() def test_account_st...
1,850
555
''' fake posts to bootstrap a development database. Put any interesting cases useful for development in here. ''' from datetime import datetime POST_DATA_1 = [ { "created" : datetime(2015, 10, 1), "published": datetime(2015, 10, 1), "edited": datetime(2015, 10, 1), "rende...
6,517
2,378
from __future__ import absolute_import from django.shortcuts import render import simplejson import datetime from django.http import HttpResponse class GenericItemBase(object): ITEM_ATTRS = [] def __init__(self, identifier): self.identifier = identifier def jsonify(self, value): """ ...
2,954
883
import math import warnings import numpy as np import pandas as pd from scipy.optimize import minimize import scipy.stats from scipy.stats import norm # edit from scipy.special import log_ndtr from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, mean_absolute_error def sp...
6,061
2,127
# -*- coding: utf-8 -*- import setuptools with open(r'README.md', r'r', encoding="utf8") as stream: long_description = stream.read() setuptools.setup( name=r'hagworm', version=r'3.0.0', license=r'Apache License Version 2.0', platforms=[r'all'], author=r'Shaobo.Wang', author_email=r'wsb310...
1,554
679
""" Simple IoC containers that provide direct access to various Keras providers """ class ModelSavers: from mercury_ml.keras.providers import model_saving save_hdf5 = model_saving.save_keras_hdf5 save_tensorflow_graph = model_saving.save_tensorflow_graph save_tensorrt_pbtxt_config = model_saving.save_...
3,072
933
#!/usr/bin/env python import netfilterqueue import scapy.all as scapy import re def set_load(packet, load): packet[scapy.Raw].load = load del packet[scapy.IP].len del packet[scapy.IP].chksum del packet[scapy.TCP].chksum return packet def process_packet(packet): """Modify downloads files on t...
1,851
618
# Copyright © 2015 Elizabeth Myers. # All rights reserved. # This file is part of the pycardcast project. See LICENSE in the root # directory for licensing information. import asyncio import aiohttp from pycardcast.net import CardcastAPIBase from pycardcast.deck import (DeckInfo, DeckInfoNotFoundError, ...
4,691
1,338
from ctypes import * from .api import api from .const import * from .library import library class TriggerOutput(object): """""" def __init__(self, handle, index): self._handle = handle self._index = index def _get_enabled(self): """ Check whether a trigger output is enabled. """ ...
2,345
709
import time from faker import Faker from radish_ext.radish.step_config import StepConfig from conduit.client import ConduitClient, ConduitConfig class ConduitStepsConfig(StepConfig): def __init__(self, context): super().__init__(context) self._faker = None self.client = ConduitClient(Co...
1,374
433
import requests import credentials class SummaryExternalClient: def pullSummaryForUrl(self, artUrl, title): url = "https://api.aylien.com/api/v1/summarize" headers = {"X-AYLIEN-TextAPI-Application-Key": credentials.AYLIEN_APP_KEY, "X-AYLIEN-TextAPI-Application-ID" : credentials...
1,233
375
import os import sys from conda_build import api from conda_build import render import pytest def test_output_with_noarch_says_noarch(testing_metadata): testing_metadata.meta['build']['noarch'] = 'python' output = api.get_output_file_path(testing_metadata) assert os.path.sep + "noarch" + os.path.sep in o...
1,485
534
def main(): # input A = input() # compute # output if A == 'a': print(-1) else: print('a') if __name__ == '__main__': main()
173
66
#Writing MOOG parameter file for the parameter, abundance, and error calculations. #The parameter file only needs to be written once, at beginning of the routine, because the output #files are overwritten with each itereation of the routine, only minimal output data are needed. # #The user can choose to have the param...
5,057
1,548
"""Plots for optimization lecture.""" import matplotlib.pyplot as plt import numpy as np from matplotlib import cm def plot_contour(f, allvecs, legend_path): """Plot contour graph for function f.""" # Create array from values with at least two dimensions. allvecs = np.atleast_2d(allvecs) X, Y, Z = _g...
1,862
726
"""All functions return a Component so you can easily pipe or compose them. There are two types of functions: - decorators: return the original component - containers: return a new component """ from functools import lru_cache, partial import numpy as np from omegaconf import OmegaConf from pydantic import validate...
7,141
2,226
#coding=utf-8 from __future__ import division """ # OVERLAY UFOS For anyone looking in here, sorry the code is so messy. This is a standalone version of a script with a lot of dependencies. """ import os from AppKit import * #@PydevCodeAnalysisIgnore from vanilla import * #@PydevCodeAnalysisIgnore from mojo.drawingT...
26,640
7,536
import os appdata_path = os.path.expanduser("~/.local/share/nautapy") os.makedirs(appdata_path, exist_ok=True)
114
48
import requests import json import datetime import sys from dateutil.parser import parse as to_datetime try: import pandas as pd except: pass from pyteamup.utils.utilities import * from pyteamup.utils.constants import * from pyteamup.Event import Event class Calendar: def __init__(self, cal_id, api_key):...
9,368
2,674
from . import constant parameters = { 'RegNet' : { "lr": 0.1, "epochs": 100, "weight_decay": 5e-5, "batch_size": 128, "nesterov": True, "init_backbone":True, "init_extractor":True,}, } backbone_config = { "RegNetX002" : {"channels": 3, "dropout": 0.2,}, "RegNetY004" : {"channels": ...
8,232
2,206
# # @section License # # The MIT License (MIT) # # Copyright (c) 2016-2017, Erik Moqvist # # 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 ...
1,608
630
from django.conf.urls import patterns, include, url urlpatterns = patterns('reports.views', url(r'^index/*$', 'index'), url(r'^dashboard/*$', 'dashboard'), url(r'^$', 'index'), url(r'^detail/(?P<serial>[^/]+)$', 'detail'), url(r'^detailpkg/(?P<serial>[^/]+)/(?P<manifest_name>[^/]+)$', 'detail_pkg')...
740
304
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import multiprocessing import pytest import socket import signal import os import logging try: from urllib2 import URLError, urlopen except ImportError: from urllib.error import URLError from urllib.request import urlopen from flask import _request...
5,812
1,746
from .exceptions import ( ServerResponseError, InternalServerError, NonXMLResponseError, EndpointUnavailableError, ) from functools import wraps from xml.etree.ElementTree import ParseError from ..query import QuerySet import logging try: from distutils2.version import NormalizedVersion as Version ...
7,700
2,157
import unittest from freeplane_importer.importer import Importer from mock import Mock from mock import MagicMock from mock import call from freeplane_importer.model_not_found_exception import ModelNotFoundException class TestImporter(unittest.TestCase): def setUp(self): self.mock_collection = Mock() ...
4,617
1,520
import argparse import numpy as np from scipy.stats import linregress import matplotlib.pyplot as plt parser = argparse.ArgumentParser() parser.add_argument("--plot", action="store_const", default=False, const=True) args = parser.parse_args() data = np.loadtxt("../data/data.csv", skiprows=1, usecols=list(range(1,8)),...
1,089
464
from jedi.inference.base_value import ValueSet, NO_VALUES from jedi.common import monkeypatch class AbstractLazyValue(object): def __init__(self, data, min=1, max=1): self.data = data self.min = min self.max = max def __repr__(self): return '<%s: %s>' % (self.__class__.__name_...
1,716
555
import matplotlib.lines as lines import matplotlib.pyplot as plt COLOR_CLASSIFICATIONS = [ 'black', # Unclassified 'blue', # Classified True (1) 'red' # Classified False (0) ] def generate_line(ax, p0, p1, color='black', style='-'): ''' Generates a line between points p0 and p1 which...
1,901
673
import sys import os import re import json import pickle import tempfile import itertools import contextlib import xml.etree.cElementTree as cET from copy import deepcopy from xml.etree import ElementTree as ET from pprint import pformat from .constants import ( MARKER_COLOR, MARKER_DURATION, MARKER_NAME, ...
27,392
8,047
import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns if len(sys.argv) != 3: print('usage: python plot_performances.py <group_csv> <indiv_csv>') exit() group_file = sys.argv[1] indiv_file = sys.argv[2] # Load the data df_group = pd.read_csv(group_file) df_i...
1,287
549
from Aion.utils.data import getADBPath import subprocess def dumpLogCat(apkTarget): # Aion/shared/DroidutanTest.py # Define frequently-used commands # TODO: Refactor adbID adbID = "192.168.58.101:5555" adbPath = getADBPath() dumpLogcatCmd = [adbPath, "-s", adbID, "logcat", "-d"] clearLogca...
611
237
from collections import OrderedDict import pytest import vcr try: # Python 2.7 # requests's ``json()`` function returns strings as unicode (as per the # JSON spec). In 2.7, those are of type unicode rather than str. basestring # was created to help with that. # https://docs.python.org/2/library/func...
1,969
620
# # Copyright 2015 Naver Corp. # # 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...
3,165
1,099
import os import sys import numpy as np import matplotlib.pyplot as plt import flopy def run(): workspace = os.path.join("lake") # make sure workspace directory exists if not os.path.exists(workspace): os.makedirs(workspace) fext = "png" narg = len(sys.argv) iarg = 0 if narg > 1:...
5,509
2,006
# -*- coding: utf-8 -*- ''' Documentación sobre clustering en Python: http://scikit-learn.org/stable/modules/clustering.html http://www.learndatasci.com/k-means-clustering-algorithms-python-intro/ http://hdbscan.readthedocs.io/en/latest/comparing_clustering_algorithms.html https://joernhees.de...
11,428
4,501
""" preprocess of (single lead) ecg signal: band pass --> remove baseline --> find rpeaks --> denoise (mainly deal with motion artefact) TODO: 1. motion artefact detection, and slice the signal into continuous (no motion artefact within) segments 2. to add References: ----------- [1] https://github...
9,029
3,316
## mv to //:WORKSPACE.bzl ocaml_configure load("//ocaml/_bootstrap:ocaml.bzl", _ocaml_configure = "ocaml_configure") # load("//ocaml/_bootstrap:obazl.bzl", _obazl_configure = "obazl_configure") load("//ocaml/_rules:ocaml_repository.bzl" , _ocaml_repository = "ocaml_repository") # load("//ocaml/_rules:opam_confi...
761
287
from metrician.explainations.tests import *
44
13
import tensorflow as tf from .. src.align import detect_face from .. src import facenet from .. simple import download_model import sys import os from os.path import expanduser import copy import cv2 import numpy as np from scipy import spatial minsize = 20 # minimum size of face threshold = [0.6, 0.7, 0.7] # three ...
3,021
1,051
class AthenaError(Exception): """base class for all athena exceptions""" pass class AthenaMongoError(AthenaError): """Class for all mongo related errors""" pass
172
54
from .aggregated_stats import * from .game_stats import * from .stat_definitions import *
89
26
"""Test Manage All-Link Record.""" import unittest from binascii import unhexlify from pyinsteon.address import Address from pyinsteon.constants import AckNak, ManageAllLinkRecordAction, MessageId from pyinsteon.protocol.messages.all_link_record_flags import \ AllLinkRecordFlags from tests import set_log_levels fr...
1,515
548
#!/usr/bin/env python # coding: utf-8 # # Figure Info. # # | Title | Journal | Authors | Article Date | Code Date | Figure | Links | # |:------|:-------:|:-------:|:------------:|:---------:|:------:|:-----:| # |A microfluidic approach for experimentally modelling <br> the intercellular coupling system of a mammalian...
5,054
2,126
from django.shortcuts import render, HttpResponse, HttpResponseRedirect from django.template import loader from django.conf import settings from django.contrib.auth.models import User from rameniaapp.models import ReviewReport, ProfileReport, NoodleReport, Report, Review, Profile, Noodle from django.views.generic impor...
10,733
3,005
#!/usr/bin/python # # This tool is an attempt to automate some taks related # to malware unpacking. # # Most (if not all) of the tricks used in this tool # directly comes from an excellent course given # by Nicolas Brulez (@nicolasbrulez) # # Tool developped by David DURVAUX for Autopsit # (commercial brand of N-Labs...
10,135
3,628
from ._head_base import HeadComponent __all__ = ['MjStyle'] class MjStyle(HeadComponent): @classmethod def default_attrs(cls): return { 'inline' : '', } def handler(self): add = self.context['add'] inline_attr = 'inlineStyle' if (self.get_attr('inl...
512
153
# Copyright 2020 Huawei Technologies Co., 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...
3,399
1,085
import torch from torch.nn import functional as F from torch.utils.data import Dataset from gensim.corpora.dictionary import Dictionary class LangDataset(Dataset): def __init__(self, src_sents, trg_sents, max_len=-1): self.src_sents = src_sents self.trg_sents = trg_sents # Create the voca...
2,273
751
# MINLP written by GAMS Convert at 08/20/20 01:30:45 # # Equation counts # Total E G L N X C B # 297 170 42 85 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
74,691
42,494
import logging import os import shutil import subprocess import pytest import salt.utils.platform log = logging.getLogger(__name__) @pytest.fixture(scope="package", autouse=True) def skip_on_tcp_transport(request): if request.config.getoption("--transport") == "tcp": pytest.skip("Multimaster under the T...
4,322
1,522
import game_framework from pico2d import * import title_state name = "StartState" image = None logo_time = 0.0 def enter(): global image image = load_image('kpu_credit.png') def exit(): global image del(image) def update(): global logo_time if (logo_time > 1.0): logo_time = 0.8 ...
1,210
455
#!/usr/bin/env python3 # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
22,620
9,069
import configparser class Settings: '''The Settings class is a wrapper for configparser and it's functions. This class simplifies the tasks of loading, storing and manipulating settings data.''' def __init__(self, filename): '''Create a new Settings object with a specific file name.''' ...
1,944
462
from __future__ import print_function import itertools from demisto_sdk.commands.common.constants import VALIDATED_PACK_ITEM_TYPES from demisto_sdk.commands.common.errors import Errors from demisto_sdk.commands.common.hook_validations.base_validator import \ BaseValidator from demisto_sdk.commands.common.tools im...
3,900
1,072
import numpy as np class ProjectionMatrix(): """This matrix provides projection distortion. Projection distortion is when things that are far away appear smaller and things that are close appear bigger. This works flawlessly so far. Takes in screen-size and provides near- and far clipping. fov is f...
14,326
4,789
from xml.dom import minidom import pywikibot from api.decorator import time_this SiteMock = pywikibot.Site class PageMock(pywikibot.Page): def __init__(self, *args, **kwargs): super(PageMock, self).__init__(*args, **kwargs) self.filename = "test_data/test_pages_%s.xml" % self.site.lang ...
1,652
515
import os from functools import partial from io import BytesIO import numpy as np import PIL.Image import scipy.misc import tensorflow as tf graph = tf.Graph() sess = tf.InteractiveSession(graph=graph) model_fn = "./models/tensorflow_inception_graph.pb" with tf.gfile.FastGFile(model_fn, 'rb') as f: graph_def = tf...
5,796
2,718
import calendar import datetime import logging import os import webapp2 import dbmodel TESTING = os.environ.get('SERVER_SOFTWARE', '').startswith('Development') class ResetHandler(webapp2.RequestHandler): def get(self): timestamp = calendar.timegm(datetime.datetime.utcnow().timetuple()) self.re...
1,829
535
from dataclasses import dataclass from itertools import cycle from typing import Dict, Union import numpy as np from ...layers.utils.color_transformations import ( transform_color, transform_color_cycle, ) @dataclass(eq=False) class ColorCycle: """A dataclass to hold a color cycle for the fallback_color...
2,708
827