input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
service can identify.
"""
self.languages = languages
@classmethod
def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages':
"""Initialize a IdentifiableLanguages object from a json dictionary."""
args = {}
if 'languages' in _dict:
args['languages'] = [
IdentifiableLanguage.from_dict(x)
for x in _dict.get('... | |
weight of the core, e.g. ``self.minw``, the
selector is marked as garbage and will be removed in
:func:`filter_assumps`. Otherwise, the clause is split as
described in [1]_.
"""
# new relaxation variables
self.rels = []
for l in self.core_sels:
if self.wght[l] == self.minw:
# marking variable as being a part... | |
def _make_date(dattim):
"""Make a date object from GEMPAK DATTIM integer."""
return GempakFile._convert_dattim(dattim).date()
@staticmethod
def _make_time(t):
"""Make a time object from GEMPAK FTIME integer."""
string = '{:04d}'.format(t)
return datetime.strptime(string, '%H%M').time()
def _unpack_real(self, ... | |
<reponame>jaredlunde/cargo-orm
"""
`Cargo ORM Relationships`
--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--
2015 <NAME> © The MIT License (MIT)
http://github.com/jaredlunde
"""
import copy
import importlib
from functools import lru_cache
from pydoc import locate, ErrorDuringImpor... | |
# Shift the boundaries of the grid for the Galilean frame
if self.use_galilean:
self.shift_galilean_boundaries( 0.5*dt )
# Get the charge density at t = (n+1) dt
self.deposit('rho_next', exchange=(use_true_rho is True))
# Correct the currents (requires rho at t = (n+1) dt )
if correct_currents:
fld.correct_curr... | |
<filename>Database/DB_dev.py<gh_stars>1-10
import pprint
pp = pprint.PrettyPrinter(indent=3 ,depth=6,width=100)
import pickle
def add_compsdata():
comps = { "comps" :{
"Faculty" : {
"Dr.<NAME> is the Head of Department"
"The Computer Department has a total of 30 faculty members consisting of highly skilled profess... | |
from .Address import Address
from .Authorization import Authorization
from .Avatar import Avatar
from .BankAccount import BankAccount
from .Contract import Contract
from .DigitalAssetAddress import DigitalAssetAddress
from .EmailAddress import EmailAddress
from .Error import Error
from .JoinOrganizationInvitation impor... | |
self.assertRaises(ValueError):
bond.l_monomer = 'a'
with self.assertRaises(ValueError):
bond.l_monomer = -2
bond.r_monomer = 2
with self.assertRaises(ValueError):
bond.r_monomer = 'a'
with self.assertRaises(ValueError):
bond.r_monomer = -2
def test_is_equal(self):
bond_1 = core.OntoBond()
bond_2 = core.Ont... | |
95*m.x3*m.x17 + 100*m.x4*m.x14 + 100*m.x5*m.x14
+ 85*m.x6*m.x11 + 100*m.x7*m.x14 + 80*m.x8*m.x14 + 60*m.x9*m.x17 + 70*m.x10*m.x17) - 100*m.x20
- 100*m.x23 - 100*m.x26 - 100*m.x29 == 0)
m.c41 = Constraint(expr=m.x40*m.x32 - (7.5*m.x5*m.x14 + 3.2*m.x6*m.x11 + 10*m.x7*m.x14 + 35*m.x8*m.x14 + 65*m.x9*m.x17
+ 60*m.x10*m... | |
decreasing=None,
dx=None,
dy=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
increasing=None,
insidetextanchor=None,
insidetextfont=None,
legendgroup=None,
measure=None,
measuresrc=None,
meta... | |
= [abs_root]
rel_path = self.__ParseMacros(rel_path)
if not rel_path or rel_path[0] != '/':
path_parts.append(self.__ParseMacros(self.RELEASE_MOD_FOLDER))
path_parts.append(rel_path)
abs_path = os.path.normpath(os.sep.join(path_parts))
if '=>NULL' in abs_path and not allow_unresolved:
print 'ERROR: Cannot const... | |
import importlib
import string
import re
from .vocab import english
from .grammar import Command, GrammarObject
from .verb import (
ScoreVerb,
FullScoreVerb,
HelpVerbVerb,
GetVerb,
StandUpVerb,
DropVerb,
RemoveFromVerb,
)
from .thing_base import Thing
from .things import Container, Surface, UnderSpace, Liquid
f... | |
# coding: utf-8
"""
Copyright (c) 2021 Aspose.BarCode for Cloud
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... | |
ppstm):
"""
Clone(self: IStream) -> IStream
Creates a new stream object with its own seek pointer that references the same
bytes as the original stream.
"""
pass
def Commit(self, grfCommitFlags):
"""
Commit(self: IStream, grfCommitFlags: int)
Ensures that any changes made to a stream objec... | |
import torch
from torch import nn
from torch import optim
from model.model_preprocessing import Preprocess
from model.model_encoder import pulsar_encoder
from model.model_tcn_multi import TemporalConvNet_multi
from model.model_output import OutputLayer
from model.model_multiclass import MultiClass
try:
from model.mode... | |
#########################
# GLOBAL VARIABLES USED #
#########################
ai_name = 'F.R.I.D.Y.'.lower()
EXIT_COMMANDS = ['bye','exit','quit','shut down', 'shutdown']
rec_email, rec_phoneno = "", ""
WAEMEntry = None
avatarChoosen = 0
choosedAvtrImage = None
botChatTextBg = "#007cc7"
botChatText = "w... | |
#!/usr/bin/python2.7
# Compresses the core Blockly files into a single JavaScript file.
#
# Copyright 2012 Google Inc.
# https://developers.google.com/blockly/
#
# 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 o... | |
<gh_stars>10-100
# coding=utf8
# Copyright 2016 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
#
#... | |
def private_endpoint_ip_address(self) -> str:
"""
The private IP address of the created private endpoint.
"""
return pulumi.get(self, "private_endpoint_ip_address")
@property
@pulumi.getter
def state(self) -> str:
"""
The current state of the bastion.
"""
return pulumi.get(self, "state")
@property
@pulum... | |
= Constraint(expr=m.x273*m.x684 - m.x384*m.x590 == 0)
m.c1302 = Constraint(expr=m.x273*m.x685 - m.x385*m.x590 == 0)
m.c1303 = Constraint(expr=m.x274*m.x690 - m.x386*m.x592 == 0)
m.c1304 = Constraint(expr=m.x274*m.x691 - m.x387*m.x592 == 0)
m.c1305 = Constraint(expr=m.x274*m.x692 - m.x388*m.x592 == 0)
m.c1306 = Con... | |
# MINLP written by GAMS Convert at 04/21/18 13:54:20
#
# Equation counts
# Total E G L N X C B
# 6101 101 0 6000 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 6031 6001 30 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 21031 12031 9000 ... | |
for p in proto.params:
base_type = p.ty.replace('const ', '').strip('*')
if 'count' in p.name.lower():
param_count = p.name
if base_type in vulkan.core.objects:
# This is an object to potentially check for validity. First see if it's an array
if '*' in p.ty and 'const' in p.ty and param_count != 'NONE':
loop_par... | |
"""
Establishes a PyModbus server/slave context that maps to ClearBlade platform collections.
Requires a unique instance per slave device represented in the platform.
"""
from clearblade.ClearBladeCore import Query
from pymodbus.interfaces import IModbusSlaveContext
from pymodbus.datastore.context import ModbusServerC... | |
<reponame>ayushmankumar7/cc-licenses
"""
Every license can be identified by a URL, e.g. "http://creativecommons.org/licenses/by-nc-sa/4.0/"
or "http://creativecommons.org/licenses/by-nc-nd/2.0/tw/". In the RDF, this is the rdf:about
attribute on the cc:License element.
If a license has a child dc:source element, then ... | |
<filename>scripts/qos/test_qos.py
from tcutils.wrappers import preposttest_wrapper
from compute_node_test import ComputeNodeFixture
import test
from common.qos.base import *
from svc_instance_fixture import SvcInstanceFixture
from svc_template_fixture import SvcTemplateFixture
from policy_test import PolicyFixture
fr... | |
<reponame>ml4ai/tomcat-planrec
# actions
def go_to_school(state):
state["went-to-school"] = 1
return state
def go_to_work(state):
state["went-to-work"] = 1
return state
def do_chores(state):
state["did-chores"] = 1
return state
def do_homework(state):
state["did-homework"] = 1
state["have-homework"] = 0
... | |
<filename>defects4cpp/processor/test.py
"""
Test command.
Run tests of the project inside a container.
"""
import argparse
import shutil
from dataclasses import dataclass
from os import getcwd
from pathlib import Path
from textwrap import dedent
from typing import Callable, Generator, List, Optional, Set, Union, cast
... | |
<reponame>agoragames/python-valve
# -*- coding: utf-8 -*-
# Copyright (C) 2013 <NAME>
from __future__ import (absolute_import,
unicode_literals, print_function, division)
import collections
import struct
import six
from . import util
NO_SPLIT = -1
SPLIT = -2
class BrokenMessageError(Exception):
pass
class B... | |
<reponame>fluiddyn/fluiddyn<gh_stars>10-100
"""Fast Fourier transforms (:mod:`fluiddyn.calcul.easypyfft`)
=============================================================
.. autofunction:: fftw_grid_size
Provides classes for performing fft in 1, 2, and 3 dimensions:
.. autoclass:: FFTP2D
:members:
.. autoclass:: FFTW... | |
<filename>skyrimse/views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from skyrimse.models import *
from skyrimse.forms import *
from mongoengine.context_managers import switch_db
from mongoengine.base.datastructures import EmbeddedDocumentList
from datetime import datetime
from... | |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Fri April 3 13:12:06 2020
@author: Omer
"""
"""
User Guide
1- Create a directory named as "data_augmentation" in and put this dataaugmentation.py file in it.
2- Collect the images for your dataset and carete a subdirector inside parent such as "images_to_augment... | |
<gh_stars>0
'''
Created on Mar 10, 2016
@author: <NAME>
'''
# Imports
import sys
import multiprocessing
import math
# Constants
MAX_X = 500
MAX_Y = 500
STEPS_MAX = 200
UNCHANGED_MAX = 10
NSTEPS_INDEX = 0
VEGIES_INDEX = 1
###########################
# Method called by each worker process to run... | |
opposed
# to a programmer who can call the function with or without a 'password'.
# Hence, we treat an empty password here, as if no 'password' was passed.
password = get_password('Enter a password for an encrypted RSA'
' file \'' + Fore.RED + filepath + Fore.RESET + '\': ',
confirm=False) or None
if password is... | |
start paginating. This is the ``NextToken`` from a previous response.
:rtype: dict
:returns:
"""
pass
class GetTables(Paginator):
def paginate(self, DatabaseName: str, CatalogId: str = None, Expression: str = None, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through respo... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .utils import *
from .affine_net import *
from .momentum_net import *
import mermaid.module_parameters as pars
import mermaid.model_factory as py_mf
import mermaid.utils as py_utils
from functools import p... | |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
import math
from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError
class MrpProduction(models.Model):
""" Man... | |
dataset's fact table
i += 1
outfile.write(f"*TOTAL*,{self.totalCOR},{self.totalINC},{self.totalPAR},{self.totalSPU},{self.totalMIS},{self.totalIGN}")
self._possible = self.totalCOR + self.totalINC + self.totalPAR + self.totalMIS
self._actual = self.totalCOR + self.totalINC + self.totalPAR + self.totalSPU
self._wro... | |
self._minval, self._maxval
for idx in range(len(created_vars), size):
assert idx == len(created_vars)
smtval = z3.Int(self._varname + "@" + str(idx))
space.add(smtval >= minval)
space.add(smtval <= maxval)
created_vars.append(SymbolicInt(smtval))
def __len__(self):
return self._len
def __bool__(self) -> bool... | |
import argparse
import time
import torch
from Models import get_model
from Process import *
from Utils import *
import torch.nn.functional as F
from Optim import CosineWithRestarts
from Batch import create_masks
from Beam import beam_search
from torch.autograd import Variable
import dill as pickle
from torch.utils.tens... | |
<reponame>bvbohnen/X4_Customizer
from time import time
from itertools import chain
from collections import OrderedDict
from Framework import Settings
from PyQt5 import QtWidgets
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from ..Shared.Misc import Set_Icon, Set_Foreground_Color
#-Removed; all file syst... | |
<reponame>kirillyat/klever
#
# Copyright (c) 2021 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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 ... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
: Project - Comparision experiments
: standalone segmentation using torch in-built models - fcn, deeplabv3, lr-aspp
: Author - <NAME>
: Institute - University of Kansas
: Date - 5/13/2021 last updated 5/15/2021
: Model Reference:
https://pytorch.org/vision/stable/mode... | |
<filename>src/functions.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
from scipy import stats
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
import textdistance
from collections import Counter
import os
import pandas as pd
import numpy as n... | |
<reponame>raspberrypieman/brython
"""
Python implementation of the io module.
"""
import os
import abc
import codecs
import errno
# Import _thread instead of threading to reduce startup cost
try:
from _thread import allocate_lock as Lock
except ImportError:
from _dummy_thread import allocate_lock as Lock
# Brython-... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Flow direction data
# The `FlwdirRaster` object is at the core of the pyflwdir package.
# It contains gridded flow direction data, parsed to an actionable common format
# which describes the linear index of the next dowsntream cell.
# Currently `pyflwdir` supports two ... | |
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def custom_action_response_descriptor_octopus... | |
mapping.
:vartype status: str
"""
_validation = {
'id': {'required': True},
'status': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'ResourceIdentity'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
... | |
"""Models for tables not included in UCR, generated for our system
`models.py` is meant to simply reflect the tables as they exist in UCR
itself; `cdemodels.py` extends those model classes. *These* models, on
the other hand, must actually be generated in our system.
"""
from copy import deepcopy
import logging
from ps... | |
"""
********************************************************************************
* Name: map_manager
* Author: nswain
* Created On: August 30, 2018
* Copyright: (c) Aquaveo 2018
********************************************************************************
"""
import copy
import json
from abc import ABCMeta, abst... | |
self._subscription_other_error_delay = ClientGUITime.TimeDeltaButton( misc, min = delay_min, days = True, hours = True, minutes = True, seconds = True )
self._downloader_network_error_delay = ClientGUITime.TimeDeltaButton( misc, min = delay_min, days = True, hours = True, minutes = True, seconds = True )
#
galle... | |
'Ødot;': '\uebcd',
'&oogondotbl;': '\ue608', '&Oogondotbl;': '\ue208', 'ö': 'ö',
'Ö': 'Ö', '&odiaguml;': '\ue8d7', 'öacute;': '\ue62c',
'ó': 'ó', 'Ó': 'Ó', 'øacute;': 'ǿ',
'Øacute;': 'Ǿ', 'ødblac;': '\uebc7',
'Ødblac;': '\uebc6', '&oogonacute;': '\ue60c',
... | |
differences : sparse array
A NxN dimensional sparse array representing a weighted adjancency matrix, with the edge weights corresponding to the backward hierarchical differences.
The column index represents the source node of the edge and the row index represents the destination node of the edge.
mean hierarchic... | |
**range:** 0..4294967295
.. attribute:: unit
Config unit
**type**\: :py:class:`QosUnit <ydk.models.cisco_ios_xr.Cisco_IOS_XR_skp_qos_oper.QosUnit>`
"""
_prefix = 'skp-qos-oper'
_revision = '2016-02-18'
def __init__(self):
super(PlatformQos.Nodes.Node.BundleInterfaces.BundleInterface.MemberInterf... | |
<reponame>PrincetonCompMemLab/narrative
from csv import reader
from copy import deepcopy
import os
import numpy as np
import re
#import sys # not used
import json
import cStringIO
# constants
# attach end_of_state, end_of_story marker
# MARK_END_STATE = False
# attach question marker at the end of the st... | |
from __future__ import absolute_import
import base64
import json
import logging
import re
import subprocess
import sys
from datetime import datetime
import pytz
import zmq
import zmq.auth
from zmq.auth.thread import ThreadAuthenticator
import time
from bemoss_lib.platform.BEMOSSAgent import BEMOSSAgent
from bemoss_li... | |
por mes por los siguientes gastos.",
"zh-s": "### 现在,请估算您每个月的以下花费是多少。",
"zh-t": "### 現在,請估算您每個月的以下開支。"
},
"you_take_home_pre": {
"en": "You said you take home",
"es": "Usted dijo que gana ",
"zh-s": "您说您每个月带回家${ format_money(income) }。如果您没有此项花费",
"zh-t": "您說每個月帶回家"
},
"you_take_home_post": {
"en": " each m... | |
<reponame>oldarmyc/cap
# Copyright 2016 <NAME>
#
# 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 t... | |
or node. Conflicts with `availability_zone`. Changing this creates a
new server.
"""
return pulumi.get(self, "availability_zone_hints")
@availability_zone_hints.setter
def availability_zone_hints(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "availability_zone_hints", value)
@property
@pulumi.ge... | |
ExperimentBranchBuilder(conflicts, {'manual_resolution': True})
assert len(conflicts.get()) == 2
assert len(conflicts.get_resolved()) == 1
branch_builder.set_algo()
assert len(conflicts.get()) == 2
assert len(conflicts.get_resolved()) == 2
conflict = conflicts.get_resolved()[0]
assert conflict.is_resolved
... | |
# -*- coding: utf-8 -*-
import urllib
import ConfigParser
import io
import StringIO
import gevent
import json
import pytz
import random
import zipfile
import re
from configobj import ConfigObj
from datetime import datetime, timedelta
from jsonfield import JSONField
from django.db import models, transaction
from dja... | |
request = self.get_request(post_data={'no': 'data'})
self.assertFalse(LogEntry.objects.count())
response = self.admin_class.publish_page(request, page.pk, "en")
self.assertEqual(response.status_code, 302)
self.assertEqual(1, LogEntry.objects.count())
self.assertEqual(page.pk, int(LogEntry.objects.all()[0].object_i... | |
= 'G'
return module
def prepare_psf(self):
"""Get metadata relevant to the instrument/detector as well as the
pixel scale from either the mosaic file, the PSF file, or both.
Read in or create the PSF that is representative of the mosaic
data.
"""
# Get the PSF associated with the mosaic
if self.psf_file is No... | |
<reponame>tryone144/dotfiles
#!/usr/bin/env python3
# -*- coding: utf8 -*-
#
# I3WM
# powerline-styled wrapper for i3status/j4status
# needs: [i3]
# [powerline-fonts]
# [ionicon-fonts]
#
# file: ~/.config/i3/panel/arrowbar_renderer.py
# v0.5.1 / 2015.11.12
#
import re
import sys
POSITION_LEFT = 0
POSITION_RIGHT = 1
... | |
Ensure that no other process is performing this procedure simultaneously. Thus, an inactive item selected will not become active unless it is done by this thread itself.
get = [item[1] for item in sorted([ (item["priority"],item) for item in self._queue if item["active"]==False and args["nick"] in item["nick"] ])] # ... | |
key=lambda s: s[1]):
if not isinstance(name, tuple):
# one of our special columns, ignore:
continue
visible = columns_visible[column_index]
visible_item = QtGui.QStandardItem()
visible_item.setCheckable(True)
if visible:
visible_item.setCheckState(QtCore.Qt.Checked)
visible_item.setData(QtCore.Qt.Checked, self... | |
counts by position.
def one_row(r):
digits = [x for x in r.Protein_Change if x.isdigit()]
if not digits:
return np.nan
return int(''.join(digits))
df4['Protein_Position'] = df4.apply(one_row, axis=1)
df4 = df4.dropna(subset=['Protein_Position'])
df4 = df4.sort_values(['Protein_Position'])
if ax is None:
fig,... | |
<filename>pret/redtools/gbz80disasm.py
from __future__ import print_function
from __future__ import absolute_import
#author: <NAME> <<EMAIL>>
#date: 2012-01-09
from . import extract_maps
import os
import json
from copy import copy, deepcopy
from .pretty_map_headers import random_hash, map_name_cleaner
from ctypes impor... | |
# Starts from OS Mastermap base map and:
# 1. Assigns CEH Landcover map (LCM) definition of either Arable or Improved grassland to agricultural land polygons
# 2. Assigns Rural Payments Agency CROME Crop map data (input must be dissolved by land use code and joined to description
# and simplified description (Arable, I... | |
# Copyright 2017 Netflix, 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 writing, so... | |
~azure.cognitiveservices.vision.face.models.Coordinate
:param nose_left_alar_out_tip:
:type nose_left_alar_out_tip:
~azure.cognitiveservices.vision.face.models.Coordinate
:param nose_right_alar_out_tip:
:type nose_right_alar_out_tip:
~azure.cognitiveservices.vision.face.models.Coordinate
:param upper_lip_top:
:... | |
# Copyright 2021 Accenture Global Solutions 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 agr... | |
<filename>m700.py
# coding: utf-8
'''
三菱電機CNC M700シリーズとEZSocketを使って通信する。
通信対象はマシニングセンタ系三菱CNC M700/M700V/M70/M70V。
'''
from enum import Enum
import threading
import pythoncom
import win32com.client
from win32com.client import VARIANT
class M700():
#同一スレッド内で同一ホストの接続は同じインスタンスを使う
#同一スレッドなのは、COMオブジェクトを別スレッドで共有するのが複雑な... | |
= self.screen.width - len(minion.name) - 18
self.screen.write_body(row, 3 + len(minion.name) + 1, "." * dots_len,
CursesScreen.COLOR_MINION, False, selected, True)
timer_str = "({})".format(self.ftime(
(minion.end_time if minion.finished() else now) - minion.begin_time))
if not minion.finished():
color = CursesS... | |
test = {
'name': 'Problem 10',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> p0 = [2, 2, 3]
>>> p1 = [6, 1, 2]
>>> fastest_words(match(['What', 'great', 'luck'], [p0, p1]))
[['What'], ['great', 'luck']]
>>> p0 = [2, 2, 3]
>>> p1 = [6, 1, 3]
>>> fastest_words(match(['What', 'great', 'luck'], [p0... | |
<gh_stars>10-100
import discord
import brawlstats
import box
import re
from discord.ext import commands
class BS(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.client = brawlstats.Client(
token=bot.config.bsapi,
session=bot.session,
is_async=True
)
def check_tag(self, tag):
return [char for cha... | |
import os, sys, re
import pickle
import pandas as pd
import hashlib
class Drug(object):
"""
Class defining a Drug object
"""
def __init__(self, drug_name):
"""
@param: drug_name
@pdef: Name of the drug
@ptype: {String}
@raises: {IncorrectTypeID} if the method translate_network is used with
a network of ty... | |
<gh_stars>0
import os, math
import time
import numpy as np
import pandas as pd
import geopy.distance
from concurrent.futures import ProcessPoolExecutor
'''
Input: "xxx.csv" with first column as "Date"
Output: the saved files for preprocessed datasets, i.e., "train/val/test_dataTime.npz" including:
- x
- dateTime
... | |
),
$result = UNIONALL($optional__0, $optional__1)
"""
expected_gremlin = """
g.V('@class', 'Animal')
.filter{it, m -> it.name.contains($wanted)}
.as('Animal___1')
.ifThenElse{it.in_Animal_ParentOf == null}{null}{it.in('Animal_ParentOf')}
.as('Animal__in_Animal_ParentOf___1')
.ifThenElse{it == null}{null}{it.in... | |
service['ts_use'], reverse=True)
return sorted(temp, key=lambda service: service['in_use'])
# end
# master election
def service_list_fixed(self, pubs):
self._debug['policy_fi'] += 1
return sorted(pubs, key=lambda service: service['sequence'])
# end
def service_list(self, service_type, pubs):
policy = self.ge... | |
if (branch_path[i][1] == "transloss" and
branch_path[i][0] == branch_path[i+1][0])]
for i in remove:
del branch_path[i]
brecon[node] = branch_path
# remove unused nodes from brecon
for node in brecon.keys():
if node.name not in tree:
del brecon[node]
return doomed
def add_implied_spec_nodes_brecon(tree, b... | |
import cv2, time, numpy as np
# test pictures
pic1 = 'test_images/i_robot_1.jpg' # robot body image
pic2 = 'test_images/i_robot_2.jpg' # robot full body image
pic3 = 'test_images/i_robot_3.jpg' # robot face image
pic4 = 'test_images/human_face.jpg' # human face
pic5 = 'test_images/human_upper_body.jpg' # human upper b... | |
0.3',
'boa/0.92o': 'boa 0.92o',
'boa/0.93.15': 'boa 0.93.15',
'boa/0.94.14rc21': 'boa 0.94.14rc21',
'cl-http/70.216 (lispworks': 'cl-http 70.216',
'caudium/1.4.9 stable': 'caudium 1.4.9',
'cherokee': 'cherokee 0.6.0',
'cherokee/0.99': 'cherokee 0.99',
'virata-emweb/r6_0_1': 'cisco vpn 3000 concentrator virata e... | |
<reponame>HIPS/firefly-monte-carlo<gh_stars>10-100
import numpy as np
import numpy.random as npr
from abc import ABCMeta
from abc import abstractmethod
EPS = 1e-6 # Gap between bound and likelihood to tolerate floating point error
def log_logistic(x):
# Overflow-avoiding version of the log logistic function.
abs_x ... | |
<filename>tests/test_logic.py
import unittest
import random
import math
from unittest.case import expectedFailure
import model
import numpy as np
from unittest.mock import Mock
from model import logic
ATTR_COUNT = 7 # Number of attributes associated with a Particle
# For reference:
# [0] = x-coord
# [1] = diameter... | |
<reponame>logstar/scedar
import numpy as np
import scipy.sparse as spsp
import seaborn as sns
import scedar.eda as eda
import matplotlib as mpl
mpl.use("agg", warn=False) # noqa
import matplotlib.pyplot as plt
import pytest
class TestSparseSampleFeatureMatrix(object):
"""docstring for TestSparseSampleFeatureMatrix... | |
<reponame>lpsinger/pytest-doctestplus
import glob
import os
from packaging.version import Version
from textwrap import dedent
import sys
import pytest
import doctest
from pytest_doctestplus.output_checker import OutputChecker, FLOAT_CMP
pytest_plugins = ['pytester']
def test_ignored_whitespace(testdir):
testdir.... | |
don't
# check or write lockfiles. Also returns a single string, no list.
try:
with open(filename, mode=mode) as File:
contents = File.readlines()
return [x.rstrip() for x in contents]
except (IOError, OSError):
return []
def write_list_file(filename, line, mode="w"):
# A "null append" is meaningful, as we can... | |
#!/usr/bin/env python
#
# autotextctrl.py - The AutoTextCtrl class.
#
# Author: <NAME> <<EMAIL>>
#
"""This module provides the :class:`AutoTextCtrl` class, an alternative to the
``wx.TextCtrl``, which has auto-completion capability.
I wrote this class because ``wx.TextCtrl`` auto-completion does not work under
OSX, an... | |
<reponame>martinjm97/typed-argument-parser<filename>tap/tap.py
from argparse import ArgumentParser
from collections import OrderedDict
from copy import deepcopy
import json
from pprint import pformat
import sys
import time
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Union
from tap.utils impo... | |
#!/user/bin/env python3
# Note that all the tests in this module require dataset (either network access or cached)
import os
import torch
import torchtext
import json
import hashlib
from torchtext.legacy import data
from parameterized import parameterized
from ..common.torchtext_test_case import TorchtextTestCase
from ... | |
!= "S" and word[2] != "s" :
print("\nWrong!\n")
numberOfErrors = numberOfErrors + 1
wrongChars = wrongChars + "s" + ", "
if guessChar == "T" or guessChar == "t" :
if word[1] == "T" or word[1] == "t" :
toGuess = toGuess[:1] + "t" + toGuess[2:]
if word[2] == "T" or word[2] == "t" :
toGuess = t... | |
# -*- coding: utf-8 -*-
"""
Mapping among MWE, lemma form and sense candidates
"""
# This code is a part of coolisf library: https://github.com/letuananh/intsem.fx
# :copyright: (c) 2014 <NAME> <<EMAIL>>
# :license: MIT, see LICENSE for more details.
MWE_ERG_PRED_LEMMA = {
'_flesh_v_out_rel' : 'flesh out'
,'_flip_v_... | |
<filename>pommerman/agents/gameNodes/game_node.py
import numpy as np
import random
import copy
from collections import defaultdict
import time
from pommerman import utility, constants, characters, forward_model, agents
from pommerman.agents import helper_func
#from agent_classes import Agent
class State():
def a... | |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and contributors.
#
# 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
#
# ... | |
""" Handle MDIO interface via bitbang and SPI bus. """
from typing import List, Optional
from pyrpio.gpio import CdevGPIO
from pyrpio.spi import SPI
class MDIO:
""" Bit-bang MDIO interface. """
C22_FRAME = 0x01
C45_FRAME = 0x00
OP_C22_WR = 0x01
OP_C22_RD = 0x02
OP_C45_AD = 0x00
OP_C45_WR = 0x01
OP_C45_RD_INC =... | |
#!/usr/bin/env python3
# Convert a BMP source file to Python source.
# Copyright <NAME> and <NAME> 2016
# Released under the MIT licence
# Files created by any graphic tool exporting bmp files, e.g. gimp
# the colour depth may be 1, 4, 8, 16, or 24 pixels, lower sizes preferred
# Usage:
# ./bmp_to_icon checkbox_on.b... | |
to edit" )
return trans.show_error_message( "You must provide a history dataset id to edit" )
if data is None:
trans.log_event( "Problem retrieving dataset (encoded: %s, decoded: %s) with history id %s." % ( str( dataset_id ), str( id ), str( hid ) ) )
return trans.show_error_message( "History dataset id is invalid... | |
<gh_stars>10-100
import logging
from enum import Enum, unique
from lib import constant_pool
from lib import run_time_data
from lib import descriptor
from lib import frame as FRAME
from lib.hijack_jre_methods import get_native_method
from lib import class_loader
OPCODES = {}
def bytecode(code):
def bytecode_decorato... | |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
The Python parts of the Jedi library for VIM. It is mostly about communicating
with VIM.
"""
import traceback # for exception output
import re
import os
import sys
from shlex import split as shsplit
from contextlib import contextmanager
try:
from itertools import zip_longest
ex... | |
"""visualization.py: Functions for visualizing MAVE-NN models."""
# Standard imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re
import pdb
# Special plotting-related imports
#from matplotlib.colors import DivergingNorm, Normalize
from matplotlib.colors import TwoSlopeNorm, Normali... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.