file_path
stringlengths
10
10
code
stringlengths
79
330k
code_en
stringlengths
79
330k
language
stringclasses
1 value
license
stringclasses
0 values
token_count
int32
24
158k
0012137.py
import requests from classes.login import Login from classes.logger import logger log = logger().log with open('config/accounts.txt') as accounts_file: accounts = accounts_file.read().splitlines() def run(x): req = requests.Session() log("{} Attempting Login".format(x.split(':')[0])) l = Login(req)...
import requests from classes.login import Login from classes.logger import logger log = logger().log with open('config/accounts.txt') as accounts_file: accounts = accounts_file.read().splitlines() def run(x): req = requests.Session() log("{} Attempting Login".format(x.split(':')[0])) l = Login(req)...
en
null
116
0037288.py
#!/usr/bin/env python # ROS imports import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError # Custom ROS imports from av_msgs.msg import Mode, States from prius_msgs.msg import Control # Python imports import cv2 class Visualizer: def __init__(self): # Front camera...
#!/usr/bin/env python # ROS imports import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError # Custom ROS imports from av_msgs.msg import Mode, States from prius_msgs.msg import Control # Python imports import cv2 class Visualizer: def __init__(self): # Front camera...
en
null
1,826
0004111.py
import json import pytest import os import sys abs_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(f'{abs_path}/../..') sys.path.append(f'{abs_path}/../../..') print(sys.path[-1]) from moto import mock_dynamodb2 from redirect_handler import app import boto_utils from constants import TABLE_NAME import...
import json import pytest import os import sys abs_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(f'{abs_path}/../..') sys.path.append(f'{abs_path}/../../..') print(sys.path[-1]) from moto import mock_dynamodb2 from redirect_handler import app import boto_utils from constants import TABLE_NAME import...
en
null
559
0005128.py
import time from threading import Event, RLock from mltk.utils import hexdump from .device_interface import DeviceInterface, MAX_BUFFER_SIZE WAIT_FOREVER = 4294967.0 class JLinkDataStream(object): """JLink data stream""" def __init__( self, name:str, mode:str, ifc: Dev...
import time from threading import Event, RLock from mltk.utils import hexdump from .device_interface import DeviceInterface, MAX_BUFFER_SIZE WAIT_FOREVER = 4294967.0 class JLinkDataStream(object): """JLink data stream""" def __init__( self, name:str, mode:str, ifc: Dev...
en
null
2,940
0024653.py
from json import loads from ..models.response import ErrorMessage class WebsiteContactsApiError(Exception): def __init__(self, message): self.message = message @property def message(self): return self._message @message.setter def message(self, message): self._message = me...
from json import loads from ..models.response import ErrorMessage class WebsiteContactsApiError(Exception): def __init__(self, message): self.message = message @property def message(self): return self._message @message.setter def message(self, message): self._message = me...
en
null
395
0003043.py
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import base64 import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors impor...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import base64 import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors impor...
en
null
8,387
0011540.py
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework.authtoken.views import ObtainAuthToken from res...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework.authtoken.views import ObtainAuthToken from res...
en
null
1,125
0017190.py
from torch import nn, Tensor from typing import Any, Callable, Iterable, Sequence, Tuple, TypeVar, Union from .utils.device import Device try: from typing import GenericMeta, NamedTupleMeta # type: ignore class GenericNamedMeta(NamedTupleMeta, GenericMeta): pass except ImportError: from typing i...
from torch import nn, Tensor from typing import Any, Callable, Iterable, Sequence, Tuple, TypeVar, Union from .utils.device import Device try: from typing import GenericMeta, NamedTupleMeta # type: ignore class GenericNamedMeta(NamedTupleMeta, GenericMeta): pass except ImportError: from typing i...
en
null
270
0019355.py
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 ...
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 ...
en
null
763
0015736.py
# coding=utf-8 """Using 2 different textures in the same Fragment Shader""" import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_sh...
# coding=utf-8 """Using 2 different textures in the same Fragment Shader""" import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_sh...
en
null
2,219
0045170.py
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. __name__ = "biotite.application" __author__ = "Patrick Kunzmann" __all__ = ["MSAApp"] import abc from tempfile import NamedTemporaryFile from collections import Or...
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. __name__ = "biotite.application" __author__ = "Patrick Kunzmann" __all__ = ["MSAApp"] import abc from tempfile import NamedTemporaryFile from collections import Or...
en
null
3,119
0023175.py
import _plotly_utils.basevalidators class TemplateitemnameValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name='templateitemname', parent_name='layout.polar.radialaxis.tickformatstop', **kwargs ): super(TemplateitemnameValidator, sel...
import _plotly_utils.basevalidators class TemplateitemnameValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name='templateitemname', parent_name='layout.polar.radialaxis.tickformatstop', **kwargs ): super(TemplateitemnameValidator, sel...
en
null
134
0023405.py
# Natural Language Toolkit: IEER Corpus Reader # # Copyright (C) 2001-2014 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com> # Edward Loper <edloper@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Corpus reader for the Information Extraction and Entity Recognition C...
# Natural Language Toolkit: IEER Corpus Reader # # Copyright (C) 2001-2014 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com> # Edward Loper <edloper@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Corpus reader for the Information Extraction and Entity Recognition C...
en
null
1,262
0001286.py
import IoTSensor import LORAGateway class GatewayPlacement: def __init__(self, sensor_list): self._sensor_list = sensor_list self._gateway_list = [] def add_gateway(self, gateway): self._gateway_list.append(gateway) def remove_gateway(self, gateway): self._gateway_list.re...
import IoTSensor import LORAGateway class GatewayPlacement: def __init__(self, sensor_list): self._sensor_list = sensor_list self._gateway_list = [] def add_gateway(self, gateway): self._gateway_list.append(gateway) def remove_gateway(self, gateway): self._gateway_list.re...
en
null
377
0012701.py
# type: ignore import os from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool from learning.entities import Base # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret th...
# type: ignore import os from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool from learning.entities import Base # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret th...
en
null
558
0002036.py
from flask_restful import abort, Resource from flask import request, g, session from flask.json import jsonify from whistle_server.models.user import User def verify_password(password, hashed): from werkzeug.security import check_password_hash return check_password_hash(hashed, password) class LoginEndpoint(R...
from flask_restful import abort, Resource from flask import request, g, session from flask.json import jsonify from whistle_server.models.user import User def verify_password(password, hashed): from werkzeug.security import check_password_hash return check_password_hash(hashed, password) class LoginEndpoint(R...
en
null
401
0010815.py
import copy import math import pprint import unittest import pytest from pint import Context, DimensionalityError, UnitRegistry from pint.compat import np from pint.testsuite import QuantityTestCase, helpers from pint.unit import UnitsContainer from pint.util import ParserHelper ureg = UnitRegistry() class TestIss...
import copy import math import pprint import unittest import pytest from pint import Context, DimensionalityError, UnitRegistry from pint.compat import np from pint.testsuite import QuantityTestCase, helpers from pint.unit import UnitsContainer from pint.util import ParserHelper ureg = UnitRegistry() class TestIss...
en
null
9,302
0006985.py
import socket import gevent import time from tempfile import NamedTemporaryFile from locust.user import task, TaskSet from locust.contrib.fasthttp import FastHttpSession from locust import FastHttpUser from locust.exception import CatchResponseError, InterruptTaskSet, ResponseError from locust.main import is_user_clas...
import socket import gevent import time from tempfile import NamedTemporaryFile from locust.user import task, TaskSet from locust.contrib.fasthttp import FastHttpSession from locust import FastHttpUser from locust.exception import CatchResponseError, InterruptTaskSet, ResponseError from locust.main import is_user_clas...
en
null
7,557
0004310.py
# -*- coding: utf-8 -*- import urlparse from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from tests.factories import AuthUserFactory from api.base.settings.defaults import API_BASE class TestUsers(ApiTestCase): def setUp(self): super(TestUsers, self).setUp() self.user...
# -*- coding: utf-8 -*- import urlparse from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from tests.factories import AuthUserFactory from api.base.settings.defaults import API_BASE class TestUsers(ApiTestCase): def setUp(self): super(TestUsers, self).setUp() self.user...
en
null
909
0040169.py
from flask import Flask,render_template,url_for,request import pandas as pd import pickle import numpy as np import re filename = "model.pkl" cv = pickle.load(open('transform.pkl',"rb")) clf = pickle.load(open(filename,"rb")) app = Flask(__name__) @app.route('/') def home(): return render_template('...
from flask import Flask,render_template,url_for,request import pandas as pd import pickle import numpy as np import re filename = "model.pkl" cv = pickle.load(open('transform.pkl',"rb")) clf = pickle.load(open(filename,"rb")) app = Flask(__name__) @app.route('/') def home(): return render_template('...
en
null
230
0023756.py
import re import sys import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams from scipy.integrate import simps from scipy.special import logsumexp from scipy.optimize import minimize # from sklearn.cluster import DBSCAN # from sklearn.preprocessing import StandardScaler import time import ra...
import re import sys import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams from scipy.integrate import simps from scipy.special import logsumexp from scipy.optimize import minimize # from sklearn.cluster import DBSCAN # from sklearn.preprocessing import StandardScaler import time import ra...
en
null
2,484
0036415.py
"""EpochArray tests""" import nelpy as nel from nelpy.core import * class TestEpochArray: def test_partition(self): ep = EpochArray([0,10]) partitioned = ep.partition(n_epochs=5) assert ep.n_epochs == 1 assert partitioned.n_epochs == 5 # epochs_a = nel.EpochArray([[0, 5], [5,10],...
"""EpochArray tests""" import nelpy as nel from nelpy.core import * class TestEpochArray: def test_partition(self): ep = EpochArray([0,10]) partitioned = ep.partition(n_epochs=5) assert ep.n_epochs == 1 assert partitioned.n_epochs == 5 # epochs_a = nel.EpochArray([[0, 5], [5,10],...
en
null
277
0006257.py
from datetime import datetime from pandas import DataFrame from models.PyCryptoBot import PyCryptoBot from models.AppState import AppState from models.helper.LogHelper import Logger import sys class Strategy: def __init__( self, app: PyCryptoBot = None, state: AppState = AppState, ...
from datetime import datetime from pandas import DataFrame from models.PyCryptoBot import PyCryptoBot from models.AppState import AppState from models.helper.LogHelper import Logger import sys class Strategy: def __init__( self, app: PyCryptoBot = None, state: AppState = AppState, ...
en
null
4,494
0009031.py
"""Test the miniencoding lib A decent testing approach is to test the round trip with a random, valid string of bytes. by taking this approach, the same error/ bug would have to be present in both the 'from' and 'to' functions which whilst possible is unlikely """ # pylint: disable=invalid-name import random import st...
"""Test the miniencoding lib A decent testing approach is to test the round trip with a random, valid string of bytes. by taking this approach, the same error/ bug would have to be present in both the 'from' and 'to' functions which whilst possible is unlikely """ # pylint: disable=invalid-name import random import st...
en
null
3,014
0006477.py
from PIL import Image from django.conf import settings from . import forms, recognition from . import utils from . import models from django.shortcuts import render, redirect from django.contrib import admin from django.core.mail import send_mail from django.http import JsonResponse from django.views.decorators.csrf im...
from PIL import Image from django.conf import settings from . import forms, recognition from . import utils from . import models from django.shortcuts import render, redirect from django.contrib import admin from django.core.mail import send_mail from django.http import JsonResponse from django.views.decorators.csrf im...
en
null
1,732
0026971.py
# -*- coding: utf-8 -*- from datetime import datetime from parser import Model from parser.cmds.cmd import CMD from parser.utils.corpus import Corpus from parser.utils.data import TextDataset, batchify import torch class Predict(CMD): def add_subparser(self, name, parser): subparser = parser.add_parser...
# -*- coding: utf-8 -*- from datetime import datetime from parser import Model from parser.cmds.cmd import CMD from parser.utils.corpus import Corpus from parser.utils.data import TextDataset, batchify import torch class Predict(CMD): def add_subparser(self, name, parser): subparser = parser.add_parser...
en
null
504
0004729.py
import json from Qt import QtGui from Qt import QtWidgets def set_palette_from_dict(dct): """Set palette to current QApplication based on given dictionary""" groups = ["Disabled", "Active", "Inactive", "Normal"] roles = [ "AlternateBase", "Background", "Base", "Button", ...
import json from Qt import QtGui from Qt import QtWidgets def set_palette_from_dict(dct): """Set palette to current QApplication based on given dictionary""" groups = ["Disabled", "Active", "Inactive", "Normal"] roles = [ "AlternateBase", "Background", "Base", "Button", ...
en
null
842
0029243.py
#!/usr/bin/env python #===----------------------------------------------------------------------===## # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===------------...
#!/usr/bin/env python #===----------------------------------------------------------------------===## # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===------------...
en
null
1,351
0001235.py
Inc('dfaccto/util.py', abs=True) class _Event(ModuleContext): def __init__(self): ModuleContext.__init__(self) self._setup_packages() def _setup_packages(self): self.pkg = Pkg('dfaccto_event', x_templates={self.File('generic/package.vhd.tpl'): self.File('pkg/dfaccto_event.vhd')}) with se...
Inc('dfaccto/util.py', abs=True) class _Event(ModuleContext): def __init__(self): ModuleContext.__init__(self) self._setup_packages() def _setup_packages(self): self.pkg = Pkg('dfaccto_event', x_templates={self.File('generic/package.vhd.tpl'): self.File('pkg/dfaccto_event.vhd')}) with se...
en
null
506
0014243.py
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : data_loader.py # @Time : Created at 2019-05-31 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import random from torch.utils.data import Dataset, DataLoader...
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : data_loader.py # @Time : Created at 2019-05-31 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import random from torch.utils.data import Dataset, DataLoader...
en
null
1,388
0000670.py
# 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...
# 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...
en
null
1,426
0019469.py
# Copyright (c) 2020 Graphcore Ltd. 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 l...
# Copyright (c) 2020 Graphcore Ltd. 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 l...
en
null
4,961
0040142.py
import pandas as pd import numpy as np from bokeh.plotting import figure, show, output_notebook,ColumnDataSource,curdoc from bokeh.models import HoverTool, Select, Div from bokeh.layouts import row, column from bokeh.transform import dodge data1 = pd.read_csv('latimes-state-totals.csv') data1['date_time']=pd.to_datet...
import pandas as pd import numpy as np from bokeh.plotting import figure, show, output_notebook,ColumnDataSource,curdoc from bokeh.models import HoverTool, Select, Div from bokeh.layouts import row, column from bokeh.transform import dodge data1 = pd.read_csv('latimes-state-totals.csv') data1['date_time']=pd.to_datet...
en
null
2,096
0009032.py
""" Definition of views. """ from __future__ import absolute_import, division, print_function, unicode_literals import config from django.shortcuts import render, HttpResponse from django.http import HttpRequest, JsonResponse from django.template import RequestContext import ee import datetime as dt import types im...
""" Definition of views. """ from __future__ import absolute_import, division, print_function, unicode_literals import config from django.shortcuts import render, HttpResponse from django.http import HttpRequest, JsonResponse from django.template import RequestContext import ee import datetime as dt import types im...
en
null
1,431
0047692.py
""" Copyright (c) 2022 Intel Corporation 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 writin...
""" Copyright (c) 2022 Intel Corporation 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 writin...
en
null
931
0018047.py
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
en
null
9,095
0009619.py
from django.conf import settings from django.utils import translation import jingo import pytest from mock import Mock, patch from nose.tools import eq_ import amo import amo.tests from addons.models import Addon from translations import helpers from translations.fields import save_signal from translations.models imp...
from django.conf import settings from django.utils import translation import jingo import pytest from mock import Mock, patch from nose.tools import eq_ import amo import amo.tests from addons.models import Addon from translations import helpers from translations.fields import save_signal from translations.models imp...
en
null
1,871
0002241.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. """ Almost every FBCodeBuilder string is ultimately passed to a shell. Escaping too little or too much tends to be the most common error. The utilities in this file give a systematic way of avoiding such bugs: - When you write literal strings ...
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. """ Almost every FBCodeBuilder string is ultimately passed to a shell. Escaping too little or too much tends to be the most common error. The utilities in this file give a systematic way of avoiding such bugs: - When you write literal strings ...
en
null
968
0025510.py
""" Configuration for docs """ # source_link = "https://github.com/[org_name]/calculation" # docs_base_url = "https://[org_name].github.io/calculation" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context): context.brand_html = "Calculat...
""" Configuration for docs """ # source_link = "https://github.com/[org_name]/calculation" # docs_base_url = "https://[org_name].github.io/calculation" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context): context.brand_html = "Calculat...
en
null
101
0004888.py
"""Tests for 1-Wire sensor platform.""" from unittest.mock import patch from pyownet.protocol import Error as ProtocolError import pytest from homeassistant.components.onewire.const import ( DEFAULT_SYSBUS_MOUNT_DIR, DOMAIN, PLATFORMS, ) from homeassistant.components.sensor import ATTR_STATE_CLASS, DOMAIN...
"""Tests for 1-Wire sensor platform.""" from unittest.mock import patch from pyownet.protocol import Error as ProtocolError import pytest from homeassistant.components.onewire.const import ( DEFAULT_SYSBUS_MOUNT_DIR, DOMAIN, PLATFORMS, ) from homeassistant.components.sensor import ATTR_STATE_CLASS, DOMAIN...
en
null
2,774
0027237.py
# -*- coding: utf-8 -*- """ test_simple_decompression ~~~~~~~~~~~~~~~~~~~~~~~~~ Tests for decompression of single chunks. """ import brotlicffi import pytest def test_decompression(simple_compressed_file): """ Decompressing files returns their original form using decompress. """ with open(simple_com...
# -*- coding: utf-8 -*- """ test_simple_decompression ~~~~~~~~~~~~~~~~~~~~~~~~~ Tests for decompression of single chunks. """ import brotlicffi import pytest def test_decompression(simple_compressed_file): """ Decompressing files returns their original form using decompress. """ with open(simple_com...
en
null
776
0035152.py
import numpy as np import torch import torch.nn as nn from models.CCNet.CC import CC_module as CrissCrossAttention affine_par = True BatchNorm2d = nn.BatchNorm2d def outS(i): i = int(i) i = (i + 1) / 2 i = int(np.ceil((i + 1) / 2.0)) i = (i + 1) / 2 return i def conv3x3(in_planes, out_planes, s...
import numpy as np import torch import torch.nn as nn from models.CCNet.CC import CC_module as CrissCrossAttention affine_par = True BatchNorm2d = nn.BatchNorm2d def outS(i): i = int(i) i = (i + 1) / 2 i = int(np.ceil((i + 1) / 2.0)) i = (i + 1) / 2 return i def conv3x3(in_planes, out_planes, s...
en
null
2,420
0033809.py
# Copyright (c) 2019 Deere & Company # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import smtplib from _common_setup import * from models.FieldOperation import FieldOperation from models.FieldOperationMeasurement import FieldOpMeasurem...
# Copyright (c) 2019 Deere & Company # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import smtplib from _common_setup import * from models.FieldOperation import FieldOperation from models.FieldOperationMeasurement import FieldOpMeasurem...
en
null
1,901
0014452.py
from __future__ import division, print_function import six from time import time, ctime from subprocess import PIPE, CalledProcessError if six.PY3: from subprocess import run else: from subprocess import check_call class Executor(object): """ Log and execute shell commands. @param dryRun: If C{...
from __future__ import division, print_function import six from time import time, ctime from subprocess import PIPE, CalledProcessError if six.PY3: from subprocess import run else: from subprocess import check_call class Executor(object): """ Log and execute shell commands. @param dryRun: If C{...
en
null
1,134
0025578.py
#!/usr/bin/env python3 # license removed for brevity #策略 機械手臂 四點來回跑 import rospy import os import numpy as np from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * import math import enum import Hiwin_RT605_ROS as strategy pos_feedback_times = 0 mode_feedback_times = 0 msg_feedback ...
#!/usr/bin/env python3 # license removed for brevity #策略 機械手臂 四點來回跑 import rospy import os import numpy as np from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * import math import enum import Hiwin_RT605_ROS as strategy pos_feedback_times = 0 mode_feedback_times = 0 msg_feedback ...
en
null
2,946
0040307.py
"""Create annotation table Revision ID: 4c0c44605c09 Revises: 4886d7a14074 Create Date: 2016-01-20 12:58:16.249481 """ # revision identifiers, used by Alembic. revision = "4c0c44605c09" down_revision = "21f87f395e26" import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql from h.d...
"""Create annotation table Revision ID: 4c0c44605c09 Revises: 4886d7a14074 Create Date: 2016-01-20 12:58:16.249481 """ # revision identifiers, used by Alembic. revision = "4c0c44605c09" down_revision = "21f87f395e26" import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql from h.d...
en
null
783
0028654.py
from Usina import Usina; from RecebeDados import RecebeDados; class Termica(Usina): def __init__(self, recebe_dados, abaTerm, offset, iTerm, nMeses, nMesesPos, continuidade=False): # define fonte_dados como o objeto da classe RecebeDados e o nome da aba com as usinas UHE self.nomeAba ...
from Usina import Usina; from RecebeDados import RecebeDados; class Termica(Usina): def __init__(self, recebe_dados, abaTerm, offset, iTerm, nMeses, nMesesPos, continuidade=False): # define fonte_dados como o objeto da classe RecebeDados e o nome da aba com as usinas UHE self.nomeAba ...
en
null
1,102
0006800.py
# # 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, software # ...
# # 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, software # ...
en
null
2,071
0044671.py
# -*- coding: UTF8 -*- # vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 foldmethod=marker: # import json # 本地 db 规则: # # /data/group_name/node_id/database_name/table_name/partition_id/ # /source_data/base/database_name/table_name/partition_id/version # /source_data/delta/database_name/table_name/partition_id...
# -*- coding: UTF8 -*- # vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 foldmethod=marker: # import json # 本地 db 规则: # # /data/group_name/node_id/database_name/table_name/partition_id/ # /source_data/base/database_name/table_name/partition_id/version # /source_data/delta/database_name/table_name/partition_id...
en
null
525
0018812.py
#!/usr/bin/env python #from:http://www.wooyun.org/bugs/wooyun-2010-093049 import re,time def assign(service, arg): if service == "umail": return True, arg def audit(arg): url = arg + '/webmail/fast/index.php?module=operate&action=login' postdata = 'mailbox=test@domain.com&link=?' ...
#!/usr/bin/env python #from:http://www.wooyun.org/bugs/wooyun-2010-093049 import re,time def assign(service, arg): if service == "umail": return True, arg def audit(arg): url = arg + '/webmail/fast/index.php?module=operate&action=login' postdata = 'mailbox=test@domain.com&link=?' ...
en
null
260
0010539.py
# project/tasks/sample_tasks.py import time from celery import shared_task @shared_task def send_email(email_id, message): time.sleep(10) print(f"Email is sent to {email_id}. Message sent was - {message}") @shared_task def get_micro_app_status(app): print(f"La micro app {app}. est UP") @shared_task ...
# project/tasks/sample_tasks.py import time from celery import shared_task @shared_task def send_email(email_id, message): time.sleep(10) print(f"Email is sent to {email_id}. Message sent was - {message}") @shared_task def get_micro_app_status(app): print(f"La micro app {app}. est UP") @shared_task ...
en
null
156
0022287.py
from typing import Tuple from context import Context class SimpleFramebuffer: def __init__(self, size: Tuple[int, int]): ctx = Context.context self.image = ctx.image(size, 'rgba8unorm') self.depth = ctx.image(size, 'depth24plus') self.framebuffer = [self.image, self.depth] de...
from typing import Tuple from context import Context class SimpleFramebuffer: def __init__(self, size: Tuple[int, int]): ctx = Context.context self.image = ctx.image(size, 'rgba8unorm') self.depth = ctx.image(size, 'depth24plus') self.framebuffer = [self.image, self.depth] de...
en
null
152
0037921.py
# Copyright (c) 2021 Teradici Corporation # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import requests import retry from retry import retry class CASManager: def __init__(self, auth_token, url='https://cas.teradici.com'): se...
# Copyright (c) 2021 Teradici Corporation # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import requests import retry from retry import retry class CASManager: def __init__(self, auth_token, url='https://cas.teradici.com'): se...
en
null
1,542
0023901.py
import sys import mock from iml_common.test.command_capture_testcase import ( CommandCaptureTestCase, CommandCaptureCommand, ) from iml_common.lib.firewall_control import FirewallControlEL7 from iml_common.lib.service_control import ServiceControlEL7 from iml_common.lib.agent_rpc import agent_result_ok class...
import sys import mock from iml_common.test.command_capture_testcase import ( CommandCaptureTestCase, CommandCaptureCommand, ) from iml_common.lib.firewall_control import FirewallControlEL7 from iml_common.lib.service_control import ServiceControlEL7 from iml_common.lib.agent_rpc import agent_result_ok class...
en
null
5,185
0047623.py
from typing import Dict class Average: """Implements a simple running average counter.""" def __init__(self): self.total = 0 self.n_steps = 0 def update(self, value: float) -> None: self.total += value self.n_steps += 1 def compute(self) -> float: return self....
from typing import Dict class Average: """Implements a simple running average counter.""" def __init__(self): self.total = 0 self.n_steps = 0 def update(self, value: float) -> None: self.total += value self.n_steps += 1 def compute(self) -> float: return self....
en
null
255
0046681.py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
en
null
3,524
0015982.py
from abc import ABC, abstractmethod from contextlib import contextmanager import socket import time from lightlab import visalogger as logger from rvisa.util import from_ascii_block class InstrumentSessionBase(ABC): ''' Base class for Instrument sessions, to be inherited and specialized by VISAObject and Prol...
from abc import ABC, abstractmethod from contextlib import contextmanager import socket import time from lightlab import visalogger as logger from rvisa.util import from_ascii_block class InstrumentSessionBase(ABC): ''' Base class for Instrument sessions, to be inherited and specialized by VISAObject and Prol...
en
null
1,555
0007024.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class CarhomeItem(scrapy.Item): # define the fields for your item here like: car_name = scrapy.Field() car_url = scrapy.Field() # 车辆评分...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class CarhomeItem(scrapy.Item): # define the fields for your item here like: car_name = scrapy.Field() car_url = scrapy.Field() # 车辆评分...
en
null
192
0000166.py
#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
en
null
3,327
0030317.py
# Copyright (c) 2020 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 required by appli...
# Copyright (c) 2020 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 required by appli...
en
null
5,926
0015091.py
#-*- coding: utf-8 -*- # pysqlite2/dbapi.py: pysqlite DB-API module # # Copyright (C) 2007-2008 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from...
#-*- coding: utf-8 -*- # pysqlite2/dbapi.py: pysqlite DB-API module # # Copyright (C) 2007-2008 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from...
en
null
3,265
0040934.py
import json from copy import deepcopy from hashlib import sha256 from plenum.common.constants import TARGET_NYM, NONCE, RAW, ENC, HASH, NAME, \ VERSION, FORCE, ORIGIN, OPERATION_SCHEMA_IS_STRICT, OP_VER from plenum.common.messages.client_request import ClientMessageValidator as PClientMessageValidator from plenum....
import json from copy import deepcopy from hashlib import sha256 from plenum.common.constants import TARGET_NYM, NONCE, RAW, ENC, HASH, NAME, \ VERSION, FORCE, ORIGIN, OPERATION_SCHEMA_IS_STRICT, OP_VER from plenum.common.messages.client_request import ClientMessageValidator as PClientMessageValidator from plenum....
en
null
6,253
0010393.py
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import argparse import logging import math import os import time import warnings from benchmark_dataset import BenchmarkLMDataset, collate_sentences_lm import torch from torch.distributed import rpc import torch.multiprocessing as mp import torch...
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import argparse import logging import math import os import time import warnings from benchmark_dataset import BenchmarkLMDataset, collate_sentences_lm import torch from torch.distributed import rpc import torch.multiprocessing as mp import torch...
en
null
7,777
0027797.py
#!/usr/bin/env python """ Spectral features summarized over time using mean and variance. Returns a 22-dimension feature vector for each audio sample. Features: - Spectral Centroid - Spectral Bandwidth - Spectral Contrast (7 frequency bands) - Spectral Flatness - Spectral Rolloff """ import numpy ...
#!/usr/bin/env python """ Spectral features summarized over time using mean and variance. Returns a 22-dimension feature vector for each audio sample. Features: - Spectral Centroid - Spectral Bandwidth - Spectral Contrast (7 frequency bands) - Spectral Flatness - Spectral Rolloff """ import numpy ...
en
null
1,043
0026340.py
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python Libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.mock import ( MagicMock, patch, NO_MOCK, NO_MOCK_REASON ) fr...
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python Libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.mock import ( MagicMock, patch, NO_MOCK, NO_MOCK_REASON ) fr...
en
null
843
0049078.py
from flask_login import UserMixin class User(UserMixin): def __init__(self, id_, name, password, roles,rid): self.id = id_ self.rid = rid self.name = name self.password = password self.roles = roles def has_role(self, role): return role in self.roles
from flask_login import UserMixin class User(UserMixin): def __init__(self, id_, name, password, roles,rid): self.id = id_ self.rid = rid self.name = name self.password = password self.roles = roles def has_role(self, role): return role in self.roles
en
null
90
0000780.py
# coding: utf-8 """ ThinVolumeReinitializeDescriptor.py The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following con...
# coding: utf-8 """ ThinVolumeReinitializeDescriptor.py The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following con...
en
null
1,379
0006472.py
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # # Ported for Lord-Userbot By liualvinas/Alvin from telethon import events from userbot import CMD_HANDLER as cmd from...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # # Ported for Lord-Userbot By liualvinas/Alvin from telethon import events from userbot import CMD_HANDLER as cmd from...
en
null
413
0041487.py
# Definition of the class structures in file imas.py import imas import numpy import sys import os ''' This sample program will create a pulse file (shot 13, run 1) and will put an example of equilibirium IDS using put_slice methods. ''' # This routine reads an array of pfsystems IDSs in the database, filling # some ...
# Definition of the class structures in file imas.py import imas import numpy import sys import os ''' This sample program will create a pulse file (shot 13, run 1) and will put an example of equilibirium IDS using put_slice methods. ''' # This routine reads an array of pfsystems IDSs in the database, filling # some ...
en
null
1,654
0025258.py
# noqa D100 import sys import mock def _setup(): global bh1745 from tools import SMBusFakeDeviceNoTimeout smbus = mock.Mock() smbus.SMBus = SMBusFakeDeviceNoTimeout sys.modules['smbus'] = smbus from bh1745 import BH1745 bh1745 = BH1745() def test_set_adc_gain_x(): """Test setting adc...
# noqa D100 import sys import mock def _setup(): global bh1745 from tools import SMBusFakeDeviceNoTimeout smbus = mock.Mock() smbus.SMBus = SMBusFakeDeviceNoTimeout sys.modules['smbus'] = smbus from bh1745 import BH1745 bh1745 = BH1745() def test_set_adc_gain_x(): """Test setting adc...
en
null
1,000
0049811.py
## @package Labelling_app # Labelling app software developed with Grabcut # # @version 1 # # Pontificia Universidad Javeriana # # Electronic Enginnering # # Developed by: # - Andrea Juliana Ruiz Gomez # Mail: <andrea_ruiz@javeriana.edu.co> # GitHub: andrearuizg # - Pedro Eli Ruiz Zarate # Mail: <...
## @package Labelling_app # Labelling app software developed with Grabcut # # @version 1 # # Pontificia Universidad Javeriana # # Electronic Enginnering # # Developed by: # - Andrea Juliana Ruiz Gomez # Mail: <andrea_ruiz@javeriana.edu.co> # GitHub: andrearuizg # - Pedro Eli Ruiz Zarate # Mail: <...
en
null
8,739
0012742.py
import threading import numpy as np import torch import os.path as osp from rl.utils import mpi_utils #Replay buffer!!! def sample_her_transitions(buffer, reward_func, batch_size, future_step, future_p=1.0): assert all(k in buffer for k in ['ob', 'ag', 'bg', 'a']) buffer['o2'] = buffer['ob'][:, 1:, :] bu...
import threading import numpy as np import torch import os.path as osp from rl.utils import mpi_utils #Replay buffer!!! def sample_her_transitions(buffer, reward_func, batch_size, future_step, future_p=1.0): assert all(k in buffer for k in ['ob', 'ag', 'bg', 'a']) buffer['o2'] = buffer['ob'][:, 1:, :] bu...
en
null
1,847
0037266.py
import logging from great_expectations.exceptions import InvalidKeyError logger = logging.getLogger(__name__) from ...core.id_dict import BatchKwargs from .renderer import Renderer class SlackRenderer(Renderer): def __init__(self): super().__init__() def render( self, validation_result=Non...
import logging from great_expectations.exceptions import InvalidKeyError logger = logging.getLogger(__name__) from ...core.id_dict import BatchKwargs from .renderer import Renderer class SlackRenderer(Renderer): def __init__(self): super().__init__() def render( self, validation_result=Non...
en
null
1,662
0024056.py
# Copyright 2022 highstreet technologies GmbH # # 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 agree...
# Copyright 2022 highstreet technologies GmbH # # 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 agree...
en
null
356
0000778.py
import utility import static_sim_functions as smf import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import * from time_series_grp import TimeSeriesGroupProcessing from RandomNeighbors import RandomNeighbors from sklearn.neighbors import NearestNeighbors from sklearn.model_sele...
import utility import static_sim_functions as smf import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import * from time_series_grp import TimeSeriesGroupProcessing from RandomNeighbors import RandomNeighbors from sklearn.neighbors import NearestNeighbors from sklearn.model_sele...
en
null
8,816
0045257.py
import pytest from icevision.all import * @pytest.fixture(scope="session") def fake_faster_rcnn_model(): class FakeFasterRCNNModel(nn.Module): def __init__(self): super().__init__() # hack for the function `model_device` to work self.layer = nn.Linear(1, 1) def...
import pytest from icevision.all import * @pytest.fixture(scope="session") def fake_faster_rcnn_model(): class FakeFasterRCNNModel(nn.Module): def __init__(self): super().__init__() # hack for the function `model_device` to work self.layer = nn.Linear(1, 1) def...
en
null
966
0040836.py
class Node: def __init__(self, key): self.left = None self.right = None self.val = key # Traverse preorder def traversePreOrder(self): print(self.val, end=' ') if self.left: self.left.traversePreOrder() if self.right: self.right.traver...
class Node: def __init__(self, key): self.left = None self.right = None self.val = key # Traverse preorder def traversePreOrder(self): print(self.val, end=' ') if self.left: self.left.traversePreOrder() if self.right: self.right.traver...
en
null
328
0043605.py
"""Updates dashboard tables""" import argparse import datetime import logging import os import pandas as pd import synapseclient from synapseclient.core.utils import to_unix_epoch_time from genie import process_functions logger = logging.getLogger(__name__) def get_center_data_completion(center, df): """ G...
"""Updates dashboard tables""" import argparse import datetime import logging import os import pandas as pd import synapseclient from synapseclient.core.utils import to_unix_epoch_time from genie import process_functions logger = logging.getLogger(__name__) def get_center_data_completion(center, df): """ G...
en
null
9,541
0018823.py
import torch import torch.nn as nn import torch.nn.functional as F from horch.common import tuplify from horch.models.block import mb_conv_block, MBConv from horch.models.detection.nasfpn import ReLUConvBN from horch.models.modules import upsample_add, Conv2d, Sequential, Pool2d, upsample_concat from horch.models.dete...
import torch import torch.nn as nn import torch.nn.functional as F from horch.common import tuplify from horch.models.block import mb_conv_block, MBConv from horch.models.detection.nasfpn import ReLUConvBN from horch.models.modules import upsample_add, Conv2d, Sequential, Pool2d, upsample_concat from horch.models.dete...
en
null
4,899
0011967.py
import requests, csv, sys, os, time, json, codecs server = "https://cloudrf.com" # dir = "calculations/antennas_1W_2m" # Open CSV file import codecs # csvfile = csv.reader(codecs.open('antennas.csv', 'rU', 'utf-16')) uid = 'YOUR CLOUDRF UID HERE' key = 'YOUR CLOUDRF KEY HERE' def calc_area(dir,csv...
import requests, csv, sys, os, time, json, codecs server = "https://cloudrf.com" # dir = "calculations/antennas_1W_2m" # Open CSV file import codecs # csvfile = csv.reader(codecs.open('antennas.csv', 'rU', 'utf-16')) uid = 'YOUR CLOUDRF UID HERE' key = 'YOUR CLOUDRF KEY HERE' def calc_area(dir,csv...
en
null
398
0046715.py
from ..bright import doimaker __author__ = "Gareth Murphy" __credits__ = ["Gareth Murphy"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Gareth Murphy" __email__ = "garethcmurphy@gmail.com" __status__ = "Development" def test_doi(): bright = doimaker.DOIMaker() assert isinstance(bright.passw, s...
from ..bright import doimaker __author__ = "Gareth Murphy" __credits__ = ["Gareth Murphy"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Gareth Murphy" __email__ = "garethcmurphy@gmail.com" __status__ = "Development" def test_doi(): bright = doimaker.DOIMaker() assert isinstance(bright.passw, s...
en
null
129
0004345.py
#!opt/python-3.6/bin/python3 import unittest import sys sys.path.append("../src") from info_ordering import order_info class TestInfoOrdering(unittest.TestCase): def test_order_info(self): # TODO: fix to actually test value = 5 self.assertEqual(value, 5) if __name__ == '__main__': uni...
#!opt/python-3.6/bin/python3 import unittest import sys sys.path.append("../src") from info_ordering import order_info class TestInfoOrdering(unittest.TestCase): def test_order_info(self): # TODO: fix to actually test value = 5 self.assertEqual(value, 5) if __name__ == '__main__': uni...
en
null
113
0016785.py
# # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more in...
# # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more in...
en
null
2,821
0022773.py
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyNbformat(PythonPackage): """The Jupyter Notebook format""" homepage = "https://gith...
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyNbformat(PythonPackage): """The Jupyter Notebook format""" homepage = "https://gith...
en
null
339
0015560.py
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # # ReCode by @mrismanaziz # FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot> # t.me/SharingUserbot & t.me/L...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # # ReCode by @mrismanaziz # FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot> # t.me/SharingUserbot & t.me/L...
en
null
3,798
0028938.py
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/booster/shared_bst_koensayr_racer_mk2.iff" result.a...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/booster/shared_bst_koensayr_racer_mk2.iff" result.a...
en
null
165
0030589.py
from conan_tests.test_regression.utils.base_exe import BaseExeTest, run, conan_create_command class Bzip2Test(BaseExeTest): libref = "bzip2/1.0.6@conan/stable" librepo = "https://github.com/lasote/conan-bzip2.git" branch = "release/1.0.6" def setUp(self): super(Bzip2Test, self).setUp() ...
from conan_tests.test_regression.utils.base_exe import BaseExeTest, run, conan_create_command class Bzip2Test(BaseExeTest): libref = "bzip2/1.0.6@conan/stable" librepo = "https://github.com/lasote/conan-bzip2.git" branch = "release/1.0.6" def setUp(self): super(Bzip2Test, self).setUp() ...
en
null
253
0035495.py
import time import threading import random from queue import Queue from pool_workers import Pool # Our logic to be performed Asynchronously. def our_process(a): t = threading.current_thread() # just to semulate how mush time this logic is going to take to be done. time.sleep(random.uniform(0, 3)) print(f'{t.getN...
import time import threading import random from queue import Queue from pool_workers import Pool # Our logic to be performed Asynchronously. def our_process(a): t = threading.current_thread() # just to semulate how mush time this logic is going to take to be done. time.sleep(random.uniform(0, 3)) print(f'{t.getN...
en
null
567
0049622.py
import unittest from main import intersection_of_chars class TestIntersectionOfChars(unittest.TestCase): def test_empty(self): self.assertEqual(intersection_of_chars([]), set()) def test_one_string(self): self.assertEqual(intersection_of_chars(['abc']), set(list('abc'))) def test_many_st...
import unittest from main import intersection_of_chars class TestIntersectionOfChars(unittest.TestCase): def test_empty(self): self.assertEqual(intersection_of_chars([]), set()) def test_one_string(self): self.assertEqual(intersection_of_chars(['abc']), set(list('abc'))) def test_many_st...
en
null
153
0045438.py
# Copyright (c) ZenML GmbH 2021. 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...
# Copyright (c) ZenML GmbH 2021. 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...
en
null
576
0007335.py
'''Some helper functions for PyTorch, including: - get_mean_and_std: calculate the mean and std value of dataset. - msr_init: net parameter initialization. - progress_bar: progress bar mimic xlua.progress. ''' import os import sys import time import math import torch import torch.nn as nn impor...
'''Some helper functions for PyTorch, including: - get_mean_and_std: calculate the mean and std value of dataset. - msr_init: net parameter initialization. - progress_bar: progress bar mimic xlua.progress. ''' import os import sys import time import math import torch import torch.nn as nn impor...
en
null
1,630
0044535.py
#!/usr/bin/python DOCUMENTATION = ''' module: bgp_facts version_added: "2.0" author: John Arnold (johnar@microsoft.com) short_description: Retrieve BGP neighbor information from Quagga description: - Retrieve BGP neighbor information from Quagga, using the VTYSH command line - Retrieved facts ...
#!/usr/bin/python DOCUMENTATION = ''' module: bgp_facts version_added: "2.0" author: John Arnold (johnar@microsoft.com) short_description: Retrieve BGP neighbor information from Quagga description: - Retrieve BGP neighbor information from Quagga, using the VTYSH command line - Retrieved facts ...
en
null
1,921
0026025.py
import numpy as np import scipy.interpolate from .. import distributions as D np.random.seed(1) def sampltest(distr, left=None, right=None, bounds=None): # check that mean and stddev from the generated sample # match what we get from integrating the PDF def FF1(x): return distr.pdf(x) * x d...
import numpy as np import scipy.interpolate from .. import distributions as D np.random.seed(1) def sampltest(distr, left=None, right=None, bounds=None): # check that mean and stddev from the generated sample # match what we get from integrating the PDF def FF1(x): return distr.pdf(x) * x d...
en
null
2,402
0049815.py
""" Copyright 2015 Hewlett-Packard 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, softwar...
""" Copyright 2015 Hewlett-Packard 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, softwar...
en
null
3,728
0034607.py
#!/usr/bin/env python3 # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. from basecls.configs import HRNetConfig _cfg = dict( model=dict( name="hrnet_w64", ), ) class Cfg(HRNetConfig): def __init__(self, values_or_file=None, **kwargs): super().__init__(_cfg) self.merge(va...
#!/usr/bin/env python3 # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. from basecls.configs import HRNetConfig _cfg = dict( model=dict( name="hrnet_w64", ), ) class Cfg(HRNetConfig): def __init__(self, values_or_file=None, **kwargs): super().__init__(_cfg) self.merge(va...
en
null
130
0015350.py
#!/usr/bin/python import random from Crypto.Util import number from functools import reduce TOTAL = 15 THRESHOLD = 10 MAX_COELACANTH = 9 NUM_LOCKS = 5 NUM_TRIES = 250 # substitute for math.prod prod = lambda n: reduce(lambda x, y: x*y, n) def create_key(t, n, size=8): while True: seq = sorted([number.ge...
#!/usr/bin/python import random from Crypto.Util import number from functools import reduce TOTAL = 15 THRESHOLD = 10 MAX_COELACANTH = 9 NUM_LOCKS = 5 NUM_TRIES = 250 # substitute for math.prod prod = lambda n: reduce(lambda x, y: x*y, n) def create_key(t, n, size=8): while True: seq = sorted([number.ge...
en
null
880
0022573.py
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
en
null
1,517
0033697.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import random import argparse import matplotlib.pyplot as plt import pandas as pd from datetime import datetime import ray from ray.tune import run, sample_from from ray.tune.schedulers import Popu...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import random import argparse import matplotlib.pyplot as plt import pandas as pd from datetime import datetime import ray from ray.tune import run, sample_from from ray.tune.schedulers import Popu...
en
null
1,979
0006164.py
from datetime import datetime import datetime def yesterday(today=datetime.datetime.now()): yesterday = today - datetime.timedelta(days=1) yesterday_timestamp = int(yesterday.timestamp()) * 1000 return yesterday_timestamp def extractDate(name, prefix, fileType): prefixLen = len(prefix) fileTypeL...
from datetime import datetime import datetime def yesterday(today=datetime.datetime.now()): yesterday = today - datetime.timedelta(days=1) yesterday_timestamp = int(yesterday.timestamp()) * 1000 return yesterday_timestamp def extractDate(name, prefix, fileType): prefixLen = len(prefix) fileTypeL...
en
null
109
0034392.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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.apac...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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.apac...
en
null
934