text stringlengths 1 927k |
|---|
import cProfile
import gym
import numpy as np
from connect_four.evaluation.incremental_victor.graph.graph_manager import GraphManager
from connect_four.evaluation.incremental_victor.solution.victor_solution_manager import VictorSolutionManager
from connect_four.problem import ConnectFourGroupManager
env = gym.make(... |
from pymongo import MongoClient
import json
from pprint import pprint
client = MongoClient('localhost:27017')
db = client.admin
serverStatusResult = db.command("serverStatus")
pprint(serverStatusResult) |
import os
import pandas as pd
from chemreader.writers import GraphWriter
from chemreader.readers import Smiles
from rdkit.Chem import MolFromSmiles
from slgnn.models.gcn.utils import get_filtered_fingerprint
from tqdm import tqdm
def _is_active(value):
if value < 1000:
return 1
elif value >= 10000:
... |
# -*- coding: utf-8 -*-
import os
import glob
import shutil
import nose.tools
import blackbird.utils.configread
import blackbird.utils.error
class TestConfigReaderGetGlobalIncludeAbsPath(object):
def __init__(self):
infile = (
'[global]',
'user = nobody',
'group = n... |
from . import static
from . import fdem
from . import tdem |
#!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Various small unit tests
import io
import json
import xml.etree.ElementTree
from youtube_dlc.... |
#!/usr/bin/env python
"""Resort a BAM file karyotypically to match GATK's preferred file order.
Broad's GATK and associated resources prefer BAM files sorted as:
chr1, chr2... chr10, chr11... chrX
instead of the simple alphabetic sort:
chr1, chr10, chr2 ...
This takes a sorted BAM files with an alternative... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# BSD 3-Clause License
#
# Copyright (c) 2020-2021, Faster Speeding
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of sour... |
"""Constituency Parsing related modeling class"""
import re
from typing import List, Optional, Tuple
from lxml import etree
from pororo.tasks.utils.base import PororoFactoryBase, PororoTaskBase
from pororo.tasks.utils.download_utils import download_or_load
class PororoConstFactory(PororoFactoryBase):
"""
C... |
'''BOMusic'''
from tkinter import *
import pygame
class App3(Toplevel):
cor1 = '#171717'
cor2 = '#58009D'
cor3 = '#efefef'
def __init__(self, original):
self.frame_original = original
Toplevel.__init__(self)
self.config()
self.frames()
self.wid... |
TQL_HELP = """
Commands can optionally be multi-line.
Few common commands
-----------------------
show databases; -> list all available databases
use db; -> switches context to specified database
'db' this must be done if queries do
not use full name... |
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/main/LICENSE
"""
This module defines integer constants used by serialization and deserialization routines.
"""
from __future__ import absolute_import
import numpy
# used in unmarshaling
kByteCountMask = numpy.int64(0x40000000)
kByteCountVMask = ... |
#
# PySNMP MIB module CISCOSB-PHY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-PHY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
import ciso8601
import dateutil.parser
from cartographer.field_types import SchemaAttribute
from cartographer.utils.datetime import as_utc, make_naive
class DateAttribute(SchemaAttribute):
@classmethod
def format_value_for_json(cls, value):
return as_utc(value).isoformat()
def from_json(self, s... |
# Generated by Django 2.2.4 on 2019-09-02 07:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sushi', '0014_sushifetchattempt_processing_success'),
]
operations = [
migrations.AlterField(
model_name='sushifetchattempt',
... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='test@gmail.com', password='test1234'):
return get_user_model().objects.create_user(email, password)
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
... |
# 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
fro... |
import numpy
# Normalization functions
class NormalizationNo():
def normalize(self, img, settings=None):
if settings is None:
settings = {}
return img
class NormalizationMean(NormalizationNo):
def normalize(self, img, settings=None):
if settings is None:
setti... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
import copy
from phidl.device_layout import Device
from pp.cell import cell
from pp.component import Component, ComponentReference, Port
from pp.config import call_if_func
@cell
def import_phidl_component(component: Device, **kwargs) -> Component:
""" returns a gdsfactory Component from a phidl Device or functi... |
import sqlalchemy as sa
import ocdskingfisherviews.cli.commands.base
from ocdskingfisherviews.field_counts import FieldCounts
class FieldCountsCommand(ocdskingfisherviews.cli.commands.base.CLICommand):
command = 'field-counts'
def configure_subparser(self, subparser):
subparser.add_argument("viewnam... |
#!/usr/bin/env python3
import datetime
import pytz
import smtplib, ssl
import re
from email.utils import make_msgid
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.charset import Charset, QP
import os
import sys
sys.path.insert(0, os.path.... |
import sys
from flask import request, jsonify, abort
from flaskblog import app, db, bcrypt
from flaskblog.models import Token, Post, User
import datetime
# method used to create a token that can be used for some time defined by the delta
@app.route('/api/token/public', methods=['POST'])
def get_token():
data = reque... |
# -*- coding: utf-8 -*- #
# 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 requir... |
from contextlib import contextmanager
from testflows.core import *
from rbac.requirements import *
import rbac.tests.errors as errors
@TestFeature
@Name("create row policy")
@Args(format_description=False)
def feature(self, node="clickhouse1"):
"""Check create row policy query syntax.
```sql
CREATE [ROW... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from test_venta.sales.v0.urls import router as sales
from django.views.g... |
"""
Copyright 2016 Fabric S.P.A, Emmanuel Benazera, Alexandre Girard
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the ... |
import pytest
import numpy as np
import itertools
from sklearn.exceptions import ConvergenceWarning
from sklearn.utils import check_array
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import ignore_warnings
from sklearn... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
import os # noqa
import unittest
from typing import Callable
from unittest.mock import patch
from graphql.type import (
GraphQL... |
from flask import Blueprint, render_template, redirect, url_for, flash, jsonify
from sqlalchemy import exc
from application import db
from application.routes.leads.models import Lead
from application.routes.leads.forms import AddLeadForm
leads = Blueprint("leads", __name__)
@leads.route("/")
def index():
return ... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import os
import pathlib
import pandas as pd
import matplotlib.pyplot as plt
from src.models.walk_forward_predictor import WalkForwardPredictor
from src.models.mlp import MultiLayerPerceptron
from src.utils import series_to_supervised
# TODO: Add description! Mention datasources
# Get data path or create a directo... |
"""
This implements a set of classes that wraps a file object interface
around code that executes in another process. This allows you fork
many different commands and let the run concurrently.
Functions:
copen_sys Open a file-like pipe to a system command.
copen_fn Open a file-like pipe to a python function.... |
#!/usr/bin/env python
#
# Copyright 2019 The Vitess 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from .compiler import Compiler
import colorama
import ctypes
import glob
import os
import sys
colorama.init()
def write(t):
print("\033[22;37m"+t,end="")
def write_warn(w):
print("\033[2;33m"+w,end="")
def write_error(e):
print("\033[2;31m"+e,end="")
if ("--compile" in sys.argv):
sys.argv=sys.argv[1:]
D=(... |
import numpy as np
import torch
from torch import nn
from tensorboardX import SummaryWriter
from scipy.special import softmax
import argparse
from general_functions.dataloaders import get_loaders, get_test_loader
from general_functions.utils import get_logger, weights_init, load, create_directories_from_list, \
... |
import argparse
from tqdm import tqdm
import numpy as np
import cv2
from config import cfg
import torch
from base import Tester
from utils.vis import vis_keypoints
from utils.pose_utils import flip
import torch.backends.cudnn as cudnn
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--... |
# -*- coding: utf-8 -*-
# Owner(s): ["module: autograd"]
from torch.testing._internal.common_utils import TestCase, run_tests, IS_WINDOWS
import pkgutil
import torch
import sys
from typing import Callable
import inspect
import json
import os
import unittest
class TestPublicBindings(TestCase):
def test_no_new_bind... |
# coding: utf-8
#/*##########################################################################
#
# Copyright (c) 2004-2020 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to de... |
from os import DirEntry, read, getcwd
from pathlib import Path
import io
import sys
from globales import *
# Función que lee los cuadruplo
def leerCuadruplos(txt_cuadruplos):
readStr = 0
while readStr < len(txt_cuadruplos):
cantidades = txt_cuadruplos[ readStr:txt_cuadruplos.find( '\n', readStr ) ]
operado... |
#Question: https://python.web.id/blog/given-an-array-of-integers-cf/
def arrayElementsProduct(inputArray):
product = 1
for numb in inputArray:
product *= numb
return product
'''
>>> inputArray = [1, 3, 2, 10]
>>> arrayElementsProduct(inputArray)
60
>>>
>>> inputArray = [2, 4, 10, 1]
>>> arrayEleme... |
import os
ANODOT_API_URL = os.environ.get('ANODOT_API_URL', 'https://api.anodot.com')
ENV_PROD = True if os.environ.get('ENV_PROD') == 'true' else False
HOSTNAME = os.environ.get('HOSTNAME', 'agent')
STREAMSETS_PREVIEW_TIMEOUT = os.environ.get('STREAMSETS_PREVIEW_TIMEOUT', 30000)
VALIDATION_ENABLED = os.environ.get... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import re
from astropy.table import Table
import Quaternion
from parse_cm import read_backstop, read_or_list
from Chandra.Time import DateTime
import hopper
def check_characteristics_date(ofls_characteristics_file, ref_date=None):
# de_bytetring the... |
from solutions.hydrothermal_venture import Grid, Line, Point
def test_lines_from_strings():
"""Given a string of a certain format, lines can be made."""
line = Line.from_string("0,9 -> 3,9")
assert line.points == [Point(0, 9), Point(1, 9), Point(2, 9), Point(3, 9)]
def test_line_can_draw_horizontally_wi... |
#! /usr/bin/python
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__ = "anfv"
__date__ = "$16-May-2016 10:43:47$"
import vision
import cv2
import time
def test_threshold():
... |
"""
The maps that model the different processes in the QKD return for input that is diagonal in Bell-basis a diagonal output.
To reduce calculations I determined in the scipt "How many numbers for state" the effect of the maps on the diagonal elements
"""
import numpy as np
import functools
"""These are some helper fu... |
"""
ZdumpV - command ``/usr/sbin/zdump -v /etc/localtime -c 2019,2039``
===================================================================
The ``/usr/sbin/zdump -v /etc/localtime -c 2019,2039`` command provides information about
'Daylight Saving Time' in file /etc/localtime from 2019 to 2039.
Sample content from com... |
import numpy as np
from ai.domain_adaptation.datasets import image_index
from ai.domain_adaptation.utils import np_utils
from IPython.display import display, Image
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def load_data_for_vis(prob_path, target_domain_file, dataset_dir):
domain... |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
"""Tests of coverage/debug.py"""
import os
import pytest
import coverage
from coverage.backward import StringIO
from coverage.debug import filter_text, info_form... |
#!/usr/bin/python
# from raspberrypi-spy.co.uk
import sys
import time
import RPi.GPIO as GPIO
import curses
# set up curses
stdscr = curses.initscr()
#curses.noecho()
curses.cbreak()
stdscr.keypad(1)
# use BCM GPIO refs
GPIO.setmode(GPIO.BCM)
# define pins
#StepPins = [17, 22, 23, 24]
#StepPins = [35, 36, 37, 38]... |
#!/usr/bin/env python
#
# Copyright 2001 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 require... |
from edna.core.execution.context import StreamingContext
from edna.api import StreamBuilder
from edna.ingest.streaming import SimulatedIngest
from edna.serializers.EmptySerializer import EmptyStringSerializer
from edna.process.map import JsonToObject
from edna.process.filter import KeyedFilter
from edna.emit import ... |
# HitchHikerDemo documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values th... |
import os
import os.path
from os.path import join as pjoin, dirname as pdirname
from distutils.errors import DistutilsPlatformError
from distutils.errors import DistutilsExecError, DistutilsSetupError
from numpy.distutils.command.build_ext import build_ext as old_build_ext
from numpy.distutils.ccompiler import CCompi... |
import fixtures
import testtools
from smiley import db
from smiley import db_linecache
class DBFileCacheTest(testtools.TestCase):
def setUp(self):
super(DBFileCacheTest, self).setUp()
self.useFixture(fixtures.FakeLogger())
self.db = db.DB(':memory:')
self.db.start_run(
... |
# -*- coding: utf-8 -*-
'''
The EC2 Cloud Module
====================
The EC2 cloud module is used to interact with the Amazon Elastic Cloud
Computing.
To use the EC2 cloud module, set up the cloud configuration at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/ec2.conf``:
.. code-block:: yaml
... |
from django.shortcuts import render
from pmedian.tasks import *
from pandas import errors
from pmedapp.common.utilities import *
import json
import pandas as pd
from django.views.decorators.csrf import csrf_exempt
from django.utils.datastructures import MultiValueDictKeyError
import glob
import os.path
@csrf_exempt
d... |
from armulator.armv6.opcodes.abstract_opcodes.rev16 import Rev16
from armulator.armv6.opcodes.opcode import Opcode
class Rev16T2(Rev16, Opcode):
def __init__(self, instruction, m, d):
Opcode.__init__(self, instruction)
Rev16.__init__(self, m, d)
def is_pc_changing_opcode(self):
return... |
# coding: utf-8
# ----------------------------------------------------------------------------
# <copyright company="Aspose" file="AiNameFormatted.py">
# Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtai... |
# -*- coding: utf-8 -*-
"""Mspray task module."""
from __future__ import absolute_import
import gc
import logging
import os
from datetime import timedelta
from django.conf import settings
from django.contrib.gis.geos import Point
from django.contrib.gis.geos.polygon import Polygon
from django.db.models import Q, Sum,... |
# Generated by Django 3.0.8 on 2020-07-22 12:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Home', '0009_auto_20200722_1734'),
]
operations = [
migrations.AlterField(
model_name='student',
name='branch',
... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Simple Fun #182: Happy "g"
#Problem level: 7 kyu
def happy_g(s):
for i in range(len(s)):
if s[i]=='g':
if i==0 and s[i+1]!='g':
return False
if s[i-1]!='g' and s[i+1]!='g':
return False
return True |
import torch
import torch.nn as nn
from fannypack.nn import resblocks
state_dim = 3
control_dim = 7
obs_pos_dim = 3
obs_sensors_dim = 7
def state_layers(units: int) -> nn.Module:
"""Create a state encoder block.
Args:
units (int): # of hidden units in network layers.
Returns:
nn.Module:... |
# coding=utf-8
# Copyright 2020 The Google Research 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from .models import User, Subscription
@admin.register(User)
class UserAdmin(UserAdmin):
fieldsets = (
(None, {'fields': ('username', 'avatar',
'background', 'p... |
### Full credit for this file goes to Richard Fan @ https://github.com/richardfan1126/nitro-enclave-python-demo
import socket
import sys
import threading
import time
def server(local_port, remote_cid, remote_port):
try:
dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dock_socket.bi... |
COLNAMES = ["Column", "UDI", "Count", "Type", "Description"]
COL_JUSTIFY = ["right", "left", "right", "center", "left"] |
#!/usr/bin/env python3
# Copyright (C) 2018-2019 Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted for any purpose (including commercial purposes)
# provided that the following conditions are met:
#
# 1. Redistributions of sourc... |
class Wallet:
def __init__(self, stocks, initial_account=3000):
self.stocks_amount = 0
for stock in stocks:
self.stocks_amount += stock.getCostPrice()
self.available_cash = initial_account - \
self.stocks_amount # argent disponible en cash
self.virtual_acco... |
import FWCore.ParameterSet.Config as cms
# Magnetic Field
# Geometries
# from Geometry.CommonDetUnit.bareGlobalTrackingGeometry_cfi import *
# from RecoMuon.DetLayers.muonDetLayerGeometry_cfi import *
import TrackingTools.KalmanUpdators.Chi2MeasurementEstimator_cfi
EstimatorForSTA = TrackingTools.KalmanUpdators.Chi2Me... |
from server import app, format_decades
from model import Decade, Country, Book, connect_to_db, db
from textprocessor import unpickle_data
from random import sample
from collections import Counter
def measure_and_sample_corpus(data_type, want_sample):
with app.app_context():
decades = format_decades()
... |
# -*- coding: utf-8 -*-
#
# Gargoyle documentation build configuration file, created by
# sphinx-quickstart on Fri May 6 11:47:36 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from maskrcnn_benchmark.modeling import registry
from torch import nn
@registry.ROI_BOX_PREDICTOR.register("FastRCNNPredictor")
class FastRCNNPredictor(nn.Module):
def __init__(self, config, in_channels):
super(FastRCNNPredictor, self... |
# 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
from ... import _utilities, _tables
from... |
from dataclasses import dataclass, field
from typing import Optional
__NAMESPACE__ = "http://hello/"
@dataclass
class HelloByeError:
class Meta:
namespace = "http://hello/"
message: Optional[str] = field(
default=None,
metadata={
"type": "Element",
"namespace"... |
# File: watsonv3_connector.py
#
# Copyright (c) 2021-2022 Splunk 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------
# Name: cache.py
# Python Library
# Author: Raymond Wagner
# Purpose: Caching framework to store TMDb API results
#-----------------------
from __future__ import absolute_import
import time
import os
from .tmdb_exceptions import *
from .cache_engi... |
import numpy as np
def relu(x):
if x > 0:
return x
else:
return 0.0
def cvar_fn_val(sigma, exp_ret_rs, prob_rs, alpha):
fn_val_relu_part = 0.0
for i,ret in enumerate(exp_ret_rs):
fn_val_relu_part += prob_rs[i] * relu(sigma - ret)
fn_val = sigma - 1.0 / (1.0 - alpha) *... |
# Generated by Django 2.2 on 2020-10-17 07:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('student', '0001_initial'),
('core', '0001_initial'),
('library', '0001_initial'),
]
... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'phogram.settings')
try:
from django.core.management import execute_from_command_line
except Impo... |
from django.urls import path, include
urlpatterns = [] |
"""
The typing module: Support for gradual typing as defined by PEP 484.
At large scale, the structure of the module is following:
* Imports and exports, all public names should be explicitly added to __all__.
* Internal helper functions: these should never be used in code outside this module.
* _SpecialForm and its i... |
# pylint: disable=missing-docstring
import os
from resolwe.flow.models import Data, Collection, Relation
from resolwe.flow.models.entity import RelationPartition, RelationType
from resolwe.test import tag_process, with_resolwe_host
from resolwe_bio.expression_filters.relation import replicate_groups
from resolwe_bio... |
# Javier Escalada Gomez
#
# from:
# https://stackoverflow.com/questions/4524723/take-screenshot-in-python-on-mac-os-x
from pyscreenshot.plugins.backend import CBackend
from pyscreenshot.tempexport import read_func_img
class MacQuartzWrapper(CBackend):
name = "mac_quartz"
childprocess = False
def __init_... |
#!/usr/bin/env python
#
# Copyright 2019 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
INFRA_GO = 'go.skia.org/infra'
WHICH = 'where' if sys.platform == 'win32' else 'which'
def check():
'''Verify that g... |
OMDB_API_KEY = 'df397f1b'
YOUTUBE_API_KEY = 'AIzaSyBlr3kG98VwGz5D3QufXG2dqXgj6HDnwpQ' |
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team.
#
# 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... |
import unittest
import math
import random
from src.util.point import Point
from src.core.translate import Translator
from src.core.parse import Parser
from src.util.amino import Amino
class TestPoint(unittest.TestCase):
def test_add(self):
p = Point(1, 2, 3) + Point(2, 4, 6)
self.assertEqual(p, Po... |
import random
import string
from typing import Callable, List, Optional
import discord
from redbot.core import Config
from redbot.core.commands import Context
from redbot.core.bot import Red
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.utils.predicates import MessagePredicate, ReactionPr... |
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtGui as QtGui
import os
import qrcode
import electrum_ltc
from electrum_ltc.i18n import _
from util import WindowModalDialog
class QRCodeWidget(QWidget):
def __init__(self, data = None, fixedSize=False):
QWidget.__init__(self)
s... |
import torch
from torch import nn
from torch.nn import functional as F
import torchvision
def main():
print('cuda device count: ', torch.cuda.device_count())
net = torchvision.models.squeezenet1_1(pretrained=True)
#net.fc = nn.Linear(512, 2)
net = net.eval()
net = net.to('cuda:0')
print(net)
... |
import re
import pytest
from deidentify.base import Annotation, Document
from deidentify.util import mask_annotations, surrogate_annotations
def test_mask_annotations():
text = "De patient J. Jansen (e: j.jnsen@email.com, t: 06-12345678)"
annotations = [
Annotation(text='J. Jansen', start=11, end=20... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Caitlah Technology and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from erpnext.controllers.accounts_controller import AccountsController
class Transferfrom... |
"""
Sponsored project configuration classes
USAGE:
git clone https://github.com/cBioPortal/cbioportal.git
python runSP.py AKT1 ../cbioportal/ --staging
"""
import os
import random
import string
import pandas as pd
import synapseclient
from . import new_redcap_export_mapping
from . import sp_redcap_export_mapping
c... |
#Image Stego using LSB
import cv2
def encode(input_image_name, output_image_name, file_name):
input_image = cv2.imread(input_image_name)
height, width, nbchannels = input_image.shape
size = width*height
current_width = 0
current_height = 0
current_channel = 0
maskonevalues = [1, 2, 4, 8, ... |
# Random shuffle by sentences instead of samples (predicates).
import math
import os
import random
import sys
from os.path import join
def get_sent_to_samples(input_file):
num_samples = 0
sent2samples = []
fin = open(input_file, 'r')
prev_words = ""
prev_predicate = -1
for line in fin:
line = line.str... |
import re
from collections import namedtuple
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
Value = Union[bool, float, int, str]
Variable = str
Term = Union[Value, Variable]
Substitution = Dict[Variable, Term]
Step = namedtuple('Step', ['index', 'literal', 'substi... |
from .allowed_channels import allowed_channels
from .allowed_guilds import allowed_guilds
from .direct_message import direct_message |
#!/usr/bin/python
# pylint: disable=too-many-lines
# -*- coding: utf-8 -*-
# vim: expandtab:tabstop=4:shiftwidth=4
# Reason: Disable pylint too-many-lines because we don't want to split up this file.
# Status: Permanently disabled to keep this module as self-contained as possible.
"""Ansible module for retrieving and ... |
# -*- coding: utf-8 -*-
from basetestcase import BaseTestCase
from couchbase_helper.documentgenerator import doc_generator
from membase.api.rest_client import RestConnection
from couchbase_helper.document import View
class DocumentKeysTests(BaseTestCase):
def setUp(self):
super(DocumentKeysTests, self).s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.