content stringlengths 5 1.05M |
|---|
# spinnman imports
from multiprocessing.pool import ThreadPool
from spinnman.connections.udp_packet_connections.\
udp_eieio_connection import UDPEIEIOConnection
from spinnman.messages.eieio.command_messages.database_confirmation import \
DatabaseConfirmation
# front end common imports
from spinn_front_end_comm... |
#!/usr/bin/env python3
import os, glob, itertools
def add_line_prefix_to_file(fname, out_name, line_transform, validate):
with open(fname) as f_in:
with open(out_name, 'w') as f_out:
print('Write:', fname, '->', out_name)
for line in f_in:
line = line.strip()
... |
#Desafio: Crie um programa onde o usuário digite uma expressão qualquer que use parênteses.
# Seu aplicativo deverá analisar se a expressão passada está com os parenteses abertos e fechados em ordem correta.
num = list
num = input('Digite a expressão: ')
if num.count('(') == num.count(')'):
print('Sua expressão e... |
import re
from pyramid_debugtoolbar.tbtools import Traceback
from pyramid_debugtoolbar.panels import DebugPanel
from pyramid_debugtoolbar.utils import escape
from pyramid_debugtoolbar.utils import STATIC_PATH
from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME
from pyramid_debugtoolbar.utils import EXC_ROUTE_NAME
... |
from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.db import transaction
from .validators import ProtectedGroupsValidator
from .validators import SomeSuperuserLeftValidator
class CreatableSlugRelatedField(serializers.SlugRela... |
from peewee import *
db = SqliteDatabase('iso639corpora.db')
class Languages(Model):
name = CharField()
part1 = CharField(null=True)
part2 = CharField(null=True)
part3 = CharField(null=True)
text = TextField(null=True)
class Meta:
database = db # This model uses the "people.db" data... |
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# 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 la... |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import os
import math
import torch.nn.functional as nn
from torch.autograd import Variable
import torch
from tensorflow.examples.tutorials.mnist import input_data
from sklearn import manifold
def P(z):
mnist = input_data.rea... |
import sys
from rebus.agent import Agent
@Agent.register
class Search(Agent):
_name_ = "search"
_desc_ = "Output a list of selectors for descriptors that match provided "\
"domain, selector prefix and value regex"
_operationmodes_ = ('automatic', )
@classmethod
def add_arguments(cls,... |
import random
import numpy as np
import os
import torch
import h5py
import argparse
import json
import torchvision.transforms as transforms
import sys
sys.path.insert(0, "../")
from tkinter import filedialog
from tkinter import *
from PIL import Image, ImageTk
from torch.autograd import Variable
from dense_coattn.mo... |
from decimal import Decimal
from strawberry.utils.debug import pretty_print_graphql_operation
def test_pretty_print(mocker):
mock = mocker.patch("builtins.print")
pretty_print_graphql_operation("Example", "{ query }", variables={})
mock.assert_called_with("{ \x1b[38;5;125mquery\x1b[39m }\n")
def test... |
# -*- coding: utf-8 -*-
from .exec_env_config import ExecEnvConfig
class DockerConfig(ExecEnvConfig):
def __init__(self, parsed_yaml: {}, key: str):
super().__init__(parsed_yaml, key)
configs = parsed_yaml.get(key, {})
self.container_name = configs.get('container_name', '')
|
#!/usr/bin/env python3
import sys
import os
from systemrdl import RDLCompiler, RDLCompileError
from ralbot.html import HTMLExporter
# Collect SystemRDL input files from the command line arguments
input_files = sys.argv[1:]
# Create an instance of the compiler
rdlc = RDLCompiler()
try:
# Compile all the files... |
#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import unittest
from api_list_data_source import APIListDataSource
from server_instance import ServerInstance
from test_fi... |
"""
Sequential generator model - sample the outputs vector
iteratively entry by entry.
For an output vector of size n, n models are trained.
First model learns the distribution of first entry in
output vector.
Second model learns the distribution of second entry,
conditioned on first one.
Thirs model learns the distri... |
from django.db import models
import users.models
from subscriptions.models import Subscription
from django.utils.translation import gettext as _
# Create your models here.
class Show(models.Model):
TYPE_CHOICE_UNKNOWN = 0
TYPE_CHOICE_MOVIE = 1
TYPE_CHOICE_TV = 2
TYPE_CHOICES = (
(TYPE_CHOICE_UN... |
from yml2sif import dict_to_sif
from os import sys
import yaml
def test_dict_to_sif():
ymlfile = open('./esim1.yml', 'r')
siffile = sys.stdout
ymldata = yaml.load(ymlfile.read())
dict_to_sif(ymldata, siffile)
ymlfile.close()
if __name__=="__main__":
test_dict_to_sif()
|
def remove_outer_symbols(s):
left = s.index("[")
right = s.rindex("]", left)
return s[:left] + s[left+1:right] + s[right+1:]
async def embed_cmd(bot, discord, message, botconfig, platform, os, datetime, one_result, localization, unix_time_millis, embed_color, connection, cursor, prefix):
args = mes... |
#!/usr/bin/env python3
"""
Import packages
"""
import numpy as np
import argparse
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from net import ResBase, ResClassifier, RelativeRotationClassifier
f... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import os
import pytest
from cryptography.exceptions im... |
# pylint: disable=invalid-name
"""
https://leetcode.com/problems/longest-palindrome/
Given a string s which consists of lowercase or uppercase letters, return the
length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome
here.
... |
"""
Utilities for generating input and output strings.
"""
def seq_to_str(seq, sep="\n", with_len=True, len_sep="\n", end_sep="\n"):
"""
Convert a Python sequence into a string with the given separator.
Each item is converted to a string using str().
If with_len is given, put the length first, and sep... |
# coding: utf-8
# Copyright (c) 2016, 2021, 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... |
#!/usr/bin/env python
#
# Translational stop site (tlss) distance
# For each read (BED file), determine the distance to the nearest 3' UTR translational stop site
# Input is a BED file containing all 3'UTRs - distance calculated is from TLSS.
#
# Matches before the TLSS are negative, w/in 3' UTR are positive
import sy... |
from utils.utils import write_to_video, make_dir
import cv2
import json
import argparse
import os
import glob
import numpy as np
def video_generator(video_dir,
frame_height=64,
frame_width=64,
frame_channels=3,
batch_size=1,
time=10,
camera_fps=2,
crop_height=224,
crop_width=112,
json_files="dataset_jso... |
import math
def get_slabs():
slabs_list=[0]+[int(i) for i in input().split()]+[math.inf]
percent=[0]+[int(i) for i in input().split()]
slabs=[]
for i in range(len(slabs_list)-1):
val=(slabs_list[i+1]-slabs_list[i])*percent[i]/100
slabs.append((slabs_list[i],slabs_list[i+1],percent[i],va... |
from __future__ import print_function
from string import Template as TStr
import logging
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
class GSheet:
# If modifying these scopes, de... |
import glob
import math
import numpy as np
import os
import fnmatch
import sys
def round_up(x, y):
return int(math.ceil(float(x) / float(y)))
def add_parameter(class_object, kwargs, parameter, default=None):
if parameter in kwargs:
setattr(class_object, parameter, kwargs.get(parameter))
else:
... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
import socket
def main():
HOST = '212.47.229.1'
PORT = 33003
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (HOST, PORT)
tcp.connect(dest)
data = tcp.recv(2048)
while "FLAG" not in data:
result = 0
print(da... |
from django.shortcuts import render
from molo.profiles.admin import FrontendUsersModelAdmin, UserProfileModelAdmin
from molo.profiles.models import (
UserProfilesSettings, UserProfile, SecurityAnswer)
from wagtail.contrib.modeladmin.options import modeladmin_register
from wagtail.admin.site_summary import SummaryIt... |
# The port SendGrid will upload events to.
REPOSTER_PORT = 12345
# Where to repost them?
SITE_URLS = {
'default': 'http://localhost:10002',
'dev-marcink': 'http://localhost:10003',
}
|
"""
Shared utility functions
"""
from boto.datapipeline import regions
from boto.datapipeline.layer1 import DataPipelineConnection
from time import sleep
import dateutil.parser
from dataduct.config import Config
config = Config()
REGION = config.etl.get('REGION', None)
DP_ACTUAL_END_TIME = '@actualEndTime'
DP_ATTEMP... |
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
import json
from .models import *
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return HttpResponseRedirec... |
from .base import Transform, TransformChain
from .homogeneous import *
from .thinplatesplines import ThinPlateSplines
from .piecewiseaffine import PiecewiseAffine
from .rbf import R2LogR2RBF, R2LogRRBF
from .groupalign.procrustes import GeneralizedProcrustesAnalysis
|
# encryption.py
# Class to utilize the cryptography library and produce encrypted values
# Authors: Akansh Divker
import string
import random
from Crypto.Hash import SHA256
class Encryption:
def __init__(self):
letters = string.ascii_lowercase
key = ''.join(random.choice(letters) for i in range(1... |
# Generated by Django 3.2.3 on 2021-07-01 16:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0014_auto_20210628_0012'),
]
operations = [
migrations.AlterField(
model_name='ordernumbermodel',
name='ord... |
# Author: Kelvin Lai <kelvin@firststreet.org>
# Copyright: This module is owned by First Street Foundation
# Standard Imports
import logging
# Internal Imports
from firststreet.api import csv_format
from firststreet.api.api import Api
from firststreet.models.environmental import EnvironmentalPrecipitation
class Env... |
# Time: O(m * n)
# Space: O(1)
# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
# Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
#
# Example 1:
#
# Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
# Output: True
# Explanation:
# 1234
# 5123
# 9... |
from .model import ClassAttention, ClassAttentionLayer, SelfAttentionLayer, CaiTBackbone, CaiTWithLinearClassifier
from .config import CaiTConfig |
from struct import pack, unpack
from .zkconst import *
def zkversion(self):
"""Start a connection with the time clock"""
command = CMD_VERSION
command_string = ''
chksum = 0
session_id = self.session_id
reply_id = unpack('HHHH', self.data_recv[:8])[3]
buf = self.createHeader(command, chks... |
"""Deprecated path for GCS storage."""
# TODO: Remove after deprecation period.
from grow.common import deprecated
from grow.storage import google_storage as new_ref
# pylint: disable=invalid-name
CloudStorage = deprecated.MovedHelper(
new_ref.CloudStorage, 'grow.pods.storage.google_storage.CloudStorage')
CloudS... |
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1443802885.4184651
_enable_loop = True
_template_filename = '/usr/local/lib/python3.4/dist-package... |
#!/usr/bin/python3
# UTF8
# Date: Thu 20 Jun 2019 13:00:45 CEST
# Author: Nicolas Flandrois
from engine import Engine
def main():
"""Main running function."""
Engine.menu()
if __name__ == '__main__':
main()
|
import logging
from aiogram import types
from aiogram.dispatcher import Dispatcher
from aiogram.utils.executor import start_webhook
from config import (
API_TOKEN,
preliminary_command,
retraction_command,
secret,
update_command,
)
from logconfig import logging_kwargs
from gracebot import GraceBot
... |
# coding=utf-8
from __future__ import absolute_import, print_function
import torch
from torch.backends import cudnn
from evaluations import extract_features
import models
from data import dataset
from utils.serialization import load_checkpoint
cudnn.benchmark = True
def Model2Feature(data, net, checkpoint, dim=512, ... |
#!/usr/bin/env python
# vi: sw=4 ts=4:
"""
Mnemonic: vfd_pre_start.py
Abstract: This script calls the 'dpdk_nic_bind' script to bind PF's and VF's to vfio-pci
Date: April 2016
Author: Dhanunjaya Naidu Ravada (dr3662@att.com)
Mod: 2016 7 Apr - Created script
... |
def first_repeated(c):
hash = dict()
c = list(c)
for i in range(len(c)):
if c[i] not in hash:
hash[c[i]] = 1
else:
return c[i]
return "No repeated Element"
a = input("Enter : ")
print(first_repeated(a)) |
# Generated by Django 3.1.7 on 2021-05-03 04:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Department',
fields=[
('id',... |
def add(x, y):
return x + y
def diff(x, y):
return x - y
def multiple(x, y):
return x * y
def get_x(x,y):
return x
def get_y(x,y):
return y
def x_is_greater_than_y(x,y):
return (x > y) * 1.0
|
#!/bin/python3
# author: Jan Hybs
import argparse
import pathlib
import maya
from cihpc.common.utils.vcs import HistoryBrowser
default_min_age = maya.when('6 months ago')
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', help='URL of the repo', default='https://github.com/flow123d/flow123d.git'... |
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
import helper as hlp
talk = hlp.Talk()
Builder.load_str... |
# _*_coding:utf-8_*_
import pika
from config import config
def mq_client():
_config = config("../conf/mq.ini")
user = _config.getOption("rabbit_mq", "user")
passwd = _config.getOption("rabbit_mq", "passwd")
ip = _config.getOption("rabbit_mq", "ip")
port = _config.getOption("rabbit_mq", "port")
... |
import copy
import inspect
from urlparse import urljoin
from jfr_playoff.dto import Match, Team
from jfr_playoff.logger import PlayoffLogger
class ResultInfoClient(object):
def __init__(self, settings, database=None):
self.settings = settings
self.database = database
@property
def priori... |
# -*- coding: utf-8 -*-
class Singleton:
_instance = None
@classmethod
def _getInstance(cls):
return cls._instance
@classmethod
def instance(cls, *args, **kargs):
cls._instance = cls(*args, **kargs)
cls.instance = cls._getInstance
return cls._instance
|
import numpy as np
import pandas as pd
import pytest
from prereise.gather.hydrodata.eia.decompose_profile import get_profile_by_state
def test_get_profile_argument_type():
arg = ((1, "WA"), (pd.Series(dtype=np.float64), 1))
for a in arg:
with pytest.raises(TypeError):
get_profile_by_state... |
import rx
import rx.operators as ops
import rxsci as rs
def test_lag1():
source = [1, 2, 3, 4, 5, 6, 7, 8, 9]
actual_result = []
expected_result = [
(1, 1),
(1, 2),
(2, 3),
(3, 4),
(4, 5),
(5, 6),
(6, 7),
(7, 8),
(8, 9),
]
rx... |
import re
import string
def extract_tags(txt):
"""
create tags for flashes
:param text: flashes content
:return: tags created for the flash
"""
txt = txt.translate(txt.maketrans("","", string.punctuation))
easy_injuries = ['קל']
hard_injuries = ['קשה', 'אנוש']
middle_injuries = ['... |
import re
__all__ = ("load_config", "get_setting_value")
def load_from_django():
from django.conf import settings
DEFAULT_CONFIG = {
"CACHE": not settings.DEBUG,
"IGNORE": [r".+\.hot-update.js", r".+\.map"],
"LOADER_CLASS": "webpack_boilerplate.loader.WebpackLoader",
}
user_... |
class Solution:
# time: O(1)
# space: O(1)
def findComplement(self, num: int) -> int:
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num
|
import requests
class HTTP:
@staticmethod
def get(url, return_json=True):
r = requests.get(url)
'''
if r.status_code == 200:
if return_json:
return r.json()
else:
return r.text
else:
return {}
'''
... |
# -*- coding: utf-8 -*-
import itertools
import re
from copy import copy
import pandas as pd
import requests
from zvt.contract.api import get_entity_code
from zvt.utils import to_pd_timestamp, normal_index_df
WORLD_BANK_URL = "http://api.worldbank.org/v2"
# thanks to https://github.com/mwouts/world_bank_data
_econ... |
from .ParentClass import ParentClass
from .ParentPlural import ParentPlural
from .ParentPluralDict import ParentPluralDict
from .ParentPluralList import ParentPluralList |
import sys
PY3 = sys.version_info[0] == 3
# zcml is not yet compatible with python 3, but we need to provide compatible
# syntax in case this module gets imported by the test runner under python 3
if not PY3:
from pyramid_zcml import IRouteLikeDirective
from pyramid_zcml import with_context
from zope.... |
from seguridad.relaciones_models import *
from seguridad.maestros_models import *
# menu = ReMenu.objects.filter(padre_id__isnull=True).values()
# for hijo in menu:
def menu_prueba():
obj = [{'id': 1, 'nombre': 'Luis Farfan', 'padre_id': None},
{'id': 2, 'nombre': 'Ana Vega', 'padre_id': None},
... |
from io import BytesIO as _BytesIO
from copy import deepcopy
from abc import ABCMeta, abstractmethod
import bitcoin.core
from bitcoin.core.script import *
from binascii import unhexlify, hexlify
from base58 import b58encode, b58decode
from hashlib import sha256
from ecdsa import SigningKey
from ecdsa.util import sigenc... |
import unittest
import mock
from tethys_portal.views.developer import is_staff, home
class TethysPortalDeveloperTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_is_staff(self):
mock_user = mock.MagicMock()
mock_user.is_staff = 'foo'
... |
print('\n===== DESAFIO 005 ====\n')
print('Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e o seu antecessor.')
n = int(input('Digite um número: '))
print('O sucessor de {} é {} \ne o antecessor de {} é {}'.format(n, n+1, n, n-1))
print('\n===== DESAFIO 006 ====\n')
print('Crie um algoritm... |
import requests
from requests.auth import HTTPBasicAuth
import time
url = "https://api.mysportsfeeds.com/v2.1/pull/nhl/2021-2022-regular/games.csv"
token = "4e92f126-d598-4577-98e3-bb0674"
password = "MYSPORTSFEEDS"
top_directory = r"C:\Users\John Lang\Documents\Marauder\NHL\core"
years = ["2017","2018","2019"... |
import cv2 as cv
import numpy as np
img = cv.imread("nancy.jpg")
# resizing
resize = cv.resize(img, (400, 400), interpolation=cv.INTER_AREA)
print(img.shape)
print(resize.shape)
cv.imshow("resize", resize)
# cropping
Cropped = img[150:200, 200:300]
cv.imshow("Crop", Cropped)
cv.waitKey(0)
cv.destroyAl... |
from requirements_detector.detect import find_requirements |
#!/home/blur/Desktop/projekty/subjectio/bot/bot_backend/.venv/bin/python
# import sys
# sys.path.append(".")
from botski.importy import *
from botski.config import *
from botski.models import *
from botski.db import *
from botski.tweepy_init import *
from botski.helpers import *
locale.setlocale(locale.LC_TIME, 'pl_... |
# -*- coding: utf-8 -*-
#
# H3C Technologies Co., Limited Copyright 2003-2015, 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/LICEN... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("EWKDimuonSkim")
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )
# source
process.source = cms.Source("PoolSo... |
import json
import requests
import os
import os.path
import sys
iqurl = sys.argv[1]
iquser = sys.argv[2]
iqpwd = sys.argv[3]
jsonfile = 'applicationevaluations.json'
csvfile = 'applicationevaluations.csv'
def get_metrics():
req = requests.get('{}/api/v2/reports/applications'.format(iqurl), auth=(iquser, iqpwd), ver... |
# -*- coding: utf-8 -*-
import unittest
from app.missions.mission import is_mission_feasible, get_expiry_date
from app.planes.supersonic_tu_plane import SupersonicTUPlane
class TestMission(object):
def __init__(self, **kwargs):
self.km_nb = kwargs['km_nb']
self.travellers_nb = kwargs['travellers_... |
"""
===================================================================================
| N A M E G O E S H E R E L O L (v-2.4.0) |
| a game made by SSS_Says_Snek#0194, aimed at upgrading snake |
| it's actually gonna be a terrible game, but hey, why not... |
# coding: utf-8
"""
Copyright 2016 SmartBear 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 applica... |
import os
from tornado.web import url
from app.handlers import index
handlers = [
('/', index.IndexHandler),
# url('/html', HtmlHandler),
# url('/data/?', DBHandler),
# url(r'/(?P<name>\w+)/?', MainNameHandler),
# (r"/(.*?)/(.*?)/(.*)", RedirectHandler, {"url": "/{1}/{0}/{2}", 'permanent': True}),... |
#!/usr/bin/env python
# Standard library imports
import os.path
import sys
# Third party imports
import numpy as np
import pytest
# Local imports
from shakelib.conversions.imt.newmark_hall_1982 import NewmarkHall1982
homedir = os.path.dirname(os.path.abspath(__file__)) # where is this script?
shakedir = os.path.a... |
# Aula 8 - Utilizando Módulos
from math import sqrt, floor
import emoji
num = int(input('Digite um numero: '))
raiz = sqrt(num) # importando apenas um modulo da biblioteca, nao eh necessario declarar a biblioteca (math.sqrt)
print(f'A raiz quadrada de {num} eh {floor(raiz):.2f}') # floor() arredonda pra cima
pri... |
# Copyright (c) 2019 Eric Steinberger
import numpy as np
import torch
from prl.environment.steinberger.PokerRL.rl import rl_util
from prl.environment.steinberger.PokerRL.rl.neural.DuelingQNet import DuelingQNet
from prl.environment.steinberger.PokerRL.rl.neural.NetWrapperBase import NetWrapperArgsBase as _NetWrapper... |
"""Stocastic graph."""
# Copyright (C) 2010-2013 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import networkx as nx
from networkx.utils import not_implemented_for
__author__ = "Aric Hagberg <aric.hagberg@g... |
#!/usr/bin/python
import unittest
import autodetect as detect
class TestDetectDevice(unittest.TestCase):
options = {}
def setUp(self):
self.options = {}
self.options["--ssh-path"] = "/usr/bin/ssh"
self.options["--telnet-path"] = "/usr/bin/telnet"
self.options["--login-timeout"... |
# -*- coding: utf-8 -*-
"""SPUB.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1cqgT4kKo8l52Rs_hozQQBVFZK8atvd8g
#**Sentence Prediction using Bert**
"""
pip install transformers
from transformers import BertTokenizer, BertForNextSentencePredic... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.fields import related
# Create your models here.
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200, null=True, blank=True)
... |
# Generated by Django 2.1 on 2018-09-04 14:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('phantomapp', '0007_shopcategory_shopproduct'),
]
operations = [
migrations.AlterField(
model_name='shopproduct',
name=... |
from django.urls import path
from .views import ApplicationListAPIView, update_status_apiview
urlpatterns = [
path('applications/', ApplicationListAPIView.as_view()),
path('update-status/<int:pk>/', update_status_apiview),
]
|
from strawberry.tools import create_type
from .mutations.login import login
from .mutations.register import register
from .mutations.request_reset_password import request_reset_password
from .mutations.reset_password import reset_password
from .mutations.update_profile import update_profile
Mutation = create_type(
... |
"""This module tests the main function"""
from mock import patch
from game import main, Game
def test_main():
"""This function tests the main function"""
def new_play(self):
"""We need this function to test the main function"""
self.boolean = False
with patch.object(Game, 'play', new_play... |
import nibabel as nib
import numpy as np
import os, glob
def run_realign(emb, tar, firstpass = False):
realign = []
if firstpass:
realign.append(tar)
for i, embedding in enumerate(emb):
u, s, v = np.linalg.svd(tar.T.dot(embedding), full_matrices=False)
xfm = v.T.dot(u.T)
rea... |
from app import models, db, app
user_file = "./users.txt"
base = "ctys"
num = 1
with open(user_file) as f:
for user in f:
lname, fname = user.strip().split(",")
pw = base + str(num) + lname[:3]
user = models.User(firstname=fname,
lastname=lname,
username=fname.lower(),
password=pw,
s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import numpy as np
import common
def load_json(filename):
with open(filename, "r") as f:
return json.load(f)
def load_data(filename):
j = load_json(filename)
return j["nsamples"], np.array(j["mean"]), np.array(j["variance"])
# converge... |
import struct
import mmtf
import mmtf.utils.constants
def parse_header(input_array):
"""Parse the header and return it along with the input array minus the header.
:param input_array the array to parse
:return the codec, the length of the decoded array, the parameter and the remainder
of the array"""... |
import requests
def get_proxy():
return requests.get("http://127.0.0.1:8010/get?type=https").json()
def delete_proxy(proxy):
requests.get("http://127.0.0.1:8010/delete/?proxy={}".format(proxy))
# your spider code
def getHtml():
# ....
retry_count = 5
proxy = get_proxy().get("proxy")
while... |
MODEL_PATH = "yolo-coco"
MIN_CONF = 0.3
NMS_THRESH = 0.4
USE_GPU = False
MIN_DISTANCE = 50
from detection import detect_people
from scipy.spatial import distance as dist
import numpy as np
import argparse
import imutils
import time
import cv2
import os
start_time = time.time()
ap = argparse.ArgumentParser()
ap.add... |
#!/usr/bin/env python
"""
extractORFs.py <6 frame translation>
Author: Tony Papenfuss
Date: Wed Aug 23 08:52:58 EST 2006
"""
import os, sys
import re, copy
import fasta, sequence
pattern = re.compile('[\*|X{200,}]')
minLen = 20
i = 0
writer = fasta.MfaWriter('ORFs.fa')
filename = sys.argv[1]
header,dna = fasta.... |
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from nltk.stem.snowball import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
import nltk
def do_numpy_stuff():
return np.sqrt(5)
def tokenize(text):
wordnet = Wor... |
# -*- coding: utf-8 -*-
"""
Runs the simulation with the right variables and handles output.
"""
import helpers.runsimulation as run
import numpy as np
import matplotlib.pyplot as plt
import helpers.muaanalytical as muaAna
def Rvsr():
""" Runs the simulation once for a given mua. """
mua = 10.
prop =... |
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from requests import Session
from threading import Thread
from threadutil import run_in_main_thread
from time import sleep
name = input("Please enter your name: ")
chat_url = "https://build-system.fman.io/chat"
server = Session()
# GUI:
app = QApplication([])
t... |
import discord
from discord.ext import commands
import random
import aiohttp
import os
import asyncio
from assets import quotes
eat_reactions = ['''_{0}_, you try to eat _{1}_, but you can\'t do it.'
So you, leave with the taste of failure hanging in your mouth''',
'_{0}_, you try to gobble up _{1}_.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.