text stringlengths 1 927k |
|---|
import xml.etree.ElementTree as et
import logging
import gzip
import urllib.request
from urllib.error import HTTPError, URLError
from socket import timeout
from scout.constants import CHROMOSOMES
from scout.utils.ensembl_rest_clients import EnsemblBiomartClient
LOG = logging.getLogger(__name__)
HPO_URL = (
"http... |
def main(request, response):
ua = request.headers.get('sec-ch-ua', '')
response.headers.set("Content-Type", "text/html")
response.headers.set("Accept-CH", "UA")
response.headers.set("Accept-CH-Lifetime", "10")
response.content = '''
<script>
window.opener.postMessage({ header: '%s' }, "*");
</scri... |
import json
import requests
import sys
import datetime
unix_epoch = datetime.datetime(1970, 1, 1)
BASE_API_URL = "https://api.pushshift.io"
SUBMISSION_API_URL = "/reddit/search/submission/"
COMMENT_API_URL = "/reddit/search/comment/"
def search_subs_reddit(**kwargs):
request = requests.get(BASE_API_U... |
import matplotlib as mpl
import matplotlib.pyplot as plt
from PIL import Image
def gen_frame(path):
"""
Input: path to image
Generates the single frame of a gif from an image
"""
im = Image.open(path)
alpha = im.getchannel('A')
# Convert the image into P mode but only use 255 colors in the... |
import pprint
import sys
sys.ps1 = "\033[0;34m>>> \033[0m"
sys.ps2 = "\033[1;34m... \033[0m"
sys.displayhook = pprint.pprint |
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from six.moves import cPickle
import unet
import simplified_unet
arg_scope = tf.contrib.framework.arg_scope
class UnetModel(object):
def __init__(self, number_class=3, is_training=True, is_simplified = False, dropout = True):
""... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import six
from hestia.cached_property import cached_property
from polyaxon_schemas.exceptions import PolyaxonConfigurationError
from polyaxon_schemas.ops.experiment.environment import ExperimentEnvironmentConfig
from polyaxon_s... |
HOME = '/'
SETUP = '/setup/<browser>'
SETUP_ONLY = '/setup/'
COMMANDS = '/commands'
PICK_COMMANDS = '/pick_commands'
EDIT_COMMAND = '/edit_command/<command_name>'
EDIT_COMMAND_ONLY = '/edit_command/'
NEW_COMMAND = '/new_command/<command_name>'
NEW_... |
t=()
for i in range(3):
mark1=int(input('enter the marks of first subject :'))
mark2=int(input('enter the marks of 2 subject :'))
mark3=int(input('enter the marks of 3 subject :'))
mark=(mark1,mark2,mark3)
t=t+(mark,)
print(t) |
"""
.. module:: experimental_design
:synopsis: Methods for generating an experimental design.
.. moduleauthor:: David Eriksson <dme65@cornell.edu>,
Yi Shen <ys623@cornell.edu>
:Module: experimental_design
:Author: David Eriksson <dme65@cornell.edu>
Yi Shen <ys623@cornell.edu>
"""
import nu... |
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.optim import lr_scheduler
def get_norm_layer(norm_type='instance'):
if norm_type == 'batch':
norm_layer = functools.partial(nn.BatchNorm2d, affine=True)
elif norm_type == 'instance':
norm_layer = functools... |
strN = input("Please enter a number:")
N = int(strN)
#N = 10
total = 0
for current in range(N+1):
total = total + current
print("summation 1..",N,"is",total) |
VERSION = '0.20' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import the necessary packages
from collections import deque
import numpy as np
import argparse
import imutils
import cv2
import time
import pandas as pd
import matplotlib.pyplot as plt
import RPi.GPIO as GPIO
# construct the argument parse and parse the arguments
ap = ... |
def getBestBloker(si, gat):
global relations
for g in gat:
if g in relations[si]:
return [si, g]
for g in gat:
if len(relations[g]) > 0:
return [g, relations[g][0]]
return [0, 0]
def unsetter(c1, c2):
global relations
relations[c1].remove(c2)
relatio... |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... |
"""
This file offers the methods to automatically retrieve the graph Paenibacillus sp. 32O-W.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protei... |
# Copyright (c) 2022 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... |
"""Birds Basement Spider Entrypoint."""
from typing import Generator
from scrape_from_the_ape.items import ScrapeFromTheApeItem
from scrape_from_the_ape.utils.birds_basement_helpers import birds_parser
import scrapy
class BirdsBasementSpider(scrapy.Spider):
"""Birds Basement Spider.
Args:
scrapy (... |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass
from datetime import datetime
from gql.gql.datetime_utils import DATETIME_FIELD
from gql.gql.graphql_client import GraphqlClient
from functools import partial
from numbers import Number
from typing import Any, Call... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test p2p mempool message.
Test that nodes are disconnected if they send mempool messages when bloom
fi... |
import functools
import logging
import time
import pika
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
LOGGER = logging.getLogger(__name__)
class Dlx:
def __init__(self, _parameters):
self._parameters = _parameters
self._... |
from torch2trt.torch2trt import *
from torch2trt.module_test import add_module_test
@tensorrt_converter('torch.nn.BatchNorm1d.forward')
def convert_BatchNorm1d(ctx):
module = ctx.method_args[0]
input = ctx.method_args[1]
input_trt = trt_(ctx.network, input)
output = ctx.method_return
scale =... |
"""Test helper functions."""
from adaptavist.const import STATUS_BLOCKED, STATUS_FAIL, STATUS_IN_PROGRESS, STATUS_NOT_EXECUTED, STATUS_PASS
from bs4 import BeautifulSoup
from pytest_adaptavist._helpers import calc_test_result_status, html_row
class TestHelpersUnit:
"""Test helper functions on unit test level.""... |
"""
This file offers the methods to automatically retrieve the graph Elephantulus edwardii.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein ... |
"""Module/script to byte-compile all .py files to .pyc files.
When called as a script with arguments, this compiles the directories
given as arguments recursively; the -l option prevents it from
recursing into directories.
Without arguments, if compiles all modules on sys.path, without
recursing into subdirectories. ... |
import numpy as np
def fitness_functions_continuous(function_number):
if function_number == 1:
return lambda chromosome: -(np.abs(chromosome[0]) + np.cos(chromosome[0]))
elif function_number == 2:
return lambda chromosome: -(np.abs(chromosome[0]) + np.sin(chromosome[0]))
elif function_num... |
"""Linky generic test utils."""
from unittest.mock import patch
import pytest
@pytest.fixture(autouse=True)
def patch_fakeuseragent():
"""Stub out fake useragent dep that makes requests."""
with patch("pylinky.client.UserAgent", return_value="Test Browser"):
yield |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
"""Default REST view for Grok.
The views provided by this module get invoked when an object receives an
HTTP request in a REST skin for which no more-specific REST behavior has
been defined. These all return the HTTP response Method Not Allowed.
"""
import grokcore.component as grok
import grokcore.rest
import grokc... |
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
from PythonUtils.live_info.emaillist import EmailList
from PythonUtils.live_info.display_item import DisplayItem
from pathlib import Path
import base64
class EmailInfo(DisplayItem):
de... |
import unittest.mock
from programy.parser.pattern.nodes.base import MultiValueDict
class MultiValueDictTests(unittest.TestCase):
def test_add_remove(self):
multidict = MultiValueDict()
multidict["name"] = "value1"
multidict["name"].append("value2")
self.assertTrue("name" in mult... |
# -*- test-case-name: twisted.test.test_reflect -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Standardized versions of various cool and/or strange things that you can do
with Python's reflection capabilities.
"""
from __future__ import division, absolute_import, print_function
impor... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Dequan Wang and Xingyi Zhou
# ------------------------------------------------------------------------------
from __f... |
import pytest
from django.conf import settings
from django.test import RequestFactory
from employee_management_backend.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> settings.AUTH_USE... |
import lldb
import re
# USAGE
#
# EITHER (automatic)
# Run the setup_iplug_lldb_xcode.sh script that sits alongside this one to add this to the lldb import paths
# OR (manually) Put this line in your ~/.lldbinit file:
# command script import [path]
# Where [path] is the full path to this file. For example:
# command... |
# -*- coding:utf-8 -*-
import datetime
import logging.config
import os
import time
from flask import Flask, send_from_directory, g, request, Response, Blueprint
from flask_restplus import Api, Namespace
from werkzeug.exceptions import default_exceptions, HTTPException
from werkzeug.utils import find_modules, import_st... |
import discord
from Config._functions import grammar_list
from Config._const import DB_LINK
from datetime import datetime, timedelta
from Config._db import Database
from Config._servers import MAIN_SERVER
class EVENT:
db = Database()
# Executes when loaded
def __init__(self):
self.RUNNING = False
self.param = ... |
#!/usr/bin/python
#
# Show the main interfaces of the three sensor classes
#
#
from time import sleep
import redis
from altimu.lsm6ds33 import LSM6DS33
from altimu.lis3mdl import LIS3MDL
from altimu.lps25h import LPS25H
from datetime import datetime
imu = LSM6DS33() # Accelerometer and Gyroscope
imu.enable(... |
from django.http import HttpResponse
from django.shortcuts import render,render_to_response, get_object_or_404,redirect
from .models import *
from reviews.models import Review , Review_Comment
from django.template import RequestContext
from django.contrib.auth import login, authenticate, logout
from django.contrib.aut... |
"""List server credentials."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer import exceptions
@click.command(cls=SoftLayer.CLI.command.SLCommand, )
@click.argum... |
from flask_wtf import FlaskForm as Form
from ..models import User, Organization
# from wtforms import StringField, SubmitField
from wtforms.fields import (
StringField,
IntegerField,
SelectField,
SubmitField,
DateTimeField,
BooleanField,
PasswordField,
)
from wtforms import ValidationError
f... |
#!/usr/bin/env python3
import argparse
import atexit
import datetime
import functools
import json
import os
import os.path
import re
import shutil
import sys
import time
import traceback
import uuid
import psutil
import tornado.httpserver
import tornado.ioloop
import tornado.web
from blindbackup import util
from torn... |
import artist
import track_encrypt
import ipfshttpclient
import os
import json
from umbral.keys import UmbralPrivateKey, UmbralPublicKey
from flask import Flask, request, Response, jsonify
from flask_cors import CORS
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = './uploads'
CORS(app)
api = ipfshttpclient.connec... |
from flask import Flask, render_template, request, redirect
import youtube_dl
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/download', methods=["POST", "GET"])
def download():
url = request... |
# Hope to move all the API here |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from pyocser import ocdumps
from pyocser import ocloads
import sys
try :
import numpy
#print '** importing NUMPY arrays'
import numpy_test
except :
#print " ... but can't import numpy ..."
numpy = None
numpy_test = None
try :
import Numeric
#print "** importing NUMERIC arrays"
except :... |
from threading import stack_size
from ximea import xiapi
from imutils.video import FPS
import cv2
import numpy as np
import time
import multiprocessing
from multiprocessing import Pool, Queue
import sys,os
import pickle
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import leastsq
from numba impo... |
#!/usr/bin/env python3
import os
import exinfo
import time
exinfopath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
extpkl = os.path.join(exinfopath, "exinfo.pkl")
exinfo.init()
exinfo.test_query("8.8.8.8", "")
time.sleep(10) |
from sigfeat import Extractor
from sigfeat import feature as fts
extractor = Extractor(
fts.SpectralFlux(),
fts.SpectralCentroid(),
fts.SpectralFlatness(),
fts.SpectralRolloff(),
fts.SpectralCrestFactor(),
fts.CrestFactor(),
fts.ZeroCrossingRate(),
fts.RootMeanSquare(),
fts.Peak(),... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
"""
This file offers the methods to automatically retrieve the graph soc-slashdot.
The graph is automatically retrieved from the NetworkRepository repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 202... |
"""
A striplog is a sequence of intervals.
:copyright: 2019 Agile Geoscience
:license: Apache 2.0
"""
import re
from io import StringIO
import csv
import operator
import warnings
from collections import defaultdict
from collections import OrderedDict
from functools import reduce
from copy import deepcopy
import numpy... |
"""
Simplest plugin that exercises all the hooks
"""
from tljh.hooks import hookimpl
@hookimpl
def tljh_extra_user_conda_packages():
return [
'hypothesis',
]
@hookimpl
def tljh_extra_user_pip_packages():
return [
'django',
]
@hookimpl
def tljh_extra_hub_pip_packages():
return [
... |
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))
import spreading_dye_sampler.dye_blot
import numpy as np
from numpy.random import random
import pytest
@pytest.fixture
def blot():
num_cells = 100
grid_width = 100
grid_height = 100
blot = None
while blot i... |
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys
sys.path.append('../')
from niapy.task import StoppingTask, OptimizationType
from niapy.benchmarks import Benchmark
from niapy.algorithms.basic import GreyWolfOptimizer
from nu... |
#!/usr/bin/env python
import rospy
import time
from mindwave_driver.bluetooth_headset import BluetoothHeadset
from mindwave_driver.common import *
# 20:68:9D:70:CA:96
headset = BluetoothHeadset("20:68:9D:70:CA:96")
#headset = BluetoothHeadset()
#headset.echo_raw()
#headset.read()
while True:
if headset.status !... |
import bisect
import csv
import os
import sys
import traceback
import matplotlib
matplotlib.use('Agg') # noqa
from matplotlib import pyplot
# Data outputs
DETAILS = 'D'
MATCHED_PAIRS = 'MP'
ORPHANS = 'O'
# Data output formats
GFF_EXT = 'gff'
TABULAR_EXT = 'tabular'
# Statistics historgrams output directory.
HISTOGRA... |
#!/usr/bin/env python3
#
# file: main.py
# author: Michael Brockus
# gmail: <michaelbrockus@gmail.com>
#
import sys
def main():
n = int(input())
s = str()
for it in range(n):
s += str(it + 1)
print(s)
if __name__ == '__main__':
sys.exit(main()) |
# Copyright 2020 The PyMC Developers
#
# 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 ag... |
import pympi
from convertextract.parsers.utils import BaseParser
class Parser(BaseParser):
"""Extract text from ELAN file using pympi-ling.
"""
def extract(self, filename, **kwargs):
if 'mapping' in kwargs and kwargs['mapping']:
transducer = self.create_transducer(kwargs['mapping'])
... |
from keras.layers import Input, Conv1D, Embedding, Flatten, Dense, Reshape, Lambda, Activation, Dropout
from keras.models import Model
from keras import objectives, backend as K
from keras.optimizers import Adam
class VAE(object):
def create(self, nchars, max_length, kernels, filters,
embedding_dim... |
# -*- coding: utf-8 -*-
import numpy as np
# from tqdm import tqdm
import torch
from torch import nn
from ctp.util import make_batches
from ctp.models import BaseLatentFeatureModel
from typing import Tuple, Dict
def evaluate_slow(entity_embeddings: nn.Embedding,
predicate_embeddings: nn.Embeddin... |
# Copyright (C) 2021 Man-Userbot
# Created by mrismanaziz
# FROM <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/Lunatic0de
from asyncio.exceptions import TimeoutError
from telethon.errors.rpcerrorlist import YouBlockedUserError
from userbot import CMD_HELP, bot
from userbot.events import r... |
import unittest
from SimPEG import *
from SimPEG import EM
import sys
from scipy.constants import mu_0
from SimPEG.EM.Utils.testingUtils import getFDEMProblem
testEB = True
testHJ = True
verbose = False
TOL = 1e-5
FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order
CONDUCTIVITY = 1e1
MU = mu... |
# Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
#! /usr/bin/env python
# coding=utf-8
# Django
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied
from django.http.response import Http404, HttpResponse
from django.test import RequestFactory, TestCase
from django.view... |
"""Generate and work with PEP 425 Compatibility Tags."""
from __future__ import absolute_import
import distutils.util
import logging
import platform
import re
import sys
import sysconfig
import warnings
from collections import OrderedDict
from pip._vendor.six import PY2
import pip._internal.utils.glibc
from pip._int... |
"""namespace config, 'cause the c++ side doesn't do it too nicely"""
from __main__ import _pythonscriptmodule
from __main__ import _naali
import rexviewer as r #the old module is still used , while porting away from it
import sys #for stdout redirecting
#from _naali import *
# for core types like PythonQt.private.Att... |
"""
MIT License
Copyright (c) 2019 Simon Olofsson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish... |
from django.conf.urls import url, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'clases', views.GdzClasViewSet)
router.register(r'subjects', views.GdzSubjectViewSet)
router.register(r'books', views.GdzBookViewSet)
urlpatterns = [
#api endpoint
u... |
import os
PLOTLY_DIR = os.environ.get("PLOTLY_DIR",
os.path.join(os.path.expanduser("~"), ".plotly"))
TEST_FILE = os.path.join(PLOTLY_DIR, ".permission_test")
def _permissions():
try:
if not os.path.exists(PLOTLY_DIR):
try:
os.mkdir(PLOTLY_DIR)
... |
#!/usr/bin/python
import httplib2
import os
import sys
from googleapiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
import sloelib
class SloeYouTubeSession(object):
YOUTUBE_API_SERVICE... |
from __future__ import annotations
from datetime import (
date,
datetime,
time,
timedelta,
tzinfo,
)
import operator
from typing import (
TYPE_CHECKING,
Hashable,
)
import warnings
import numpy as np
from pandas._libs import (
NaT,
Period,
Timestamp,
index as libindex,
... |
#!/usr/bin/env python
import os
import struct
import zmq
import numpy as np
from opendbc import DBC_PATH
from common.realtime import Ratekeeper
from selfdrive.config import Conversions as CV
import selfdrive.messaging as messaging
from selfdrive.services import service_list
from selfdrive.car.honda.hondacan import f... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
def create_user(**params):
return get_user_model... |
# Madame Song (9390214) | San Commerci (865000000)
from net.swordie.ms.loaders import StringData
options = []
al = chr.getAvatarData().getAvatarLook()
faceColour = al.getFace() % 1000 - al.getFace() % 100
baseFace = al.getFace() - faceColour
for colour in range(0, 900, 100):
colourOption = baseFace + colour
... |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import Odometry
from uf_common.msg import PoseTwistStamped
from neural_control.nn_controller import NN_controller
from geometry_msgs.msg import PoseStamped
def odom_callback(odom_msg):
controller.give_new_state(odom_msg.pose.pose, odom_msg.twist.twist, odom_msg.hea... |
# code-checked
# server-checked
import os
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.autograd import Variable
from model_mcdropout import DepthCompletionNet
from datasets import DatasetKITTIVal
from criterion import MaskedL2Gauss, RMSE
import numpy as np
import cv2
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import requests
import re
import os
import time
from PIL import Image
def parseImageUrls(wxUrl):
rsp = requests.get(wxUrl)
imgs = re.findall(r'<p><img (.*?)></p>', rsp.text)
imgUrls = []
for img in imgs:
data_src = re.search(r'data-src="(.*?)"', i... |
import os
from datetime import timedelta
from django.core.files.uploadedfile import SimpleUploadedFile
from django.contrib.auth.models import User
from django.utils import timezone
from allauth.account.models import EmailAddress
from rest_framework.test import APITestCase, APIClient
from challenges.models import Ch... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket, sys, thread, select, json, time, struct
from time import sleep
HEARTBEAT_PORT = 8881
CONNECTION_PORT = 8882
RECV_BUFFER = 8192
class Heartbeat:
def __init__(self):
self.heartbeat_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
... |
# Copyright 2017-2018 Yelp
# Copyright 2019 Yelp
#
# 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... |
yes = "Sure , I can work with this"
no = "No thanks , I can find something better"
hate = "No way"
k = "Kampala"
m = 'Mbarara'
s = 'Space'
location = input("Enter location:")
pay = input("Enter the pay:")
try:
location = str(location)
pay = int(pay)
if location.lower() == m.lower():
if pay > 4000000... |
import numpy as np
import cv2
BUFFER_SIZE = 30
class imageGenerator:
def __init__(self, img):
self.imgBuffer = [img] * BUFFER_SIZE
self.currentIndex = 0
print(f"Image type: {type(img)}")
print(f"buffer shape: {self.imgBuffer[0].shape}")
def addNewImage(self, img):
self... |
# Copyright 2017 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... |
import pytest
from yelp_beans.logic.user import add_preferences
from yelp_beans.logic.user import create_new_employees_from_list
from yelp_beans.logic.user import hash_employee_data
from yelp_beans.logic.user import is_valid_user_subscription_preference
from yelp_beans.logic.user import mark_termed_employees
from yelp_... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import redirect, request, session
from werkzeug.except... |
import json
import importlib
import datetime
import dateutil.parser as date_parser
from registry import constants
from registry import utils
from registry.translation.RelatedStore import RelatedStore
def translate(user, json_data):
"""
Takes json from post data and turns it into a python data
structure. T... |
"""Kazoo testing harnesses"""
import atexit
import logging
import os
import uuid
import threading
import unittest
from kazoo.client import KazooClient
from kazoo.exceptions import NotEmptyError
from kazoo.protocol.states import (
KazooState
)
from kazoo.testing.common import ZookeeperCluster
from kazoo.protocol.co... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Host',
fields=[
('id', models.AutoField(verbose... |
"""PyTorch implementation of Wide-ResNet taken from
https://github.com/jeromerony/fast_adversarial/blob/master/fast_adv/models/cifar10/wide_resnet.py"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, d... |
"""Test function call thread safety."""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestSafeFuncCalls(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipUnlessDarwin
@add_test_categories(['pyapi'])
def t... |
"""
Packages and classes we want to expose to users
"""
from ._utils import get_project_root, store_timestamp
__all__ = [
'get_project_root',
'store_timestamp'
] |
from eICU_preprocessing.split_train_test import create_folder
from models.run_tpc import TPC
import numpy as np
import random
from models.final_experiment_scripts.best_hyperparameters import best_global
from models.initialise_arguments import initialise_tpc_arguments
def get_hyperparam_config(dataset):
c = initi... |
import numpy as np
import sys
## this module is for reading the input
class config:
basisSize = 0
numOfNodes = 0
constant_c = 0
domain = []
potential = []
def __init__(self, file):
self.domain = []
self.potential = []
f = open(file, "r")
for line in f.readlin... |
"""
meepmeep.py
author: Jonathan Tsai <hello@jontsai.com>
date: 2009.04.22
Facebook Engineering Puzzle - Meep meep!
Usage: python meepmeep.py FILE
"""
import sys
import getopt
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv = None):
if argv is None:
argv = sys.... |
# encoding=UTF8
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 m... |
import json
from typing import List
class Snippet:
"""Handle json snippets
Parse json (VS Code) snippets file and generate markdown summary.
"""
def __init__(self, name, snippet_json):
self.name = name
self.description = snippet_json.get("description")
self.prefix = self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.