content stringlengths 5 1.05M |
|---|
import FWCore.ParameterSet.Config as cms
esDigiToRaw = cms.EDProducer("ESDigiToRaw",
debugMode = cms.untracked.bool(False),
InstanceES = cms.string(''),
Label = cms.string('simEcalPreshowerDigis'),
LookupTable = cms.untracked.FileInPath('EventFilter/ESDigiToRaw/data/ES_lookup_table.dat')
)
# bypass ze... |
#!/usr/bin/env python
# coding: utf-8
# <a href="https://colab.research.google.com/github/korymath/public_notebooks/blob/master/Building_Equal_Size_Clusters_Kyle_Mathewson_Sept_2019.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# # Imports
# In[... |
#!/usr/bin/python
from prettytable import PrettyTable
from nova import compute
from nova import objects
from nova import servicegroup
from nova.context import RequestContext
import nova.scheduler.host_manager as host_manager
from nova.objects import resource_provider as rp_obj
from nova import config
import sys
c... |
from django.http import HttpResponseRedirect
from django.conf import settings
from django.http import Http404
import re
from ipaddress import ip_address
from ipaddress import ip_network
TRUSTED_URLS = getattr(settings, 'TRUSTED_URLS', [])
TRUSTED_IPS = getattr(settings, 'TRUSTED_IPS', ['127.0.0.1/32'])
class IPAddr... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Webkit HTTPS Server with CORS
# (c) 2017-2019 Radu.I
uxmScriptVersion = 'v.20190710.1159'
import BaseHTTPServer, SimpleHTTPServer
import ssl
import os, sys, signal
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 4443
web_dir = os.path.join(os.path.di... |
"""Defines services that Hue Sync Box component supports."""
import logging
import voluptuous
from homeassistant.helpers import config_validation
from homeassistant.helpers import service
from . import const
_LOGGER = logging.getLogger(__name__)
GET_ACCESS_TOKEN_SCHEMA = config_validation.make_entity_service_schem... |
"""
======================================================================
Molecular Module Demo
======================================================================
A small example to show how to use the various molecular
representations present in the `molecular` module to visualize
proteins. This example also sho... |
'''
watch.py - Analog Watch Display
Video: https://youtu.be/NItKb6umMc4
'''
import utime
import math
from machine import Pin, SPI
import axp202c
import st7789
def main():
'''
Draw analog watch face and update time
'''
try:
# Turn power on display power
axp = axp202c.PMU()
a... |
from __future__ import (
annotations,
)
import pickle
from . import (
Path_,
)
from typing import (
Any,
Protocol,
NoReturn,
)
from . import (
Pkl,
)
class PklIF(
Protocol,
):
def to_pickle(
self,
path: Path_,
) -> NoReturn:
Pkl.dump(
obj=self,
path=path,
)
@s... |
from django.urls import path
from .views import *
urlpatterns = [
path('desafioInovacao', DesafioInovacao.as_view(), name="desafioInovacao"),
path('desafioInovacao/<int:pk>', DesafioInovacaoDetailView.as_view(),
name='desafioInovacao-detail'),
path('desafioInovacao/create/', DesafioInovacaoCreate.... |
# -*- coding: utf-8 -*-
"""D_With_G
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1uqdOlUPpor_JN2EDdGx2V2KbXLqvCIEX
"""
import matplotlib
matplotlib.use('Agg')
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
impor... |
def iter_fact(n):
'''
assumes that n is an int > 0
returns n!
'''
result = 1
while n > 1:
result *= n
n -= 1
return result
iter_fact(5)
|
#!/usr/bin/env python
""" Class representing a AI Model.
Represents a AI Model. AI Models are used by AI Agents to process
incoming data.
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 re... |
import logging
from cliff import lister
import pkg_resources
LOG = logging.getLogger(__name__)
class GroupList(lister.Lister):
"""Shows the groups for which plugins are available.
"""
def take_action(self, parsed_args):
names = set()
for dist in pkg_resources.working_set:
L... |
# Generated by Django 2.2.11 on 2020-05-20 11:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('resources', '0116_merge_20200520_1347'),
]
operations = [
migrations.AddField(
model_name='res... |
# Generated by Django 3.2.5 on 2021-08-12 20:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('devices', '0038_auto_20210723_1204'),
]
operations = [
migrations.RemoveField(
model_name='asse... |
# #############################################################################
# argcheck.py
# ===========
# Author : Sepand KASHANI [kashani.sepand@gmail.com]
# #############################################################################
"""
Helper functions to ease argument checking.
"""
import collections.abc as... |
import time
import shutil
import random
import logging
from datetime import date
from typing import Optional
import typer
import joblib
import requests
import pandas as pd
from tqdm import tqdm
from bs4 import BeautifulSoup
from tenacity import retry, stop_after_attempt, wait_fixed, before_sleep_log
from requests.exce... |
# -*- coding: utf-8 -*-
class MonteCarloBase(object):
def __init__(self):
if self.__class__ is MonteCarloBase:
raise NotImplementedError
self._d_firstSampleNumber = 0
self._d_lastSampleNumber = 0
self._d_currentSampleNumber = 1
self._d_inSample = False
self._d_inStochastic = True
... |
import codecademylib3_seaborn
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
gradebook = pd.read_csv("gradebook.csv")
sns.barplot(data=gradebook, x="assignment_name", y="grade")
plt.show()
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
import unittest
import frappe
class TestClient(unittest.TestCase):
def test_set_value(self):
todo = frappe.get_doc(dict(doctype='ToDo', description='test')).insert()
frappe.set_value('ToDo', todo.name, 'description', 'test 1')
self.assertEqu... |
# -*- coding: utf-8 -*-
"""
This module contains the logic of the QL checker. The QL checker looks for and
reports errors in the AST tree. This module concreteley detects:
- Duplicated declarations.
- Duplicated labels.
- Invalid assignations.
- Invalid conditions.
- Invalid operands.
- Cyclic ... |
#!pip install pymysql
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy import insert
import pymysql
import mysql.connector as msql
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
def predictPlot():
#Start MySQL connection
db_... |
class PlayerStatus:
def __init__(self, data: dict) -> None:
"""
Parameters
----------
data: dict
The JSON data received from the Hypixel API.
"""
self.UUID = data["uuid"]
self.SESSION_INFO = data["session"]
def __str__(self) -> str:
re... |
/anaconda3/lib/python3.7/codecs.py |
import xgboost as xgb
import numpy as np
import pandas
major_list = []
training_csv = pandas.read_csv('./train.csv', index_col=0)
testing_csv = pandas.read_csv('./test_2.csv', index_col=0)
for Number in range(1,62+1): # From 1 to 62
if Number == 61:
name_of_column = 'Ret_PlusOne'
name_of_weight ... |
'''LeNet in PyTorch.
Modified based on (https://github.com/kuangliu/pytorch-cifar/blob/master/models/lenet.py)
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5, stride=2,... |
from collections import OrderedDict as dict
import pandas as pd
import numpy as np
__all__ = ['CatalogueGroup',
'Catalogue']
class CatalogueGroup(object):
""" CatalogueGroup class.
This is basically a dictionary used by Catalogue class. The idea is
to be able to store different types of ... |
from django.db import models
from django.conf import settings
class Suspicious(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='suspicious', verbose_name=('user')
)
attempt = models.PositiveSmallIntegerField(default=1, ver... |
from django.apps import AppConfig
class SearchPageConfig(AppConfig):
name = 'search_page'
|
#!/usr/bin/env python
# Copyright 2021 The PySCF Developers. 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... |
from os import close
from django.http import HttpResponse
from django.template import Template, Context
from django.template import loader
import datetime
def saludo(request):
return HttpResponse("Hola Django - Coder")
def segundaView(request):
return HttpResponse("Soy Lautaro Murua este es mi sitio web desar... |
#!/usr/bin/env python
# coding: utf-8
# In[105]:
import pandas as pd
import numpy as np
import pickle
import streamlit as st
def AshokLeyland(x):
df = pd.DataFrame({
'Jan':['A','B','C','D','E','F','G','H','J','K','L','M','N','P','R','S','T','V'],
'Feb':['Y','A','B','C','D','E','F','G','H','J... |
#!/usr/bin/env python
"""
dot to json
===========
Convert from graphviz dot file to json in order to visualize a graph using d3.js
You must install pygraphviz and networkx, on Ubuntu:
sudo apt-get install python-pygraphviz python-networkx
Then use the following template replacing the resulting 'force.json'
https... |
#!/usr/bin/env python3
import unittest
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from demo import add, minus
class TestDemo(unittest.TestCase):
"""Test mathfuc.py"""
@classmethod
def setUpClass(cls):
print ("this setupclass() method only called once.\n")
... |
# 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 pytest
from cryptography.hazmat.primitives import constan... |
#!/usr/bin/env python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _refle... |
#!/usr/bin/env python3
#
# Copyright (c) 2017-2020 Linutronix GmbH
#
# SPDX-License-Identifier: MIT
import libconf
import codecs
import logging
import os
import os.path
import shutil
import hashlib
from subprocess import Popen, PIPE
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from tempfile imp... |
# -*- coding: utf-8 -*-
import os
import json
import subprocess
from wt.jinja import filters
workdir = os.path.dirname(__file__)
rootdir = os.path.dirname(workdir)
srcdir = os.path.join(rootdir, 'src')
script = os.path.join(workdir, 'parse_css.js')
def parse_css(filename):
cmd = [
'node',
scri... |
from os import chdir, getcwd
# VERY IMPORTANT: Use the 'execute_at_target' function wrapper to
# take actions inside task directories; do not manually
# move the target directory!!
def execute_at_target(func, task):
original_dir = getcwd()
chdir(task.target_dir)
func(task)
chdir(original_dir)
|
# -*- coding: utf-8 -*-
__version__ = '2.0.0'
default_app_config = 'djangocms_snippet.apps.SnippetConfig'
|
from enhanced_subject_verb_object_extract import findSVOs, nlp
from nltk_subject_verb_object_extraction import SVO
from collections import OrderedDict
import pandas as pd
from pprint import pprint
def get_nsvos(extractor: SVO, text: str):
ntokens = extractor.sentence_split(text)
nsvo_extraction = []
for... |
"""
Implements a Processor for dequantizing model parameters.
"""
import logging
from typing import Any
import torch
from plato.processors import model
class Processor(model.Processor):
"""
Implements a Processor for dequantizing model parameters.
"""
def __init__(self, **kwargs) -> None:
su... |
class Utils:
@staticmethod
def format_time(time):
""" Formats the given time into HH:MM:SS """
seconds = (time / 1000) % 60
minutes = (time / (1000 * 60)) % 60
hours = (time / (1000 * 60 * 60)) % 24
return "%02d:%02d:%02d" % (hours, minutes, seconds)
|
import tensorflow as tf
flags = tf.app.flags
flags.DEFINE_integer("batch_size", 64, "batch size")
flags.DEFINE_integer("max_iters", 600000, "the maxmization epoch")
flags.DEFINE_integer("latent_dim", 128, "the dim of latent code")
flags.DEFINE_float("lr", 0.0003, "the init of learn rate")
#Please set this num of repea... |
import copy
from cv2 import log
import numpy as np
import torch
from utils.Fed import FedAvg,FedAvgGradient, FedAvgP
from core.SGDClient_hr import SGDClient
from core.SVRGClient_hr import SVRGClient
from core.Client_hr import Client
from core.ClientManage import ClientManage
class ClientManageHR(ClientManage):
... |
''' Work of Cameron Palk '''
import sys
import os.path
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
def displayAccuracyGraph( X, Y ):
# convert Y to perceptage strings
Y = [ y * 100 for y in Y ]
plt.plot( X, Y, 'bo' )
plt.title( 'Random Forest: Accuracy v... |
import numpy as np
from sympy import count_ops, preorder_traversal
from sympy.parsing.sympy_parser import parse_expr
from .S_get_number_DL_snapped import get_number_DL_snapped
def get_expr_complexity(expr):
expr = parse_expr(expr)
compl = 0
is_atomic_number = lambda expr: expr.is_Atom and expr.is_number... |
# Copyright (c) 2021 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 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
from unittest import TestCase
import torch
from torch.nn import CrossEntropyLoss
from loss.top_k_cross_entropy_loss import TopKCrossEntropyLoss
class TestTopKCrossEntropyLoss(TestCase):
def test_forward(self):
# Arrange
k = 2
predicted = torch.tensor([[[0.5, .5], [.7, 0.3], [0.0, 1.0]]... |
#!/usr/bin/python3
import boto3
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import picamera
import time
import json
from io import BytesIO
CHANGE_THRESHOLD = 0.005
SLEEP_TIME = 3
CLIENT_ID = 'pyzcam'
PUBLISH_TOPIC = CLIENT_ID + '/out'
SUBSCRIBE_TOPIC = CLIENT_ID + '/in'
AWS_IOT_ENDPOINT = '<YOUR_AWS_IOT_E... |
import pandas as pd
import numpy as np
import sys
import getopt
from sklearn import feature_extraction
from sklearn.cross_validation import StratifiedKFold
from sklearn.preprocessing import LabelEncoder
sys.path.append('/Users/ef/xgboost/wrapper')
import xgboost as xgb
import random
from sklearn.metrics import log_loss... |
# -*- coding: utf-8 -*-
#
# example exm0_mpl.py
# ----------------------------------------------------------------
# PURPOSE
# Setup a finite element flow model using the mesh functions
# in CALFEM.
# ----------------------------------------------------------------
#
# REFERENCES
# J Lindemann 2021-12-29
# ... |
# -*- coding: utf-8 -*-
import os
import errno
import subprocess
import pytest
import swoopi
@pytest.mark.parametrize('supported, detected', [
(True, True), (True, False), (False, False)
])
def test_picamera_status(monkeypatch, supported, detected):
vcgencmd_output = 'supported={} detected={}'.format(
... |
from habu.lib.auth.base import BaseAuth, ReturnCode
from ftplib import FTP, FTP_TLS, error_perm, Error as FTP_Error
import socket
import logging
auth_failed_messages = [
'530 Authentication failed.',
'530 Login authentication failed',
'530 Login incorrect.',
'530 Login incorrect - invalid email addre... |
# import libraries
import torch
import torch.nn as nn
import torch.utils.data as utils
from tqdm import tqdm
import copy
import matplotlib.pyplot as plt
import numpy as np
import os
import model_3D as model
import matplotlib
matplotlib.use('TkAgg')
# np.random.seed(42)
# torch.manual_seed(42)
def NMSE_loss(input, ta... |
#!/usr/bin/env python3
import pysam
import sys
if __name__ == '__main__':
if len(sys.argv) > 2:
sys.exit("Usage: {} [in.vcf]".format(sys.argv[0]))
if len(sys.argv) > 1:
vcf = pysam.VariantFile(sys.argv[1])
else:
vcf = pysam.VariantFile('-')
pos_offset = 1000000
for record in... |
####################
# ES-DOC CIM Questionnaire
# Copyright (c) 2017 ES-DOC. All rights reserved.
#
# University of Colorado, Boulder
# http://cires.colorado.edu/
#
# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].
####################
"""
.. mo... |
# load the pypes framework
from pkg_resources import require
require('pypes')
import re
import time
from pypes.pipeline import Dataflow
from pypes.component import Component
class Tail(Component):
__metatype__ = 'ADAPTER'
def __init__(self, fp):
Component.__init__(self)
self.fp = fp
def... |
'''
Copyright (C) 2021 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson
This program 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 ... |
import os
from bs4 import BeautifulSoup
import requests
import json
import concurrent.futures
import time
def char_case(argument):
# ---Function to clean the character's names when searching in Danbooru---
# Checks the text inputted to see if it's in the JSON:
try:
with open("characters.json") a... |
from django import forms
from metashare.oaipmh import supported_commands
class HarvestForm(forms.Form):
"""
Settings form for OAI-PMH import.
"""
base_URL = forms.URLField(label=u"OAI-PMH server URL",
initial=u"http://www.language-archives.org/cgi-bin/olaca3.pl",
help_te... |
# coding=utf-8
from transformers import XLMRobertaTokenizer
from transformers.utils import logging
logger = logging.get_logger(__name__)
SPIECE_UNDERLINE = "▁"
VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
PRETRAINED_VOCAB_FILES_MAP = {
"vocab_file": {
"layoutxlm-base": "https://huggin... |
#coding:utf-8
'''
根据不同给的subject标签对wos的论文进行分领域处理
'''
from basic_config import *
from gini import gini
'''
选择6个top领域,然后在6个top领域内分别选择一个子领域作为实验数据。
'''
def get_paperids_of_subjects():
pid_subjs = json.loads(open('../cascade_temporal_analysis/data/_ids_subjects.json').read())
paper_year = json.loads(open('../... |
"""Top-level model classes.
Author:
Chris Chute (chute@stanford.edu)
"""
import layers , bert_layers
import torch
import torch.nn as nn
import torch.nn.functional as F
class BiDAF(nn.Module):
"""Baseline BiDAF model for SQuAD.
Based on the paper:
"Bidirectional Attention Flow for Machine Comprehen... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES1 import _types as _cs
# End users want this...
from OpenGL.raw.GLES1._types import *
from OpenGL.raw.GLES1 import _errors
from OpenGL.constant import Constant as _C
... |
import os
import json
import argparse
from management_api import ManagementAPIClient
from utils import read_yaml, should_use_external_idp
import base64
def yaml_obj_to_loc_object(obj):
loc_obj = []
for k in obj.keys():
loc_obj.append({
"code": k,
"parts": [{
"st... |
class PreventCaptchaRevalidationMixin:
"""When get_all_cleaned_data() is called the forms are revalidated,
which causes captcha to fail becuase the same captcha response from google
is posted to google multiple times. This captcha response is a nonce, and
so google complains the second time it's seen.
... |
import os
import sys
from types import MethodType
# A flag to allow dask_gdf to detect and warn if
# IPC serialization is unavailable
CUSTOM_SERIALIZATION_AVAILABLE = False
try:
import distributed.protocol as _dp
from distributed.utils import has_keyword
except ImportError:
def register_distributed_serial... |
# baselineTeam.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.ber... |
import cv2
import json
import keras
import os
import tensorflow as tf
from typing import Tuple
from dataset.image_dataset import ImageDataset, ImagePreprocessor
from experiment_logger.loggable import ObjectDict
from keras_scripts.os_wrapper import list_images, list_subfolders
def get_x_shape_from_root_folder(root_fo... |
"""editing_type_count_by_group
Generating a editing site distribution plot for RESIC
"""
from Experiments.forontiers_jupyter.bar_utils import stacked_bar
import numpy as np
import matplotlib.pyplot as plt
import os
import re
import logging
from typing import Dict,List
from os import listdir
from os.path import isfi... |
from torch import nn
from torchvision.models.resnet import ResNet, Bottleneck
class ResNetEncoder(ResNet):
"""
ResNetEncoder inherits from torchvision's official ResNet. It is modified to
use dilation on the last block to maintain output stride 16, and deleted the
global average pooling layer and the ... |
import unittest
from metaquantome.util.testutils import testfile, TTEST_SINFO
from metaquantome.util import stat_io
from metaquantome.util.utils import TEST_DIR
from metaquantome.classes.SampleGroups import SampleGroups
from metaquantome.modules.filter import run_filter
from metaquantome.modules.expand import expand
... |
# -*- coding: utf-8 -*-
"""
Catch-up TV & More
Copyright (C) 2017 SylvainCecchetto
This file is part of Catch-up TV & More.
Catch-up TV & More 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 Foundat... |
num1 = 1
num2 =2
num = num1 + num2
print(num)
i = 5
while i<0:
sum += num
|
na#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 22:22:10 2018
@author: sudhir
"""
# =============================================================================
# Import packages
# =============================================================================
import pandas as pd
import numpy... |
import sys
from transformers import AutoTokenizer
def preprocess(dataset, destination, model_name_or_path, max_len):
subword_len_counter = 0
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
destination_file = open(destination, 'w', encoding='utf-8')
with open(dataset, "r", encoding='u... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 12:26:35 2019
@author: Caio
"""
def newton_method(number, number_iters = 500):
a = float(number) # number to get square root of
for i in range(number_iters): # iteration number
number = 0.5 * (number + a / number) # update
# x_(n+1) = 0.5 * (x_n +a ... |
import add1
def comp(ke):
lit = '00000000000000000000000000000001'
ke=list(ke)
for x in range(len(ke)):
if ke[x] == '0':
ke[x]='1'
elif ke[x] == '1':
ke[x] = '0'
ke = ''.join(ke)
ke = add1.add(ke,lit)
#ke = bin(int(ke,2) + int(lit,2))[2:].zfill(... |
from __future__ import absolute_import
import logging
from pprint import pformat
from tornado.options import define, options, parse_command_line
from celery.bin.base import Command
from . import settings
from .app import Flower
define("port", default=5555, help="run on the given port", type=int)
define("address",... |
# -*- coding: utf-8 -*-
# @Time : 2017/12/5 18:15
# @Author : Zhiwei Yang
# @File : bucket_sort.py.py
def bucket_sort(nums):
max_number = max(nums)
bucket = [0] * (max_number + 1)
for i in nums:
bucket[i] += 1
print(bucket)
sort_nums = []
for j in range(len(bucket)):
if ... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# FEDERAL UNIVERSITY OF UBERLANDIA
# Faculty of Electrical Engineering
# Biomedical Engineering Lab
# ------------------------------------------------------------------------------
# Author: Italo Gustavo Sampaio Fe... |
import pytest
from ._core import No_Exception
from .. import finding
def test_OK_finding_type():
assert isinstance(finding.OK, finding.ValidationResultStatus)
@pytest.mark.parametrize(
"h5_address, test_name, status, comment, xceptn",
[
[None, None, "exception", None, ValueError],
[None,... |
"""
File: boggle.py
Name: Tao Ke Chorng
----------------------------------------
TODO:
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
word = []
alpha = 'qwertyuioplkjhgfdsaxzcvbnm'
counter = 1
row_of_letter = []
num_of_words... |
from . import sample_data, tests
from .data_structures import (
StreamDataset,
StreamGrid,
StreamHandler,
StreamHierarchy,
hexahedral_connectivity,
)
from .fields import StreamFieldInfo
from .io import IOHandlerStream
|
"""
CALM
Copyright (c) 2021-present NAVER Corp.
MIT license
"""
import argparse
import munch
import importlib
import os
from os.path import join as ospj
import shutil
from util import Logger
_DATASET_NAMES = ('CUB', 'ILSVRC', 'OpenImages')
_ARCHITECTURE_NAMES = ('vgg16', 'resnet50', 'inception_v3')
_ATTRIBUTION_MET... |
import copy
from sdmxthon.model.base import InternationalString, LocalisedString, \
Annotation
from sdmxthon.model.component import Component, Dimension, TimeDimension, \
Attribute, PrimaryMeasure
from sdmxthon.model.definitions import DataStructureDefinition, \
DataFlowDefinition, ContentConstraint, DataK... |
# Generated by Django 3.2.6 on 2021-10-09 00:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vmmanager', '0008_auto_20211008_0224'),
]
operations = [
migrations.AddField(
model_name='virtualmachine',
name='sta... |
#coding:utf-8
#
# id: bugs.core_5367
# title: Regression: (boolean) parameters as search condition no longer allowed
# decription:
# Confirmed on WI-T4.0.0.397 before commit 04-oct-2016 17:52
# https://github.com/FirebirdSQL/firebird/commit/8a4b7e3b79a31dc7bf6e569e6cf... |
from action_detector_diagnosis import ActionDetectorDiagnosis
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as np
import pandas as pd
import os
from collections import OrderedDict
from matplotlib import gridspec, rc
import matplotlib as mpl
import matplotlib.font_manager
mpl.use('Agg'... |
"""
===============================
Using geometric transformations
===============================
This example illustrates use of geometric transformations in the context of
image processing.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skipp import... |
from abc import abstractmethod
from resultado import Resultado
import pandas as pd
from sklearn.base import ClassifierMixin, RegressorMixin
from typing import List,Union
class MetodoAprendizadoDeMaquina:
@abstractmethod
def eval(self,df_treino:pd.DataFrame, df_data_to_predict:pd.DataFrame, col_classe:str) -> ... |
# Copyright (c) 2020 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# basicRAT client
# https://github.com/vesche/basicRAT
#
import socket
import subprocess
import struct
import sys
from core import common
from core import crypto
from core import filesock
from core import persistence
from core import scan
from core import survey
from c... |
import os, sys
import imp
import time
from authorizenet import apicontractsv1
from authorizenet.apicontrollers import *
constants = imp.load_source('modulename', 'constants.py')
from decimal import *
def create_an_accept_payment_transaction(amount):
# Create a merchantAuthenticationType object with authenticatio... |
import pytest
from django.core.files.base import ContentFile
from core.models import UL_ORG_ADMIN
from organizations.models import Organization
from publications.models import Platform
from sushi.models import SushiFetchAttempt, SushiCredentials
@pytest.mark.django_db
class TestFileName:
""" Test class for chec... |
import numpy as np
from src.settings import gridsize
from src.util import fullcols, colsr, colsc
class convert_coords:
"""
Converts tkinter canvas coordinates to pandas grid coordinates, and vice versa.
"""
def __init__(self, gridsize, boardsize) -> None:
self.gridsize = gridsize
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.