content stringlengths 5 1.05M |
|---|
from pathlib import Path
from ...graphs import Graph003
from ...utils import BaseGraphSystemTester
from ....engine_input import SubprefixHijack
from ....engine import BGPSimpleAS
from ....engine import BGPAS
from ....engine import ROVSimpleAS
from ....engine import ROVAS
class BaseFig2Tester(BaseGraphSystemTester):... |
import subprocess as sub
import sys
import os
import uuid
import calendar
import datetime
import cPickle as pickle
import shutil
#input_file = open('/shrg1/wind/sw/STICS_data_processing/input_info/input_info.txt', 'r')
input_file=open('/home/kploof/STICS_data_processing/input_info/input_info.txt', 'r')
file_lines = i... |
from CommonCode.convertJSONTOPb import ConvertJSONToPb
from CommonCode.convertPbToJSON import ConvertPbToJSON
from Services.sendPushNotificationService import SendPushNotificationService
from protobuff import pushnotification_pb2
class SendPushNotificationHandler:
@staticmethod
def snedNotification(builder):... |
#!/usr/bin/env python3
import argparse
from aircrushcore.cms import compute_node, compute_node_collection, session_collection, task_instance_collection
from aircrushcore.controller.configuration import AircrushConfig
from aircrushcore.dag import Workload
from aircrushcore.cms import *
from aircrushcore.datacommons.dat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Zenine
#!/usr/bin/env python
import urllib2
import sys
import sqlite3
import cookielib
from lxml import etree
from bs4 import BeautifulSoup
import time
#coding changing
reload(sys)
#SQL_RESULT,数据库清洗SQL,还要一个模块未实现
#1.SELECT * FROM company58 WHERE email !='' AND LENGTH(PHONE_... |
import argparse
import json
import os
from tqdm import tqdm
from experiment import *
from results import MultipleResults
from joblib.parallel import Parallel, delayed
parser = None
folder = None
run_times = None
random_seed = None
def create_model(model_params):
if 'ridge_model' in model_params:
model_... |
import unittest
import os
from DockerBuildSystem import DockerComposeTools
from DockerFeed.Handlers.StackHandler import StackHandler
from tests import TestUtilities
class TestStackHandler(unittest.TestCase):
def test_DeployRemove(self):
handler: StackHandler = TestUtilities.CreateStackHandler()
ha... |
import h5py
import numpy as np
import matplotlib.pyplot as plt
original_results = '../output/cell_vars.h5'
def plot_figs(nrn_results=None):
orig_h5 = h5py.File(original_results, 'r')
new_h5 = h5py.File(nrn_results, 'r')
gids = np.array(new_h5['/mapping/gids'])
indx_ptrs = np.array(new_h5['/mapping/in... |
import setuptools
with open("README.md", "rb") as fh:
long_description = fh.read().decode('utf-8')
setuptools.setup(
name="packel",
version="1.0.1",
author="kiwec",
author_email="[email protected]",
description="Packet serialization/deserialization in a Pythonic way.",
long_description=long... |
class RemovedInWagtailMenus31Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtailMenus31Warning
class RemovedInWagtailMenus32Warning(PendingDeprecationWarning):
pass
class RemovedInWagtailMenus33Warning(PendingDeprecationWarning):
pass
|
## Copyright (c) Microsoft Corporation.
## Licensed under the MIT License.
# empty __init__.py file to allow this directory to be imported from elsewhere
|
import datetime
import re
import gws
import gws.tools.misc
import gws.types as t
_default_editor = {
t.AttributeType.bool: 'checkbox',
t.AttributeType.bytes: 'file',
t.AttributeType.date: 'date',
t.AttributeType.datetime: 'datetime',
t.AttributeType.float: 'float',
t.AttributeType.geometry: '... |
from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
import sys # to write the output while running unit tests
class CommandTests(TestCase):
def test_wait_for_db_ready(self):
"""Test waiting for db ... |
from .__main__ import FFTTransform
__all__ = [
'FFTTransform'
]
|
import argparse
import json
from . import categories, category, palette, search
def main() -> int:
parser = argparse.ArgumentParser(
description='Search for emoji information')
group = parser.add_mutually_exclusive_group()
group.add_argument('--search', type=str, required=False, default... |
from app.main import db
import jwt
from app.main.models.ChallengesModel import ChallengesModel
from app.main.models.TestCasesModel import TestCasesModel
import json
def save_changes(data):
try:
db.session.add(data)
db.session.commit()
except Exception as e:
db.session.rollback()
def ... |
import numpy as np
from progress.bar import Bar
import time
from constants import MAX_COLOR_VALUE
def normalize(arr):
"""
Normalize a vector using numpy.
Args:
arr(darray): Input vector
Returns:
darray: Normalized input vector
"""
norm = np.linalg.norm(arr)
if norm == 0:
... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
#Test modwsgi.
#Hello world test application to make sure modwsgi runs. Link from you apache file to here to test.
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
#print >> sys.stderr, "sys.stderr"
#print >> environ["wsgi.errors"], "wsgi.errors"
response_headers... |
import importlib
import itertools
from collections import namedtuple
import pytest
from dsch import exceptions, frontend, schema
from dsch.backends import inmem
backend_data = namedtuple('backend_data', ('module', 'storage_path'))
@pytest.fixture(params=('hdf5', 'mat', 'npz'))
def backend(request, tmpdir):
bac... |
import importlib
import subprocess
import sys
def _package_exists(config: dict) -> bool:
"""Check to see whether a package exists."""
try:
importlib.import_module(config["import"])
except ModuleNotFoundError:
return False
return True
def package_from_config(config: dict) -> str:
... |
"""
Autogenerated by ghenerate script, part of Quantarhei
http://github.com/tmancal74/quantarhei
Tomas Mancal, [email protected]
Generated on: 2018-11-12 14:35:11
Edit the functions below to give them desired functionality.
In present version of `ghenerate`, no edits or replacements
are ... |
import csv
import dateutil.parser
import os
import splparser.parser
from user import *
from query import *
from logging import getLogger as get_logger
from os import path
from splparser.exceptions import SPLSyntaxError, TerminatingSPLSyntaxError
BYTES_IN_MB = 1048576
LIMIT = 2000*BYTES_IN_MB
logger = get_logger("q... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import urllib
import urlparse
from saml2 import BINDING_HTTP_POST
from saml2 import BINDING_HTTP_REDIRECT
from saml2 import config
from saml2 import class_name
from saml2 import extension_elements_to_elements
from saml2 import saml
from saml2 import samlp
fro... |
# https://colab.research.google.com/drive/16B56hyMC-apzhoYOjFnF--ejHUpS0f77?usp=sharing
# -*- coding: utf-8 -*-
"""bigo.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/16B56hyMC-apzhoYOjFnF--ejHUpS0f77
# Big-O Notation: Plots
The purpose of thi... |
def getResizedLeftSMPLX_UpperLeg(vertices, customerEstimatedUpperLegLenInches, customerEstimatedHeightInches, customerEstimatedMaxLowerLegWidthInches_X, customerEstimatedMaxLowerLegDepthInches_Z, customerEstimatedMaxUpperLegWidthInches_X, customerEstimatedMaxUpperLegDepthInches_Z):
# Idea: have this spit out all... |
# encoding:utf-8
import urllib2
import cookielib
"""
下面的这个程序完成的是从响应中将cookie信息提取出来
"""
# 创建一个对象存储cookie
cookie = cookielib.CookieJar()
# 自动提取
header = urllib2.HTTPCookieProcessor(cookie)
# 处理cookie
opener = urllib2.build_opener(header)
response = opener.open("http://www.renren.com/")
cookies = ""
for data in cookie... |
N = int(input())
div = []
i = 1
while i * i <= N:
if N % i == 0:
div.append(i)
if N // i != i:
div.append(N // i)
i += 1
div.sort()
prev = 0
ans = 0
for d in div:
m = N // d - 1
if m > 0 and N // m == N % m:
ans += m
print(ans)
|
from models.base.EntityBase import EntityBase
from models.base.integration.DataIntegrationConnectionDatabaseBase import DataIntegrationConnectionDatabaseBase
from models.base.integration.DataIntegrationConnectionFileBase import DataIntegrationConnectionFileBase
from models.base.integration.DataIntegrationConnectionQueu... |
"""
This is the Journal Module
"""
import os
def load_journal(name):
"""
This method creates and loads a new ourn
:param name: the name of the journal
:return: a list with entries in the journal as its elements
"""
data = []
filename = get_journal_path(name)
if os.path.exists(filenam... |
import re
import datetime
import decimal
from twisted.internet import defer
from scrapy.spider import BaseSpider
from scrapy.http import Request, Response
from scrapy.utils.py26 import json
class SpiderReferencer(object):
"""Class to serialize (and deserialize) objects (typically dicts)
containing reference... |
from bokeh.io import output_file, show
from bokeh.models import CustomJS, Slider, Div, Column
# NOTE: the JS functions to forvide the format code for strings is found the answer
# from the user fearphage at http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
callback = CustomJS(code... |
from .fluent import Fluent
___red_end_user_data_statement__ = (
"This cog does not persistently store data about users. This cog uses google's free translator api"
)
def setup(bot):
cog = Fluent(bot)
bot.add_cog(cog)
|
from django.urls import path
from . import views
app_name = "sheets"
urlpatterns = [
path('feature_values', views.get_feature, name="feature_values"),
path('feature_name_tree', views.get_feature_name_tree, name="feature_name_tree"),
path('feature_search_list', views.get_feature_search_list, name="feature_... |
# Copyright (c) 2017 Midokura SARL
# 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 require... |
from redbot.core import commands
from .loot import Loot
def setup(bot: commands.Bot):
bot.add_cog(Loot(bot))
|
from .delete import random_deletion
from .swap import random_swap
|
from flask import Flask, render_template, request, session
import os
from flask_session import Session
#Configure app
app = Flask(__name__)
#Configure session
app.config["SESSION_PERMANENT"]= False
app.config["SESSION_TYPE"]="filesystem"
Session(app)
images=os.path.join("static", "images")
app.config["UPLOAD_FOLDER"... |
#/usr/bin/env python3.4
#
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
#!/usr/bin/python3
# coding: utf-8
import numpy as np
import plotly.graph_objects as go
from scipy import fftpack
def fft_denoise(x, y, showFigure=True, freq_int=0.15, freq_th=0.18, freq_min_A=0.03):
n = len(x)
if showFigure:
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y))
fig.s... |
import argparse
import boto3
import configparser
import datetime
import math
import json
import time
from decimal import Decimal
from binance.exceptions import BinanceAPIException
from binance.client import Client
def get_timestamp():
ts = time.time()
return datetime.datetime.fromtimestamp(ts).strftime('%Y-... |
'''
Created on Apr 19, 2015
@author: tristan
'''
import inspect
from sqlalchemy.orm.collections import InstrumentedList
def obj_map(src, dest, rules=None, mapper=None):
'''
dest could be 1) instance => copy the data to dest and return it
2) class => create a class instance, copy the data an... |
import csv
import hashlib
import inspect
import logging
from numbers import Number
from namespace import *
import codecs
import os
import petl as etl
import re
from loader.prefixes import PREFIX_LANGUAGE, PREFIX_MULTIMEDIA
from lxml import etree
from petl.util.base import Table
from rdflib import Literal, RDF, RDFS, ... |
def swap(arr, index_1, index_2):
temp = arr[index_1]
arr[index_1] = arr[index_2]
arr[index_2] = temp
def bubble_sort(arr):
for i in range(len(arr)):
# iterate through unplaced elements
for idx in range(len(arr) - i - 1):
if arr[idx] > arr[idx + 1]:
# swap ele... |
from bake import *
from scheme import *
from spire.schema import Schema
from spire.support.task import SpireTask
from spire.util import get_package_data
try:
import alembic
except ImportError:
alembic = None
else:
from alembic import command
class CreateSchema(SpireTask):
name = 'spire.schema.create'... |
import caffe
import scipy.io as sio
import os
import cv2
import numpy as np
import yaml
from multiprocessing import Process, Queue
import random
import h5py
import fast_rcnn.bbox_transform
from utils.cython_bbox import bbox_overlaps
import numpy as np
import utils.zl_utils as zl
import random
def bbox_transform_inv(b... |
# Generated by Django 3.1.2 on 2020-10-02 10:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('audiobook', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='audiobook',
old_name='file',
n... |
# Desenvolva um programa que leia as duas notas de um aluno,
# calcule e mostre a sua média.
not1 = float(input('Digite a nota 1: '))
not2 = float(input('Digite a nota 2: '))
média = (not1 + not2)/2
print('A média do aluno entre {} e {} será de {:.1f}'.format(not1, not2, média))
|
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
import sys
class Solution(object):
#accepted
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
... |
#!_PYTHONLOC
#
# (C) COPYRIGHT 2020 Ahasuerus
# ALL RIGHTS RESERVED
#
# The copyright notice above does not evidence any actual or
# intended publication of such source code.
#
# Version: $Revision: 477 $
# Date: $Date: 2019-12-01 20:16:10 -0500 (Sun, 01 Dec 2019) $
import string
import ... |
import logging
class PowerSourceItem:
def __init__(self, device_id, DeviceClass, device_instance=None):
self.device_id = device_id
self.DeviceClass = DeviceClass
self.capacity = None
self.load = 0.0
self.price = None
self.device_instance = device_instance
se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# file: extensions.py
# authors: jonathan kelley, anthony tarola
# ---
# license: the mit license
# 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... |
from django.contrib import admin
from .models import Cases
class Cases_Admin(admin.ModelAdmin):
readonly_fields = ('date_created','date_modified')
admin.site.register(Cases, Cases_Admin) |
# this is a virtual module that is entirely implemented server side
# 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 op... |
import torch
import torch.nn as nn
class SeqModel(nn.Module):
def __init__(
self,
embedding_size=200,
vocab_size=300,
output_size=5,
hidden_size=200,
num_layers=2,
nonlin="tanh",
dropout_rate=0.7,
mode=0,
unit="lstm",
more_feat... |
# https://leetcode.com/problems/binary-tree-maximum-path-sum/
#
# algorithms
# Hard (29.46%)
# Total Accepted: 177,254
# Total Submissions: 601,635
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Non... |
#!/usr/bin/env python
"""
Helper script to ingest generated data to a search index.
You must have access to a search index for this to work.
"""
import json
import globus_sdk
from login import load_tokens
import argparse
# 'cr3' index
INDEX = '11f4dbe5-1449-4d65-af83-72d322b117f3'
SEARCH_DATA = 'gmeta_ingest_doc.jso... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 15:25:20 2020
@author: babraham
"""
import json
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import pandas as pd
import pl... |
"""
Django settings for django_blog project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import o... |
from ruby.network.buffer.Encoder import Encoder
class Tests:
@staticmethod
def send(data):
encoder = Encoder()
message = encoder.encoder(data)
print(message)
pass |
import os
import unittest
from ....BaseTestCase import BaseTestCase
from kombi.Crawler import Crawler
from kombi.Crawler.PathHolder import PathHolder
from kombi.Crawler.Fs.Texture import TextureCrawler
class TextureCrawlerTest(BaseTestCase):
"""Test Texture crawler."""
__exrFile = os.path.join(BaseTestCase.da... |
def get_client(url):
from verta import Client
return Client(url)
|
from datetime import timedelta
from django_performance_testing.timing import TimeCollector
from freezegun import freeze_time
import pytest
from testapp.test_helpers import capture_result_collected
@pytest.mark.parametrize('seconds', [10, 5, 0.04])
def test_captures_and_measures_elapsed_time(seconds):
with capture... |
from enum import Enum, auto
# List of palettes to use. Remember to wrap the first + last colors!
class Palette(Enum):
Autumn = [
[0.00, [69, 21, 21]],
[0.33, [35, 25, 25]],
[0.67, [98, 58, 26]],
[1.00, [69, 21, 21]],
]
Beach = [
[0, [0,177,56]],
[0.25, [226,168,110]],
[0.5, [5,111,142... |
"""
BPJS Calculator
"""
class Bpjs:
""" BPJS Class """
def __init__(self, employee_information, configuration):
"""
Args:
employee_information (dictionary):
base_salary -- (Integer) Gaji Pokok
fixed_allowances -- (Integer) Tunjangan Tetap
... |
from crispy_forms.layout import Layout, HTML
from django.contrib import messages
from django.http import HttpResponseRedirect
from mezzanine.pages.page_processors import processor_for
from .forms import UpdateSQLiteLayout, SeriesSelectionLayout, TimeSeriesMetaDataLayout, \
UTCOffSetLayout, UTCOffSetForm
from hs_ap... |
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2016 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version... |
from queue import Queue, Empty, Full
import logging
logger = logging.getLogger(__name__)
#own classes
from networking import Connection
from networking import Message
from .router_base import RouterBase
class GroupRouter(RouterBase):
participating_in_groups = set()
def __init__(self, node_id, queue, rou... |
"""Circle package main functions."""
import math
import tkinter
def calculate_circumference(radius: float):
if radius < 0:
raise ValueError("Radius must be positive!")
return radius * 2 * math.pi
def calculate_area(radius: float):
if radius < 0:
raise ValueError("Radius must be positiv... |
from onmt.modules.Transformer.Models import TransformerEncoder, TransformerDecoder, Transformer
# For flake8 compatibility.
__all__ = [TransformerEncoder, TransformerDecoder, Transformer]
|
from multiprocessing import Process, Queue, Value
from yaml import load
import queue
import time
import sys
def mqtt_proc(q, mqtt_basetopic, mqtt_host, mqtt_port, mqtt_user, mqtt_pass):
import paho.mqtt.client as mqtt
def on_connect(mqttc, obj, flags, rc):
if rc == 0:
print("[+] MQTT conne... |
import serial
ser = serial.Serial('/dev/ttyACM1',9600)
ser.close()
ser.open()
while True:
data = ser.readline()
print(data.decode())
|
#!/usr/bin/python
#coding=utf-8
#desc: 休息一下,打开舒适音乐
#author:[email protected]
import webbrowser
import time
time.sleep(2)
webbrowser.open("https://www.youtube.com/watch?v=kRaJ_9FFzBQ") |
from unittest import TestCase
from src.core import get_message
class HelloworldTestCase(TestCase):
def test_helloworld(self):
self.assertEqual(get_message(), 'Hello World!')
|
import os # Integrates the programs or resources of the Operating System
print("#" * 60)
ip_or_host = input("Type the IP or host to be checked: ")
print("-" * 60)
os.system('ping -c 6 {}' .format(ip_or_host)) # -c -> Set limit to desire number of ping packets
print("-" * 60) |
# Copyright 2022, Lefebvre Dalloz Services
#
# 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 io_model
import numpy as np
from scipy import stats
import sequence
from statsmodels.formula.api import ols
from statsmodels.stats.anova import anova_lm
import torch
def get_loss(predictions, targets):
loss_function = torch.nn.BCELoss() # binary cross entropy
return loss_function(predictions, targets).i... |
import sqlite3 as sql
DB_PATH = "dispositivo.db"
def createDB():
conn = sql.connect(DB_PATH)
conn.commit()
conn.close()
def createTable():
conn = sql.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"""CREATE TABLE dispositivo (
id interger,
nombre_de_equipo text,
... |
import tkinter as tk
import widgets
import client
import struct
def update(conn, root, plot, ch0, ch1, prev_init):
data = conn.send_recv(0x01)
if data is None: return
fields = struct.unpack('>ffB', data)
print(fields)
if fields[2]:
if not prev_init:
plot.clear()
plot.put... |
from utils import test
def mergesort(l):
""" Implementation of the mergesort algorithm, not in-place
Sorts list l by the following steps:
1. Look at list l. If the length is less than 2 (either 1 or 0), return the
list, as it must be sorted.
2. If the list is longer than two, split it in half, an... |
from handlers import base_handlers
from models import User
class HandleLogin(base_handlers.BaseAction):
def handle_post(self, google_user):
user = User.query(ancestor=User.PARENT_KEY).filter(User.email == google_user.email().lower()).get()
if not user:
newUser = User(parent=User.PARENT... |
try:
from typing import Dict, List, Optional, Tuple
from integral_timber_joints.process import RFLPathPlanner, RobotClampAssemblyProcess
except:
pass
import itertools
from copy import deepcopy
from compas.geometry import Frame
from integral_timber_joints.assembly import Assembly, BeamAssemblyMethod
from ... |
from enum import Enum
import attr
class PgObjectType(Enum):
"""PostgreSQL object type."""
TABLE = 'TABLE'
SEQUENCE = 'SEQUENCE'
FUNCTION = 'FUNCTION'
LANGUAGE = 'LANGUAGE'
SCHEMA = 'SCHEMA'
DATABASE = 'DATABASE'
TABLESPACE = 'TABLESPACE'
TYPE = 'TYPE'
FOREIGN_DATA_WRAPPER = 'F... |
"""Changement objectif
Revision ID: b64307cd3c69
Revises: 39ed6dfe1eff
Create Date: 2021-07-22 14:55:56.245601
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b64307cd3c69'
down_revision = '39ed6dfe1eff'
branch_labels = None
depends_on = None
def upgrade():
... |
#!/usr/bin/env python
import os, sys, subprocess
is_master_commit = (
os.environ["GITHUB_REPOSITORY"] == "lihaoyi/mill" and
os.environ["GITHUB_REF"].endswith("/master")
)
if is_master_commit:
subprocess.check_call(sys.argv[1:])
|
class Solution:
"""
@param s: The first string
@param b: The second string
@return true or false
"""
def anagram(self, s, t):
# write your code here
return sorted(s) == sorted(t)
|
# -*- coding: utf-8 -*-
"""
(Description)
Created on Dec 20, 2013
"""
from ce1sus.db.classes.definitions import AttributeHandler
from ce1sus.db.common.broker import BrokerBase
__author__ = 'Weber Jean-Paul'
__email__ = '[email protected]'
__copyright__ = 'Copyright 2013, GOVCERT Luxembourg'
__license... |
# -*- coding: utf-8 -*-
import markdown
MD = markdown.Markdown(extensions=[
'markdown.extensions.fenced_code',
'markdown.extensions.codehilite',
])
class TagStripper(object):
def __init__(self, tag):
self._tag0 = '<{0}>'.format(tag)
self._tag1 = '</{0}>'.format(tag)
self._len_tag... |
def encryption(text,key):
result = ""
final=""
for i in range(len(text)):
word = text[i]
if (word.isupper()):
result += chr((ord(word) + key-65) % 26 + 65)
elif(word==" "):
result += " "
else:
result += chr((ord(word) + key - 97) % 26 + 97)... |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
#from avaliacao import views
from . import views
urlpatterns = patterns(views,
url('^$', views.index, name='home'),
) |
from django.db import models
class Payment(models.Model):
IDR = 'IDR'
USD = 'USD'
CURRENCY_CHOICES = (
(USD, 'USD'),
(IDR, 'IDR')
)
amount = models.DecimalField(decimal_places=2, max_digits=10)
currency = models.CharField(max_length=10, choices=CURRENCY_CHOICES)
|
$NetBSD: patch-myhdl___always__seq.py,v 1.1 2018/12/27 16:01:54 joerg Exp $
--- myhdl/_always_seq.py.orig 2018-12-25 21:39:40.951802739 +0000
+++ myhdl/_always_seq.py
@@ -45,7 +45,7 @@ _error.EmbeddedFunction = "embedded func
class ResetSignal(_Signal):
- def __init__(self, val, active, async):
+ def __init... |
import random
from typing import List
import hydra.utils
import torch
from torch import nn
import utils
from losses import SupConLoss
from nets import LinearClassifier
class Encoder(nn.Module):
def __init__(self, cfg):
super(Encoder, self).__init__()
self.cfg = cfg
self._encoders = nn.M... |
from django.urls import path
from partners import views
app_name = 'partners'
urlpatterns = [
path('', views.partners_list, name='partners_list'),
path('contractor/detail/<int:id>', views.contractor_detail, name='contractor_detail'),
path('contractor/add/', views.update_contractor, name='add_contractor'),... |
# Manel Ferré
# Busqueda de vulnerabilidades en el sistema operativo
# por fecha de hoy basado en vuls-control
# por versión, busca si la versión instalada es vulnerable
#from operator import truediv
import sys
#from sys import exit
from os import remove
from os import path
import argparse
# C... |
import sys, itertools
lines = [int(x) for x in sys.stdin.readlines()]
print(sum(lines))
seen = {0}
freq = 0
for l in itertools.cycle(lines):
freq += l
if freq in seen:
break
seen.add(freq)
print(freq)
|
import math
channel_bw = input("Enter the 5G Channel Bandwidth (MHz): ")
scs = input("Enter the Subcarrier Spacing (KHz): ")
mimo_layers = input("Enter the number of MIMO layers: ")
class prbs:
def __init__(self, channel_bw, scs) -> None:
self.channel_bw = channel_bw
self.scs = scs
|
# -*- coding: utf-8 -*-
import redis
from core import config
from core.datasources.movielens_source import MovieLensSource
from core.warehouse import FileWarehouse
""" Various global objects that can be loaded on demand"""
redis_conn = redis.StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)
_source = Mov... |
import requests
from celery_app.utils.utils import insert_vuln_db
from celery_app.config.config import web_port_short
#检测到 WEB-INF web.xml
plugin_id=63
default_port_list=web_port_short
def check(host, port=80):
scheme = 'https' if '443' in str(port) else 'http'
target = '{}://{}:{}'.format(scheme, host, por... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Create a mesh file with the number of vertical levels as nodal value
"""
from schimpy.schism_mesh import read_mesh, write_mesh
import numpy as np
def create_arg_parser():
""" Create an argument parser
"""
import argparse
description = ("Create a mesh f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.