text stringlengths 2 999k |
|---|
# Copyright (c) 2019 Platform9 Systems 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 ... |
"""SCons.Tool.sunf77
Tool-specific initialization for sunf77, the Sun Studio F77 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is... |
# Package: values
# Date: 11th April 2010
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Values
This defines the Value object used by components and events.
"""
from types import ListType
from itertools import imap
from events import Event
class ValueChanged(Event):
"""Value Changed E... |
"""
Deploy semi-supervised PU machine learning models.
This module provides classes for training, testing, and deploying a PU
learning model for predicting material synthesizability. Utility functions
for plotting aid in visualizing and analyzing results.
References:
[1] DOI: 10.1021/acsnano.8b08014
[2] DOI: ... |
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
"""GaussianProcessRegressionSklearn tests.
Scientific Machine Learning Benchmark:
A benchmark of regression models in chem- and materials informatics.
"""
import pytest
import numpy as np
skl = pytest.importorskip("sklearn")
import smlb
from smlb.learners.scikit_learn.gaussian_process_regression_sklearn import Gau... |
# Picking Numbers
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/picking-numbers/problem
def picking_number(n, arr):
max_combinations = 0
for i in range(n):
combination = arr.count(arr[i]) + arr.count(arr[i] + 1)
if combination > max_combinations:
max_co... |
#!/usr/bin/env python3
import os
import sys
from vmaf.core.quality_runner import QualityRunner
from vmaf.core.result_store import FileSystemResultStore
from vmaf.routine import run_remove_results_for_dataset
from vmaf.tools.misc import import_python_file
__copyright__ = "Copyright 2016-2020, Netflix, Inc."
__license__... |
""" Dataframe functions """
import logging
import os
from tempfile import mkstemp
import pandas as pd
from box import Box
# pylint: disable=too-many-arguments
logger = logging.getLogger(__name__) # pylint: disable=C0103
def pd_export(
dataframe: pd.DataFrame,
export_type: str,
df_name: str,
temp_n... |
from .MidiInfo import * |
#!/usr/bin/env python3
import argparse
import json
import urllib.request
if __name__ == '__main__':
parser = argparse.ArgumentParser ()
parser.add_argument ('-v', '--verbose', help = 'Enable Verbose Mode', action = 'store_true')
parser.add_argument ('-ip', help = 'IP Address to Test')
args = parser.parse_arg... |
import os
import json
from pathlib import Path
import jimi
# Initialize
dbCollectionName = "model"
class _model(jimi.db._document):
name = str()
className = str()
classType = str()
location = str()
hidden = bool()
manifest = dict()
_dbCollection = jimi.db.db[dbCollectionName]
def ne... |
import json
from unittest import TestCase
from time import sleep
from cs3api4lab.tests.share_test_base import ShareTestBase
from traitlets.config import LoggingConfigurable
import urllib.parse
class TestLocks(ShareTestBase, TestCase):
einstein_id = '4c510ada-c86b-4815-8820-42cdf82c3d51'
einstein_idp = 'cernbo... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
from typing import Any, Dict
import torchvision.transforms as pth_transforms
from classy_vision.dataset.transforms im... |
import _plotly_utils.basevalidators
class CategoryarraysrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='categoryarraysrc',
parent_name='layout.scene.zaxis',
**kwargs
):
super(CategoryarraysrcValidator, self).__init__(
... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.txt')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
requires = [
'elasticsearch',
'pyramid',
'pyramid_chame... |
# Copyright 2015 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 applicable law or a... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""
DataFrame
---------
An efficient 2D container for potentially mixed-type time series or other
labeled data series.
Similar to its R counterpart, data.frame, except providing automatic data
alignment and a host of useful data manipulation methods having to do with the
labeling information
"""
from __future__ import... |
import geopandas
import shapely.geometry
gdf = geopandas.GeoDataFrame(geometry=[shapely.geometry.Point(x, x) for x in [5,4,3,2]])
gdf.index.name = 'id'
gdf.to_file("test.geojson", index=True, driver='GeoJSON')
gdf.to_file("test.geojson1", driver='GeoJSON') |
r"""
Semimonomial transformation group
The semimonomial transformation group of degree `n` over a ring `R` is
the semidirect product of the monomial transformation group of degree `n`
(also known as the complete monomial group over the group of units
`R^{\times}` of `R`) and the group of ring automorphisms.
The multi... |
import numpy as np
class StaticFns:
@staticmethod
def termination_fn(obs, act, next_obs):
done = np.array([False]).repeat(len(obs))
done = done[:,None]
return done
|
"""Base class for directed graphs."""
# Copyright (C) 2004-2015 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
from copy import deepcopy
import networkx_mod as nx
from networkx_mod.classes.graph import Graph... |
import logging
import logging.config
import os
from celery.utils.log import get_task_logger
from dotenv import load_dotenv
from flask import Flask
from flask_login import LoginManager
from config import config, Config
from .AfricasTalkingGateway import gateway
from .database import db, redis
dotenv_path = os.path.jo... |
from botocore.exceptions import CapacityNotAvailableError
from botocore.retries import bucket
from tests import unittest
class FakeClock(bucket.Clock):
def __init__(self, timestamp_sequences):
self.timestamp_sequences = timestamp_sequences
self.sleep_call_amounts = []
def sleep(self, amount):... |
# -*- coding: utf-8 -*-
# Copyright 2020 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Letter-color Consistency test
O.Colizoli 2020
Each letter of the alphabet in random order x 2
Color wheel opens at a randomized color on each trial (but does not turn)
Python 2..7
"""
# data saved in ~/LogFiles/sub-XXX
# Import necessary modules
import random
import n... |
import pytest
from list_utils import *
from oracle import ColumnRecommendation, ColumnClassification
def test_find_one():
needle = 1
none = [0, 0, 5, 's']
beginning = [1, None, 9, 6, 0, 0]
end = ['x', '0', 1]
several = [0, 0, 3, 4, 1, 3, 2, 1, 3, 4]
assert find_one(none, needle) == False
... |
import logging
import azure.functions as func
import json
import os
from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
# Connect to Azu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 15:25:03 2018
@author: bathmann
"""
from .TreeDynamicTimeStepping import TreeDynamicTimeStepping
from .TreeDynamicTimeLoop import TreeDynamicTimeLoop
from .SimpleTimeLoop.SimpleLoop import Loop
|
'''
File: detect_forest_change.py
Author: Min Feng
Version: 0.1
Create: 2018-04-20 15:42:37
Description: detect forest changes from foest probility layers and tree cover layers
'''
import logging
def _load_tcc(f_tcc, msk):
from gio import geo_raster_ex as gx
from gio import config
import nump... |
import datetime
import logging
import traceback
from dis_snek.models import ComponentContext
from dis_snek.models import InteractionContext
from ElevatorBot.misc.formating import embed_message
def get_now_with_tz() -> datetime.datetime:
"""Returns the current datetime (timezone aware)"""
return datetime.da... |
# 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... |
#!/usr/bin/env python
"""
C.11.5 Index and Glossary (p211)
"""
import string, os
from plasTeX.Tokenizer import Token, EscapeSequence
from plasTeX import Command, Environment
from plasTeX.Logging import getLogger
from Sectioning import SectionUtils
try:
from pyuca import Collator
collator = Collator(os.path.... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
def delete_disconnected_nodes(gd):
# delete all nodes with no inputs a... |
import numpy as np
def _main():
# Inputs
n = 3
x = np.arange(20, dtype=np.float64)
# Slow average/std
avg = np.zeros(len(x) - n + 1)
std = np.zeros(len(x) - n + 1)
for i in range(len(avg)):
avg[i] = np.mean(x[i:i+n])
std[i] = np.std(x[i:i+n])
print('AVG')
print('\... |
import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.modeling_bert import (
BERT_INPUTS_DOCSTRING,
BERT_START_DOCSTRING,
BertEmbeddings,
BertLayer,
... |
# *** WARNING: this file was generated by the Kulado Kubernetes codegen tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import kulado
import kulado.runtime
import warnings
from ... import tables, version
class ClusterRoleBindingList(kulado.CustomResource):
"""
Clus... |
import logging
from .base import ApplicationWrapper
from ..configuration.utils import coerce_config
from ..support.converters import asbool
log = logging.getLogger(__name__)
class IdentityApplicationWrapper(ApplicationWrapper):
"""Provides user identity when authentication is enabled.
The repoze.who provide... |
#!/usr/bin/env python3
# This file is Copyright (c) 2018-2019 Rohit Singh <rohit@rohitksingh.in>
# This file is Copyright (c) 2019 Florent Kermarrec <florent@enjoy-digital.fr>
# License: BSD
import sys
from migen import *
from litex.build.generic_platform import *
from litex.soc.integration.soc_core import *
from l... |
# coding: utf-8
import pytest
from edipy import fields, validators, exceptions
@pytest.mark.parametrize('fixed_type, data', [
(fields.Integer(1, validators=[validators.Range(1, 5)]), '1'),
(fields.Integer(1, validators=[validators.MaxValue(3)]), '2'),
(fields.Integer(1, validators=[validators.MinValue(1... |
"""
tulflow.harvest
~~~~~~~~~~~~~~~
This module contains objects to harvest data from one given location to another.
"""
import hashlib
import io
import logging
import pandas
import sickle
from lxml import etree
from sickle import Sickle
from sickle.models import xml_to_dict
from sickle.oaiexceptions import NoRecordsMa... |
import turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
RIGHT = 0
LEFT = 180
class Snake:
"""Initializes length and segments of snake."""
def __init__(self):
self.length = 3
self.segments = []
self.create_snake()
se... |
# -*- coding: utf-8 -*-
"""This module contains all functions and classes for the MLTree. The MLTree buils a tree-like
structure of the objects in a given repository. This allows the user to access objects in a
comfortable way allowing for autocompletion (i.e. in Jupyter notebooks).
To use it one can simply call the :... |
count = input('How many people will be in the dinner group? ')
count = int(count)
if count > 8:
print('You\'ll have to wait for a table.')
else:
print('The table is ready.')
|
#!/usr/bin/env python
from distutils.core import setup
from glob import glob
from setuptools import find_packages
setup(name='Fibonacci',
version='1.0',
description='Python Distribution Utilities',
author='Kevin Chen',
packages=find_packages('src'),
package_dir={'': 'src'},
py_mo... |
# Copyright 2013 Cloudbase Solutions Srl
# 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 r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file an... |
"""basic ding-dong bot for the wechaty plugin"""
from typing import Union
from wechaty import Message, Contact, Room, FileBox
from wechaty.plugin import WechatyPlugin
class DingDongPlugin(WechatyPlugin):
"""basic ding-dong plugin"""
@property
def name(self):
"""name of the plugin"""
retur... |
"""
_WorkQueueTestCase_
Unit tests for the WMBS File class.
"""
from __future__ import print_function
import time
import unittest
from WMCore.Agent.HeartbeatAPI import HeartbeatAPI
from WMQuality.TestInit import TestInit
class HeartbeatTest(unittest.TestCase):
def setUp(self):
"""
_setUp_
... |
# Generated by Django 2.2.10 on 2020-03-20 13:00
import wagtail.core.blocks
import wagtail.core.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("budgetportal", "0053_custompage"),
]
operations = [
migrations.AddField(
model_na... |
import torch
from torch import nn
from torchvision.models.vgg import vgg16
class GeneratorLoss_NEW(nn.Module):
def __init__(self):
super(GeneratorLoss_NEW, self).__init__()
vgg = vgg16(pretrained=True)
# loss_network = nn.Sequential(*list(vgg.features)[:31]).eval()
loss_network = n... |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
from kivy.graphics import Color
from .navigation import Navigation
class Colors:
WHITE = Color(1, 1, 1, 1)
BLACK = Color(0, 0, 0, 1)
GREY = Color(.8, .8, .8, 1)
RED = Color(1, 0, 0, 1)
GREEN = Color(0, 1, 0, 1)
BLUE = Color(0, 0, 1, 1)
@staticmethod
def lerp(value, *args):
... |
from core.plugins.openstack import (
OpenstackChecksBase,
)
FEATURES = {'neutron': {'main': [
'availability_zone'],
'openvswitch-agent': [
'l2_population',
'firewall_driver'],
'l3-age... |
from rest_framework import serializers
from wallet.models import UserWallet, PaymentMethod, DriverWallet
class UserWalletSerializer(serializers.ModelSerializer):
class Meta:
model = UserWallet
fields = "__all__"
class DriverWalletSerializer(serializers.ModelSerializer):
class Meta:
m... |
from typing import List, Callable
from autumn.curve import scale_up_function
def get_importation_rate_func_as_birth_rates(
importation_times: List[float],
importation_n_cases: List[float],
detect_prop_func,
starting_pops: list,
):
"""
When imported cases are explicitly simulated as part of the... |
class Mahasiswa:
def __init__(self, nama, nilai):
self.nama = nama
self.nilai = nilai
def hitung_nilai(self):
return sum(self.nilai)/len(self.nilai)
mahasiswa = Mahasiswa("Fazlur", (90,70,70,70))
print("Nama :", mahasiswa.nama)
print("Total Nilai :", mahasiswa.hitung_nilai()) |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
"""
Contains classes related to Roblox group data and parsing.
"""
from typing import Optional, Tuple
from .bases.basegroup import BaseGroup
from .partials.partialuser import PartialUser
from .shout import Shout
from .utilities.shared import ClientSharedObject
class Group(BaseGroup):
"""
Represents a Join... |
# noqa
from typing import Any, BinaryIO
class CustomSerializer:
"""Custom serializer implementation to test the injection of different serialization strategies to an input."""
@property
def extension(self) -> str: # noqa
return "ext"
def serialize(self, value: Any, writer: BinaryIO): # noq... |
import io
import os
import re
import struct
from xml.etree import ElementTree
_UNIT_KM = -3
_UNIT_100M = -2
_UNIT_10M = -1
_UNIT_1M = 0
_UNIT_10CM = 1
_UNIT_CM = 2
_UNIT_MM = 3
_UNIT_0_1MM = 4
_UNIT_0_01MM = 5
_UNIT_UM = 6
_UNIT_INCH = 6
_TIFF_TYPE_SIZES = {
1: 1,
2: 1,
3: 2,
4: 4,
5: 8,
6: 1,
7: 1,
8... |
def digest_target(target):
from .element import digest_element
return digest_element(target)
|
# Copyright 2017 The TensorFlow Authors and modified by Emilien Garreau. 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.... |
# -*- coding: utf-8 -*-
import os
import re
import json
import os.path
import unittest
reg_cmnt = re.compile(r"/\*.*?\*/", re.DOTALL)
class Config:
"Работа с конфигурационным файлом"
def __init__(self, main_path=None, user_path=None):
if main_path is None:
self._main_path = "config.json... |
import pytest
import copy
from pathlib import Path
import sys
sys.path.append(str(Path(__file__).absolute().parent.parent))
from swimmer_abm.model import Model
def test_init():
model = Model(nswimmers=3)
assert len(model.swimmers) == 3
def test_step():
model = Model(nswimmers=1)
swimmer = copy.dee... |
#!/usr/bin/python3
class Evaluator:
def __init__(self, lexer):
self.__lexer = lexer
def evaluate(self, line):
return int(next(self.__lexer.tokenize(line)).raw_value)
class REPL:
def __init__(self, read, print, evaluate):
self.__read = read
self.__eval = evaluate
sel... |
import os
from time import sleep
import pytest
from tlz import frequencies
from distributed import get_task_stream
from distributed.client import wait
from distributed.diagnostics.task_stream import TaskStreamPlugin
from distributed.metrics import time
from distributed.utils_test import div, gen_cluster, inc, slowinc... |
"""This module implements the dataset item entity"""
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import abc
import copy
import itertools
import logging
from threading import Lock
from typing import List, Optional, Sequence
import numpy as np
from ote_sdk.entities.annotation i... |
from sys import argv, exit
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setCentralWidget(CustomWidget(self))
self.show()
class Cus... |
# Copyright 2011 OpenStack Foundation.
# 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 req... |
# -*- coding:utf-8; -*-
class SolutionV1:
def combinationSum(self, candidates, target):
# 1. 定义保存结果的组合
result = set()
# 2. 定义递归函数,i表示递归层数,但是具体含义还不知道
def helper(nums, candidates, target):
# 4. 编写递归模板
# 1) 定义递归终止条件
# 应该是从candidate选出来的数的sum=target就... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import six
from datetime import datetime
from django.utils import timezone
from sentry.models import Commit, CommitAuthor, Integration, PullRequest, Repository
from sentry.testutils import APITestCase
from uuid import uuid4
from .testutils import (
P... |
"""
Calls the Turbomole executable.
"""
import os
import re
from decimal import Decimal
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
from qcelemental.models import AtomicResult, Provenance, BasisSet
from qcelemental.util import safe_version, which
from ...exceptions import InputError
from ..... |
from datetime import datetime
from functools import partial
from typing import Callable, List, Union
from symbiotic.schedule import Schedule
class Action(object):
def __init__(self, callback: Callable, *args, **kwargs):
self._callback: partial = partial(callback, *args, **kwargs)
self._schedule:... |
import os
import json
def combine_schema(borough_name):
borough_name = borough_name.lower()
neighborhood_data = ""
with open('../scraped_data/borough_schema/' + borough_name + ".json", 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
for zipCodes in range(len(data[borough_n... |
"""Implementations of metrics for 3D semantic segmentation."""
import tensorflow as tf
def average_volume_difference():
raise NotImplementedError()
def dice(y_true, y_pred, axis=(1, 2, 3, 4)):
"""Calculate Dice similarity between labels and predictions.
Dice similarity is in [0, 1], where 1 is perfect... |
# Copyright 2016 Bridgewater Associates
#
# 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... |
import numpy as np
from sklearn import metrics
import math
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
from typing import *
# fastai utility
def listify(o):
if o is None: return []
if isinstance(o, list): return o
if isinstance(o, str): return [o]
if isinstan... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 30, transform = "RelativeDifference", sigma = 0.0, exog_count = 20, ar_order = 12); |
import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['BoxCox'] , ['ConstantTrend'] , ['Seasonal_DayOfMonth'] , ['MLP'] ); |
from PIL import Image
import numpy as np
import colorsys
import os, sys
import argparse
import matplotlib.pyplot as plt
rgb_to_hsv = np.vectorize(colorsys.rgb_to_hsv)
hsv_to_rgb = np.vectorize(colorsys.hsv_to_rgb)
def crop(image, box=None):
if box:
imageBox = box
else:
imageBox = image.getbb... |
# This is a simple application for alert system
from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("200x200")
def message():
messagebox.showwarning("Alert Box", "Stop virus found")
but = Button(root, text="ok", command=Message)
but.place(x=100, y=100)
root.mainloop() |
'''
Created on 26.07.2018
@author: yvo
'''
import configparser
import sys
from dataflow.DataReaders.DatabaseReaders.GlacierReader import GlacierReader
from dataflow.DataReaders.DatabaseReaders.InventoryReader import InventoryReader
def printLatestOutline(glaciers):
for glacier in glaciers.values():
... |
# 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
#
# Unless required by applica... |
"""WSGI File that enables Apache/GUnicorn to run Django"""
# pylint: disable=C0103
import os
import sys
from django.core.wsgi import get_wsgi_application
sys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(os.pardir), os.pardir)))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(os.path.di... |
from concurrent import futures
import time
import grpc
import app.helloworld_pb2 as helloworld_pb2
import app.helloworld_pb2_grpc as helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def Greet(self, request, context):
print('Saying `hello` to %s... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from taggit.managers import TaggableManager
from server.connective_tags.models import ConnectiveTaggedItem
from server.schools.models import School
from server.utils.db_utils import get... |
#!/usr/bin/env python
#
# Copyright 2015-2016 Flavio Garcia
#
# 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... |
from tqdm import tqdm
import pandas as pd
from __init__ import FILE
df = pd.read_csv(FILE)
smiles = list(df["Smiles"])
with open("_chemprop.csv", "w") as f:
f.write("smiles\n")
for smi in smiles:
f.write("{0}\n".format(smi))
|
# coding=utf-8
import copy
import functools
from typing import List
import torch
import torch.distributed._shard.sharding_spec as shard_spec
from .api import (
_register_sharded_op,
Shard,
ShardedTensor,
ShardedTensorMetadata,
TensorProperties,
)
from .metadata import ShardMetadata # noqa: F401
... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import logging
import math
import operator
import os
import queue
import time
from threading import Thread
import numpy as n... |
#!/usr/bin/env python3
from parse_topology_for_hydrogens import parse_top_for_h
def gen_h_ndx(orig_ndx, topology, out_name='h_prot.ndx'):
ndx_ind = list()
with open(orig_ndx, 'r') as f:
line = f.readline()
while '[ Protein ]' not in line:
line = f.readline()
line = f.readl... |
from suds.client import Client
from suds import WebFault
from model.project import Project
class SoapHelper:
def __init__(self, app):
self.app = app
def can_login(self, username, password):
client = Client("http://localhost:8080/mantisbt-1.2.20/api/soap/mantisconnect.php?wsdl")
try:
... |
#!/usr/bin/python
import requests
import os
token = os.getenv("DOCKER_HUB_TOKEN")
version = os.getenv("VERSION")
if token==None:
print "env DOCKER_HUB_TOKEN not set"
exit(1)
if version==None:
print "env VERSION not set"
exit(1)
url = "https://registry.hub.docker.com/u/skbkontur/kibana/trigger/%s... |
# -*- encoding:utf8 -*-
try:
from jinja2 import Environment, PackageLoader
except ImportError:
raise ImportError('Scaffolding support requires the Jinja 2 templating library to be installed.')
template_environment = Environment(loader=PackageLoader('denim.scaffold'))
def single(template_file, output_name, co... |
def sol():
a, b = 0, 1
for i in range(int(input())):
a, b = b, a + b
print(a)
if __name__ == "__main__":
sol()
|
import json
import platform
import requests
import six
import sys
from .version import __version__
class SlackRequest(object):
def __init__(
self,
proxies=None
):
# HTTP configs
self.custom_user_agent = None
self.proxies = proxies
# Construct the user-... |
#
# Copyright (c) 2020 Project CHIP Authors
# Copyright (c) 2020 Google LLC.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.