input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
family_directory
assert family_directory("some_directory/Foo.ttf") == "some_directory"
assert family_directory("some_directory/subdir/Foo.ttf") == "some_directory/subdir"
assert family_directory("Foo.ttf") == "." # This is meant to ensure license files
# are correctly detected on the current
# working directory.
... | |
<gh_stars>1-10
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# License: BSD
from collections import Sequence
import warnings
import numbers
import numpy as np
import scipy.sparse as sp
from .utils import check_arrays, array2d, atleast2d_or_csr, safe_asarray
from .utils import w... | |
<reponame>skywolf829/MRSR<gh_stars>0
from __future__ import absolute_import, division, print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
import numpy as np
import tim... | |
import numpy as np
import sys
import monai
import ponai
# sys.path.append('/nfs/home/pedro/portio')
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader, Dataset
from PIL import Image
import pandas as pd
import os
import argparse
import torchvision
import torch
import torch.nn as... | |
# coding: utf-8
"""
zweig
~~~~~
:copyright: 2014 by <NAME>
:license: BSD, see LICENSE.rst for details
"""
from __future__ import unicode_literals
import os
import sys
import ast
from io import StringIO
from contextlib import contextmanager
from itertools import chain
from functools import reduce
__version__ = '0... | |
<reponame>centerorbit/cockroach<filename>scripts/release-notes.py
#! /usr/bin/env python3
#
# Show a compact release note summary of a range of Git commits.
#
# Example use: release-notes.py --help
#
# Note: the first commit in the range is excluded!
#
# Requires:
# - GitPython https://pypi.python.org/pypi/GitPython/
#... | |
test_damping_torques = test_rod.damping_torques
# Compare damping forces and torques computed using in class functions and above
assert_allclose(test_damping_forces, damping_forces, atol=Tolerance.atol())
assert_allclose(test_damping_torques, damping_torques, atol=Tolerance.atol())
# alpha is base angle of isoscel... | |
# -*- coding: utf-8 -*-
DESC = "cme-2019-10-29"
INFO = {
"DescribeTasks": {
"params": [
{
"name": "Platform",
"desc": "平台名称,指定访问的平台。"
},
{
"name": "ProjectId",
"desc": "项目 Id。"
},
{
"name": "TaskTypeSet",
"desc": "任务类型集合,取值有:\n<li>VIDEO_EDIT_PROJECT_EXPORT:视频编辑项目导出。</li>"
},
{
"name": "StatusSet",
"des... | |
<filename>tests/test/mixed_vschema/vschema_pushdown.py
#!/usr/opt/bs-python-2.7/bin/python
import os
import sys
import datetime
import unittest
from multiprocessing import Process
from textwrap import dedent
sys.path.append(os.path.realpath(__file__ + '/../../../lib'))
import udf
from vschema_common import VSchemaT... | |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | |
isinstance(item, basestring):
raise Exception("Key is trying to index a h2o frame with a string? %s" % item)
elif isinstance(item, dict):
raise Exception("Key is trying to index a h2o frame with a dict? %s" % item)
elif isinstance( item, slice):
# debugprint("Key item start", str(item.start))
# debugprint("Key ... | |
import sys
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KDTree
from mpl_toolkits.mplot3d import Axes3D
from sklearn.mixture import GaussianMixture
class PrincipalCurve:
"""Subspace Constrained Mean Shift algorithm based on the paper
"Locally Defined Principal Curves an... | |
<filename>engine/modules.py
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from typing import List, Tuple, Dict
import numpy as np
from torch.autograd import Variable
class DepGCN(nn.Module):
"""
Label-aware Dependency Convolutional Neural Network Layer
"""
def __init__(self, dep_num... | |
'b16b6f8f',
'us liffré': '0bed5d02',
'us liffre': '0bed5d02',
'us lillebonne': 'e6f31b38',
'us lormont': '76174677',
'us lusitanos de saint-maur': '95d038b3',
'us lusitanos de saint maur': '95d038b3',
'us macouria': '6b66b09e',
'us marignane': 'c29fb6f0',
'us marseille endoume': '26d18deb',
'us matoury': '204... | |
<filename>kivy/core/text/__init__.py<gh_stars>1-10
'''
Text
====
An abstraction of text creation. Depending of the selected backend, the accuracy
of text rendering may vary.
.. versionchanged:: 1.5.0
:data:`LabelBase.line_height` added.
.. versionchanged:: 1.0.7
The :class:`LabelBase` does not generate any texture... | |
save_output, output_format):
"""
Type atomic/negativeInteger is restricted by facet minInclusive with
value -440277848538184635.
"""
assert_bindings(
schema="nistData/atomic/negativeInteger/Schema+Instance/NISTSchema-SV-IV-atomic-negativeInteger-minInclusive-2.xsd",
instance="nistData/atomic/negativeInteger/Sche... | |
<filename>openprocurement/audit/monitoring/tests/test_document.py
# -*- coding: utf-8 -*-
import unittest
from hashlib import sha512
from unittest import mock
from openprocurement.audit.monitoring.tests.base import BaseWebTest, DSWebTestMixin
from openprocurement.audit.monitoring.tests.test_elimination import Monitori... | |
import filecmp
import os
import sys
import shutil
import subprocess
import time
import unittest
if (sys.version_info > (3, 0)):
import urllib.request, urllib.parse, urllib.error
else:
import urllib
from optparse import OptionParser
from PyQt4 import QtCore,QtGui
parser = OptionParser()
parser.add_option("-r", "--ro... | |
sorted. Sorting `labels`.")
return sorted(self.labels)
def _is_sorted(self, iterable):
return all(iterable[i] <= iterable[i + 1] for i in range(len(iterable) - 1))
def fit_transform(self, y):
"""Fit label encoder and return encoded labels.
Parameters
----------
y : array-like of shape [n_samples]
Label valu... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Browser based Web App
Purpose: Battery Monitoring Demo
Version: 4/2018 Roboball (MattK.)
"""
import dash
from dash.dependencies import Input, Output, State, Event
import dash_core_components as dcc
import dash_html_components as html
import base64
from plotly import too... | |
-------------------------------------------------------------------------
def build_query(self,
id=None,
uid=None,
filter=None,
vars=None,
filter_component=None):
"""
Query builder
@param id: record ID or list of record IDs to include
@param uid: record UID or list of record UIDs to include
@param filter: f... | |
from __future__ import unicode_literals
import requests
import time
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
from decimal import Decimal
from .exceptions import (
PageError, DisambiguationError, RedirectError, HTTPTimeoutError,
WikipediaException, ODD_ERROR_MESSAGE)
from .util import c... | |
import time
import random
from copy import copy
try:
from neopixel import *
except ImportError:
print "non-neopixel"
BOARD_HEIGHT = 16
BOARD_WIDTH = 8
def unshared_copy(inList):
if isinstance(inList, list):
return list( map(unshared_copy, inList) )
return inList
# tetrisbuster code
pieces = {
'i':[ [ [True, ... | |
in range(self.num_loc_pods)
]
)
# Store for hooks
self._hooks = {}
def add_functions(
self,
num_new_functions: int,
freeze_existing_parameters: bool = False,
init_strategy: str = "random",
):
def hook(grad):
grad.data[:-num_new_functions] = 0.0
return grad
def extend_tensor(
x: torch.Tensor, num_channe... | |
such as required and readonly status,
required type, and so on.
This implementation uses a field list for this.
Subclasses may override or extend.
.. versionadded:: 4.6.0
"""
lines = []
lines.append(_DocStringHelpers.make_class_field('Implementation', type(self)))
lines.append(_DocStringHelpers.make_field("... | |
# East Asian ideograph
0x22434E: (0x6AFD, 0), # East Asian ideograph
0x2D3058: (0x4E9C, 0), # East Asian ideograph
0x29434F: (0x94DE, 0), # East Asian ideograph
0x6F562C: (0xC671, 0), # Korean hangul
0x224350: (0x6AFA, 0), # East Asian ideograph
0x347D24: (0x83C7, 0), # East Asian ideograph
0x6F552E: (0xC561, 0)... | |
<filename>code/twokenize.py
# -*- coding: utf-8 -*-
"""
Twokenize -- a tokenizer designed for Twitter text in English and some other European languages.
This tokenizer code has gone through a long history:
(1) <NAME> wrote original version in Python, http://github.com/brendano/tweetmotif
TweetMotif: Exploratory Searc... | |
"""Utility functions and base classes for implementing extension hooks."""
from __future__ import annotations
import types
from typing import Any, Callable, Dict, List
from torch.nn import Module, Parameter, Sequential
class ModuleHook:
"""Hook class to perform actions on parameters right after BackPACK's extensi... | |
"""
GDB pretty printer support for BDE components
This module provides a set of pretty printers to load into gdb for debugging
code using BDE (http://github.com/bloomberg/bde) components.
This is a work in progress, more printers will be added as needed.
Authors: <NAME> <<EMAIL>>
<NAME> <<EMAIL>>
<NAME> <<EMA... | |
<reponame>S-Manglik/gs-quant
# Copyright 2018 <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 ... | |
disconnected_outputs
def connection_pattern(self, node):
patterns = [[True, True, True], # x
[True, True, True], # scale
[True, True, True]] # bias
# Optional running_mean and running_var are only
# connected to their new values.
for i in range(3, len(node.inputs)):
patterns[0].append(True)
for pattern in pat... | |
<gh_stars>1-10
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | |
<gh_stars>0
from nose.tools import set_trace
from collections import defaultdict
import datetime
import base64
import os
import json
import logging
import re
from config import (
Configuration,
temp_config,
)
from util import LanguageCodes
from util.xmlparser import XMLParser
from util.http import (
HTTP,
Remote... | |
se_per = pd.Series(res).sort_index()
se_per.to_excel(workingDir + 'se_percentile_variation_%s.xlsx' % q)
se_per.plot()
plt.savefig(workingDir + 'se_percentile_variation_%s.png' % q, dpi=300)
plt.clf()
#os.remove(workingDir + 'combined_%s_aligned.h5' % M)
return
def analyzeCase(self, df_expr, toggleCalculateMa... | |
str(y + 1) + ";" + str(x) + "H" + string)
@staticmethod
def beep():
""" Emit a short attention sound.
"""
curses.write("\07")
@staticmethod
def curs_set(setting):
""" Set the cursor state. visibility can be set to 0, 1, for invisible, normal.
"""
if setting == 0:
curses.write("\33[?25l")
elif setting == 1... | |
# ============================================================================
#
# Copyright (c) 2007-2010 Integral Technology Solutions Pty Ltd,
# All Rights Reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL... | |
<reponame>joke-lee/s3-tests
import nose
import random
import string
from nose.plugins.attrib import attr
import uuid
from nose.tools import eq_ as eq
from . import (
get_client
)
region_name = ''
# recurssion function for generating arithmetical expression
def random_expr(depth):
# depth is the complexity of ex... | |
import os
import shutil
import time
import pandas as pd
from os import path as P
import sys
from cooka.dao.dao import DatasetDao, ModelDao
from cooka.dao import db
from cooka.dao.entity import DatasetEntity, MessageEntity
from cooka.common import util, consts
from cooka.common.exceptions import EntityNotExistsExcepti... | |
puts it into V[X]
self.V[0xF] = getLSB(self.V[b1]) # Getting the LSB thanks to our great function above
self.V[b2] = (self.V[b1] >> 1) # Dividing by 2 with binary values is the same as shifting 1 bit to the right. That is why we get the LSB beforehand, because we want to know what it was before we deleted ... | |
fontSize = self._viewFontSize)
if self.noteReversed:
text(chr(int('25B2', 16)), (xN + 8, Ycontrol + txtup))
else:
text(chr(int('25BC', 16)), (xN + 8, Ycontrol + txtup))
else:
fillRGB(colorBKG)
rect(xN, Ycontrol+1, wNote, self._lineSize)
fillRGB(COLOR_GREY_50)
font(self._viewFontName, fontSiz... | |
encapsulated" if I1iII11ii1 [ 2 ] == None else "" , IiiIIi1 , lisp_hex_string ( oOoO0O00o ) . zfill ( 4 ) ,
# iIii1I11I1II1 + i11iIiiIii / OoOoOO00
# I1ii11iIi11i % OoOoOO00 * OoOoOO00 % o0oOOo0O0Ooo * II111iiii / OoOoOO00
lisp_hex_string ( O00000OO00OO ) . zfill ( 4 ) ) )
if 73 - 73: OoOoOO00 + OOooOOo * II111iiii... | |
rows/columns for new rows/columns to add
if num_missing_rows > 0 or num_missing_cols > 0:
# Row and column offsets which indicate the difference in position of the row or column being
# added and the position of the value in the data. I.e., a row being added would have the value:
# value = get_data_point(draw_row[... | |
'8',
'range': '0 to 255',
'resolution': 'binary',
'type': 'binary bit-mapped',
},
343: {
'length': '1 character',
'name': 'coolant pump differential pressure',
'period': '1.0 s',
'pid': 343,
'priority': '6',
'range': '-416 kpa to 412.75 kpa',
'resolution': Fraction(13, 4),
'type': 'signed short integer',
... | |
name, returntype, args, varargs = self.parse_function_header()
return NativeFunction(name, returntype, args, varargs)
elif self.tokens[self.i] == VAR:
self.i += 1
name = self.identifier()
self.expect(COLON)
type = self.parse_type()
return NativeVariable(name, type)
else:
assert False
def parse_exception(self... | |
# -*- coding: utf-8 -*-
# Apache Software License 2.0
#
# Copyright (c) 2018, <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 ... | |
s = getattr(ii,field)
if s not in master_list:
master_list.append(s)
for child in node.next.values():
# FIXME: sloppy return value handling???
collect_ifield(options,child, field,master_list)
return master_list
def collect_ofield(options, node, field, master_list):
"""Collect operand field data for enumerat... | |
set_data_units(self, data_units): self.data_units = data_units
def get_valid_range(self): return self.valid_range
def set_valid_range(self, valid_range): self.valid_range = valid_range
def get_radiance(self): return self.radiance
def set_radiance(self, radiance): self.radiance = radiance
def get_reflectance(self):... | |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021-2022, <NAME>
# All rights reserved.
#
# Licensed under the BSD 3-Clause License:
# http://opensource.org/licenses/BSD-3-Clause
#
from __future__ import annotations
import asyncio
import collections
import datetime
import time
import textwrap
from typing import Callable... | |
<gh_stars>0
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargsp... | |
Retrieve validation information from the CMS object, using Adobe's
revocation info archival attribute.
"""
PADES_LT = 'pades'
"""
Retrieve validation information from the DSS, and require the signature's
embedded timestamp to still be valid.
"""
PADES_LTA = 'pades-lta'
"""
Retrieve validation information f... | |
'third',
'this',
'thorough',
'thoroughly',
'those',
'though',
'three',
'through',
'throughout',
'thru',
'thus',
'to',
'together',
'too',
'took',
'toward',
'towards',
'tried',
'tries',
'truly',
'try',
'trying',
'twice',
'two',
'u',
'un',
'under',
'unfortunately',
'unless',
'unlikely',
'unti... | |
<reponame>sjhloco/asa_acl_report
#!/usr/bin/env python
# This script is to go through ASA access list (read from the device or a file) and produce human readable xl file.
import csv
import os
import re
from datetime import datetime
from os.path import expanduser
from sys import exit
import ipaddress
from ipa... | |
def __ne__(self, other):
return not (self == other)
class KeyNotFoundException(TException):
"""
Attributes:
- msg
"""
thrift_spec = (
None, # 0
(1, TType.STRING, 'msg', None, None, ), # 1
)
def __init__(self, msg=None,):
self.msg = msg
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinar... | |
fmt = "%%%ss:" % width
fmteval = fmt[:-1]+"="
line = ( fmt % ('-'*(width-2)) ) + ( '-'*(min(40,width*5)) )
print(line)
for key,value in self.__dict__.items():
if key not in self._excludedattr:
if isinstance(value,(int,float,str,list,tuple,np.ndarray,np.generic)):
if isinstance(value,pstr):
print(fmt % key,'p"'+... | |
<reponame>bthornton191/Adams_Modules<filename>adamspy/adripy/string.py
"""A module that contains the :class:`DrillString` class
"""
import os
import copy
import re
import shutil
import thornpy
from . import TMPLT_ENV
from .tool import DrillTool
from .utilities import read_TO_file, get_cdb_location, get_cdb_path, get_fu... | |
"""
This is the main file for ParEx, a suite of parallel extrapolation solvers for
initial value problems. It includes explicit, implicit, and semi-implicit (linearly
implicit) solvers. The code is based largely on material from the
following two volumes:
- *Solving Ordinary Differential Equations I: Nonstiff Problem... | |
self.setWindowIcon(QIcon('..\\img\\icon_16px.ico'))
self.setFixedSize(self.size())
self.show()
# Set up trigger and queue to update dialog GUI during approach:
self.progress_trigger = Trigger()
self.progress_trigger.s.connect(self.update_progress)
self.finish_trigger = Trigger()
self.finish_trigger.s.connect(sel... | |
<reponame>anthonyhu/TrackR-CNN
# a lot of stuff is copied over from savitar1, but we still need to port more of it
import numpy as np
from scipy.special import expit as sigmoid
from collections import namedtuple
import munkres
from scipy.spatial.distance import cdist
import pycocotools.mask as cocomask
from cv2 import... | |
to MoMA",
"<NAME> - Meet the dazzling flying machines of the future",
"<NAME> - The business logic of sustainability",
"<NAME> - The quantified self",
"<NAME> - Visualizing ourselves ... with crowd-sourced data",
"<NAME> - The danger of hiding who you are",
"<NAME> - A robot that flies like a bird",
"<NAME> - Th... | |
range(len(cList)):
x, y, z = cList[num]
polyline.points[num].co = (x, y, z, weight)
return polyline
def execute(self, context):
#update selection
if bpy.context.object.type != "EMPTY":
if bpy.context.mode == 'OBJECT':
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.object.mode_s... | |
password_change_is_valid = True
userobject.change_password_is_valid = password_change_is_valid
userobject.password_attempted_change_date = datetime.datetime.now()
#only overwrite the password if the post was a valid password change
if password_change_is_valid:
userobject.password_salt = uuid.uuid4().hex
... | |
<reponame>josepablocam/common-code-extraction
# Function 0
def cleaning_func_0(data):
# core cleaning code
import pandas as pd
# data = pd.read_csv('../input/loan.csv', low_memory=False)
data.earliest_cr_line = pd.to_datetime(data.earliest_cr_line)
return data
#=============
# Function 1
def cleaning_func_1(data)... | |
<filename>plasticc/get_data.py
# -*- coding: UTF-8 -*-
"""
Get PLASTICC data from SQL database
"""
import sys
import os
import numpy as np
import warnings
import argparse
import pandas as pd
import astropy.table as at
import astropy.io.fits as afits
from collections import OrderedDict
import database
import helpers
RO... | |
open(pathstr + '/Diabetic_Retinopathy_transformed_numperclass_' + all_label_number_map_str\
+ choose_indices_str + '_seed_' + str(seed) + '.pkl','wb') as g:
pkl.dump((finaldata, finallabels), g)
def gen_kmeansplusplus_CelebAdataset(pathstr, inputfile, choose_indices = True,\
num_images_per_class=1000, num_classes... | |
# contains 1 or multiple text files
>>> dataset = ds.TextFileDataset(dataset_files=text_file_dataset_dir)
"""
@check_textfiledataset
def __init__(self, dataset_files, num_samples=None, num_parallel_workers=None, shuffle=Shuffle.GLOBAL,
num_shards=None, shard_id=None, cache=None):
super().__init__(num_parallel_wo... | |
c_dgcdist(rlat1,rlon1,rlat2,rlon2,2)
################################################################
def gc_interp(rlat1,rlon1,rlat2,rlon2,numi):
"""
Interpolates points along a great circle between two specified points
on the globe. The returned latitudes and longitudes are returned as
NumPy arrays in degrees in t... | |
start)
return prices, rets
def simulate_gbm_from_prices(n_years=10, n_scenarios=20, mu=0.07, sigma=0.15, periods_per_year=12, start=100.0):
'''
Evolution of an initial stock price using Geometric Brownian Model:
S_t = S_0 exp( (mu-sigma^2/2)*dt + sigma*sqrt(dt)*xi ),
where xi are normal random variable... | |
* I1Ii111 * I11i - I1ii11iIi11i + I1Ii111
if 50 - 50: OoooooooOO * II111iiii
if 7 - 7: ooOoO0o / I11i * iII111i
if 17 - 17: O0 % I1Ii111
if 28 - 28: i1IIi * ooOoO0o
lisp_remove_eid_from_map_notify_queue ( oOoOOo . eid_list )
if ( lisp_map_notify_queue . has_key ( ii1i1I1111ii ) ) :
oOoOOo = lisp_map_notify_queue... | |
import sys, string, math, types
from pandac.PandaModules import *
import direct.gui.DirectGuiGlobals as DGG
from direct.gui.DirectGui import *
from PieMenu import *
from ScrollMenu import *
dnaDirectory = Filename.expandFrom(base.config.GetString("dna-directory", "leveleditor"))
# Colors used by all color menus
DEF... | |
<gh_stars>1-10
#
# Copyright (c) 2017, 2019 Oracle and/or its affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown
# at http://oss.oracle.com/licenses/upl.
"""
This utility assists with configuring network interfaces on Oracle Cloud
Infrastructure instances. See the manual ... | |
import datetime
from datetime import date
from datetime import datetime, timedelta
import time
from time import strftime
# django settings for script
from django.conf import settings
# from djequis.core.utils import sendmail
from djzbar.utils.informix import do_sql
from djzbar.utils.informix import get_eng... | |
string.
'''
(retval, funcname, params) = get_func_params_from_prototype(prototype)
print(HDR1)
print("Now generating OpenOSC ASM-Label Redirect Mapping code for: " + funcname)
print(HDR1)
magic_str = '_CASE3'
va_args_code = generate_va_args_redefine_code(funcname, params, magic_str)
if not va_args_code:
return... | |
return False
'''
def importNecessaryHeaders(isKernel=False):
''' Import header file from publich xcode headers and kernel ida file's exported headers'''
phase = "importNecessaryHeaders"
#if checkPhaseDone(phase):
# return
print "[+] Import Necessary Headers"
#importHeaderFile(getFilePathWithRelPath("../Headers... | |
os.path.splitext(path)
if ext in ['.xml', '.cdml']:
if mode != 'r':
raise ModeNotSupported(mode)
datanode = load(path)
else:
# If the doesn't exist allow it to be created
# Ok mpi has issues with bellow we need to test this only with 1
# rank
if mode == "r" and not os.path.exists(path):
raise FileNotFoundErro... | |
#!/usr/bin/python
#
# Copyright 2017 Google Inc. 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 app... | |
if 27 - 27: OoOoOO00 * OoO0O00 * OOooOOo % I1IiiI * o0oOOo0O0Ooo + I1ii11iIi11i
ooOOOo0o0oo = I11IiI1ii . lookup_source_cache ( self . eid , True )
if ( ooOOOo0o0oo == None ) : return
if 73 - 73: i1IIi
if ( I11IiI1ii . source_cache == None ) : return
if 52 - 52: IiII / i11iIiiIii * O0
I11IiI1ii . source_cache . d... | |
<reponame>caser789/libcache<gh_stars>0
import pickle
import six
from .base import Base
from . import _to_native
from . import _DEFAULT_SOCKET_TIMEOUT
from . import _DEFAULT_TIMEOUT
from . import _TCP_KEEP_ALIVE_OPTIONS
class Redis(Base):
"""Uses the Redis key-value store as a cache backend
:param host: address o... | |
from __future__ import absolute_import
from builtins import zip
from builtins import map
from builtins import str
from builtins import range
from builtins import object
from nose.tools import (assert_equal, assert_not_equal, raises, assert_true,
assert_false)
from nose.plugins.skip import SkipTest
from .test_helpers i... | |
Class for pickups including fruit, extra health and extra life
class Fruit(GravityActor):
APPLE = 0
RASPBERRY = 1
LEMON = 2
EXTRA_HEALTH = 3
EXTRA_LIFE = 4
def __init__(self, pos, trapped_enemy_type=0):
super().__init__(pos)
# Choose which type of fruit we're going to be.
if trapped_enemy_type == Robot.TYPE_... | |
# labels = np.delete(labels, idx[:700]) # labels = labels[:2000]
# graphs = np.delete(graphs, idx[:700], axis=0) # graphs= graphs[:2000]
return graphs, labels
def load_dataset3s_large(ds_name, upper):
graph_dict = dict(zip([7, 8, 9], [1, 1, 1, 1, 1, 1, 1]))
num_rep = [20, 20, 20, 50, 50, 200, 200]
graphs = []
... | |
)
)
assert 0 < fNbytes <= fKeylen + fObjlen
assert fCycle > 0
if not is_directory_key:
assert fSeekKey == location, "fSeekKey {0} location {1}".format(
fSeekKey, location
)
fSeekKey = None
classname, position = String.deserialize(
raw_bytes[position - location :], position
)
name, position = String.deseri... | |
#!/usr/bin/python
"""Bitfinex Rest API V2 implementation"""
# pylint: disable=R0904
from __future__ import absolute_import
import json
from json.decoder import JSONDecodeError
import hmac
import hashlib
import requests
from bitfinex import utils
PROTOCOL = "https"
HOST = "api.bitfinex.com"
VERSION = "v2"
# HTTP req... | |
<reponame>julio-navarro-lara/thesis_scripts<filename>experiment_9/morwilog_v10/phase2_execution.py
#Copyright 2018 <NAME>
#Built at the University of Strasbourg (France). CSTB team @ ICube laboratory
#12/06/2018
import random
import math
from library import *
def roulette_choice(choices):
max = sum(choices.values()... | |
<reponame>MitchellTesla/datasets<gh_stars>1000+
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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 t... | |
<filename>softlearning/environments/gym/locobot/dual_nav_grasp_envs.py
import gym
from gym import spaces
import numpy as np
import os
from collections import OrderedDict, defaultdict
import tensorflow as tf
import tree
from .utils import dprint, is_in_rect, Timer
from .base_envs import RoomEnv
from .perturbations impo... | |
"""General purpose (hybrid) model class, and associated hybrid trajectory
and variable classes.
<NAME>, March 2005.
A Model object's hybrid trajectory can be treated as a curve, or as
a mapping. Call the model object with the trajectory name, time(s), and
set the 'asmap' argument to be True to use an integer time to... | |
is_valid(self, lines):
try:
g = smof_base._stream_entries(smof_base.read_fasta_str(lines))
out = [s for s in g]
return True
except BaseException:
return False
def test_good(self):
self.assertTrue(self.cmp_seqs(self.good, (self.seq1, self.seq2)))
def test_good_empty_lines(self):
self.assertTrue(self.cmp_seqs... | |
12130
},
{
"id_ref": 536,
"del_ref": "COYOACAN",
"cve_col": "03-141",
"nombre_ref": "PEDREGAL DE STO DOMINGO III",
"pob_2010": 10067
},
{
"id_ref": 537,
"del_ref": "COYOACAN",
"cve_col": "03-142",
"nombre_ref": "PEDREGAL DE STO DOMINGO IV",
"pob_2010": 10700
},
{
"id_ref": 538,
"del_ref": "COYOACAN",
... | |
"c) Ja, ik koop dit product af en toe (minder dan maandelijks)."
# "d) Ja, ik heb dit product ooit al gekocht."
# "e) Neen, ik heb dit product nog nooit gekocht."
# Door middel van het gebruik van de bijhorende toetsen (als je iets wekelijks koopt moet je de 'a' toets indrukken) kan je aanduiden welk statement het be... | |
"""
Devices controlled my the ISY are represented as "nodes" on the ISY device and with Node Objects in the API
There are three types of Node Object:
* IsyNode - Node Object
Represent lights, switches, motion sensors
* IsyScene - Scene Object
Represents Scenes contains Nodes that comprise a "Scene"
* IsyNodeFol... | |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 适用于 tensorflow >= 2.0, keras 被直接集成到 tensorflow 的内部
# ref: https://keras.io/about/
from tensorflow.keras.layers import Layer, Input, LSTM, TimeDistributed, Bidirectional, Dense, Lambda, Embedding, Dropout, \
Concatenate, RepeatVector
from tensorflow.keras.optimizers import ... | |
Turing state which issues the correct operation starting from the first PC bit."""
return State()
@memo
def nextstate(self):
"""A Turing state which increments PC by 1, with the tape head on the last PC bit."""
return self.dispatch_order(0, 1)
@memo
def nextstate_2(self):
"""A Turing state which increments PC... | |
sys.exit(-1)
def sel(self, opt, choice):
for i in range(len(opt)):
option = opt[i].find_element_by_class_name(
'ui-corner-all').get_attribute("innerHTML")
if option == choice:
btn = opt[i].find_element_by_class_name('ui-corner-all')
time.sleep(1)
btn.click()
time.sleep(1)
return
continue
def policy_delete... | |
<gh_stars>1-10
#!/usr/bin/sudo python
# El Toro LITE
#
# Coded by Jesse
# twitch.tv/oh_bother
#
# Lisences are for nerds. Er, I mean, do whatever with this. MIT or something.
# this "lite" version removes a lot of animations and similar cool stuff. :(
# also the client modified this code heavily. YMMV
#
# ElToro main ... | |
<gh_stars>10-100
#!/usr/local/bin/python
"""
Author: <NAME>
Contact: <EMAIL>
Testing:
import dash_client
mpd_file = <MPD_FILE>
dash_client.playback_duration(mpd_file, 'http://192.168.127.12:8005/')
From commandline:
python dash_client.py -m "http://192.168.127.12:8006/media/mpd/x4ukwHdACDw.mpd" -p "all"
python d... | |
if len(label_str) == 0:
return "", "en"
if "@" in label_str:
res = label_str.split("@")
text_string = "@".join(res[:-1]).replace('"', "").replace("'", "")
lang = res[-1].replace('"', '').replace("'", "")
else:
text_string = label_str.replace('"', "").replace("'", "")
lang = "en"
return text_string, lang
@sta... | |
Ax, unsigned int const [] Xx)
csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj,
long long [] Ax, long long const [] Xx)
csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj,
unsigned long long [] Ax, unsi... | |
<gh_stars>0
from __future__ import absolute_import, division, print_function
from fnmatch import fnmatch
from functools import wraps
from glob import glob
from math import ceil
from operator import getitem
import os
from threading import Lock
import uuid
from warnings import warn
import pandas as pd
import numpy as n... | |
<gh_stars>0
import os
import logging
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import Input
from tensorflow.keras.layers import Conv2D, MaxPooling2D, ReLU, BatchNormalization, Add
from tensorflow.keras.laye... | |
#!/usr/bin/env python
#
# mergetrees.py: routines that create merge scenarios
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.