content stringlengths 5 1.05M |
|---|
def checkupdate():
import requests
from subprocess import Popen, PIPE
with open("babysploit/version", "r") as fwv:
data = fwv.read().replace(" ", "")
cv = requests.get("https://raw.githubusercontent.com/M4cs/BabySploit/master/babysploit/version").text.replace(" ", "")
if data == cv:
... |
import json
import paho.mqtt.client as mqtt
from flask import Flask, render_template, request
app = Flask(__name__)
mqtt_client = mqtt.Client('web-server')
mqtt_client.connect('192.168.1.110')
def on_publish(client, userdata, result):
print("Published data for alarm clock")
mqtt_client.on_publish = on_publish
... |
# ---------------------------------------------------------------------------------------------------------------------
# AoC 2021
# ---------------------------------------------------------------------------------------------------------------------
# 6.py
# ------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# Copyright 2019 Julian Betz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
from __future__ import annotations
try:
import zipp # nopycln: import
except ImportError:
import zipfile as zipp # noqa: F401, TC002
try:
from typing import Protocol # nopycln: import
except ImportError:
from typing_extensions import Protocol # noqa: F401, TC002
from poetry.core.semver.helpers i... |
projectFolder = 'F:/myProjects/tfKeras/UCSC/CMPS203/MLSQL/'
import logging, sys, math,os
import traceback
# currentFolder = os.path.abspath('')
# try:
# sys.path.remove(str(currentFolder))
# except ValueError: # Already removed
# pass
sys.path.append(str(projectFolder))
# logging.basicConfig(
# level = l... |
######################################
# Created on Jun 15, 2015
#
# @author: Grant Mercer
#
######################################
from Tkconstants import TOP, X, BOTH, BOTTOM, END, EXTENDED, LEFT
from Tkinter import Toplevel, Frame, StringVar, Label, Text, Button, Listbox
from constants import TAGS
from log.log impo... |
"""
ini doc
"""
__DOC__ = '''
Functions for Input/Output, especially reading specific types
of scientific data files.
'''
from .fileutils import (increment_filename, new_filename, new_dirname,
fix_filename, fix_varname, pathOf, unixpath,
winpath, nativepath, strip_quotes,... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
class LineAnimation:
def __init__(self, fig_name, x=None, y=None, **kwargs):
y = np.asarray(y)
if y.ndim != 2:
raise ValueError("y should be 2 dimensional array")
if x is None:
... |
#importing the libraries
import tensorflow as tf
import numpy as np
import pandas as pd
import json
import nltk
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.layers import Input, Embedding, LSTM , Dense,GlobalMaxPooling1D,Flatten
from tensorflow.keras.models import Model
import matp... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
"""Dumper for the Dataset 2 request.
MLRA
day precip total
day sm
day delivery
"""
|
########################################################################################
# This File is testing the program before adding it to the main.py just incase of bugs #
########################################################################################
from re import A
import webbrowser, os, pathlib, tim... |
import pickle as pkl
import unittest
from _orc_metadata import read_metadata, ORCReadException
TEST_CASES = [
'TestOrcFile.columnProjection',
'TestOrcFile.metaData',
'TestOrcFile.emptyFile',
'TestOrcFile.testMemoryManagementV11',
'TestOrcFile.testMemoryManagementV12',
'TestOrcFile.testPredicat... |
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import os
import unittest
from wolframclient.utils import six
# The evaluation modules is only supported on python 3.5+, because of asyncio
# We need to prevent the test suite from loading this module containing coroutines.
if si... |
import pyqtgraph as pg
from .__plotter__ import Plotter as _P
from .__plotter__ import SubPlot as _SP
from .__plotter__ import Addon as _A
from scipy import fft
import numpy as np
from PySide2 import QtCore,QtWidgets,QtGui
import pandas as pd
from scipy import signal
from pyqtgraph import functions as fn
from functools... |
import json
import requests
MAX_BLOCK = 99999999
def get_api_details() -> tuple:
with open("./data/config.json", mode="r", encoding="utf-8") as file:
config = json.load(file)
api_url = config["api"]["url"]
api_key = config["api"]["key"]
return api_url, api_key
def get_ingest_parameters()... |
# Copyright 2015, Avi Networks, 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 la... |
import discord
from discord.ext import commands
from datetime import datetime
import json
import tracemalloc
tracemalloc.start()
base_color=0x3498db
su_color=0x2ecc71
err_color=0xe74c3c
null_color=discord.Color.from_rgb(47,49,56)
class root(commands.Cog):
def __init__(self, Bot):
self.Bot = Bot
... |
######################################################################################################
from .pathes import get_path_of_main_function
from os.path import isfile
######################################################################################################
def check_for_text_image(string_name ... |
import re
from django.core.exceptions import ValidationError
from django.db import models
def validate_hex_color(color):
pattern = re.compile(r'^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$')
if not pattern.match(color):
raise ValidationError("Please provide valid hexadecimal color value")
return color
P... |
from collections import defaultdict
from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Tuple
from rotkehlchen.accounting.structures import Balance
from rotkehlchen.chain.ethereum.utils import decode_event_data
from rotkehlchen.constants.assets import A_ETH
from rotkehlchen.constants.ethereum import Ethereu... |
#!/usr/bin/env python
#TurtleBot must have minimal.launch & amcl_demo.launch running prior to starting this script.
import rospy
import argparse
import subprocess
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
import actionlib
from actionlib_msgs.msg import *
from geometry_msgs.msg import Pose, PoseWith... |
from __future__ import print_function
from django.core.management.base import BaseCommand
from wand.walker import findSnapshots
class Command(BaseCommand):
help = 'Lists the request or response snapshots'
def handle(self, *args, **options):
snapshots = findSnapshots('.')
print('\t', '\t'.joi... |
# -*- coding: utf-8 -*-
# Scrapy settings for meizi project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/t... |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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... |
#!/usr/bin/env python
import json
import sys
import urllib2
from collections import OrderedDict
from elementtree.SimpleXMLWriter import XMLWriter
ENGINE_QUERY = '''
{
"facets": {
"%(dimension)s": {
"topN": 1000,
"minCount": %(min_count)d,
"sortBy":"countDesc"
}
}
}
'''
ENGINE_URL = 'http... |
import os
import pymysql
from pymysql.cursors import DictCursor,SSDictCursor,SSCursor,Cursor
DEFAULT_OPT_FILE = "{}/.my.cnf".format(os.environ['HOME'])
class MySQLConnection:
def __init__(self, option_file=DEFAULT_OPT_FILE):
self.opt_file = option_file
self.connection = self.connection()
def connection(self... |
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import operator
"""Baby Names exercise
Define the extract_names() funct... |
#!/usr/bin/python3
import tkinter
from tkinter import *
window = tkinter.Tk()
menubar = Menu(window)
menu1 = Menu(menubar)
menu1.add_command(label="New")
menu1.add_separator()
menu1.add_command(label = "Exit", command = window.quit)
menubar.add_cascade(label = "Section 1", menu = menu1)
menu2 = Menu(menubar)
menu... |
"""
CoSaMP step by step
==========================
This example explains the step by step development of
CoSaMP (Compressive Sensing Matching Pursuit) algorithm
for sparse recovery. It then shows how to use the
official implementation of CoSaMP in ``CR-Sparse``.
The CoSaMP algorithm has following inputs:
* A sens... |
"""@xvdp
memory tools
current snapshots
GPUse() -> current cuda use # subprocess wrapper over
CPUse() -> current cpu use
decorator using nvml torch.cuda.memory_stat and torch.profiler.profile
@memory_profiler
"""
import subprocess as sp
import psutil
import numpy as np
import torch
import pynvml as nvml
if torch.__v... |
from flask.ext.testing import TestCase
from flask.ext.fillin import FormWrapper
from . import UserSessionTestCase
from dexter.models import Document, db
from tests.fixtures import dbfixture, DocumentData, UserData
class TestEditArticleAnalysis(UserSessionTestCase):
def setUp(self):
super(TestEditArticleA... |
m = int(input())
vv = 0
if 100 <= m <= 5000:
vv = m * 10 // 1000
elif 6000 <= m <= 30000:
vv = m // 1000 + 50
elif 35000 <= m <= 70000:
vv = (m // 1000 - 30) // 5 + 80
elif m > 70000:
vv = 89
print(str(vv).zfill(2))
|
'''
The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.
For example, Penny drinks the third can of cola and the queue will l... |
# -*- coding: utf-8 -*-
"""
src.api.event
~~~~~~~~~~~~~
Model definition for Event
Classes:
Event
"""
from src import db
from src.models import BaseDocument
class Event(BaseDocument):
name = db.StringField(unique=True, required=True)
date_time = db.DateTimeField(required=True)
... |
import filecmp
import os
import shutil
import sys
import tempfile
import unittest
from unittest.mock import patch
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from Bio.PDB import PDBParser, parse_pdb_header
from symmetryshift.cli import cli
from symmetryshift.create_biological_structure_unit import... |
# Given a set of ML pruned saddle points, remove outliers or keep only chessboard area
import numpy as np
import matplotlib.pyplot as plt
pts = np.array([[237, 332],
[242, 287],
[245, 263],
[247, 360],
[249, 337],
[252, 314],
[255, 290],
[257, 389],
[258, 266],
[260, 366],
[262, 342],
[268, 294],
[271, 26... |
"""Generates Tichu boards and renders them to pdf.
"""
import json
import random
class Color:
"""Type representing a Tichu suit (stars, falchions, pagodas or jades).
Attributes:
value: Integer. The color's ranking (1-4) for sorting purposes.
"""
def __init__(self, value):
self.value = value
class ... |
"""
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
"""
# Correct if the nums does not contain duplicated numbers
class Solution(object):
def firstMissingPositiv... |
from django.test import TestCase
# Create your tests here.
from hc.test import BaseTestCase
from django.contrib.auth.models import User
from .models import BlogPosts, BlogPostsCategory, Comment
from django.shortcuts import reverse
from django.utils import timezone
"""
All our tests will be in this file and fir... |
#Understand How to Convert DataType and what is function of type in python
birth_year=input("Birth Year: ")
print(type(birth_year))
age=2019-int(birth_year)
print(type(age))
print("YOUR AGE:")
print(age)
#ASK A USER TO THEIR WEIGHT(IN POUNDS),CONVERT IT TO KILOGRAMS AND PRINT ON THE TERMINAL.
weight=input("Ente... |
from com.im.lac.types import MoleculeObject, MoleculeObjectIterable
from com.im.lac.util import CloseableMoleculeObjectQueue
from java import lang
import sys
#Place the python module on the path
#sys.path.append('/lac/components/rdkit-camel/src/main/python')
from java.util import ArrayList
from find_props.find_props i... |
from helper_fns import *
import matplotlib.pyplot as plt
import numpy as np
data = []
for g in db.completed_games.find({"balance_code":"1.2", "p2c2":{"$exists":True}, "p1c2":{"$exists":True}}):
p1 = g["p1c1"][0] + g["p1c2"][0]
if chars.index(p1[0]) > chars.index(p1[1]):
p1 = p1[1]+p1[0]
p2 = g["p2... |
# -*- coding: utf-8 -*-
# (c) Copyright 2022 Sensirion AG, Switzerland
from sensirion_i2c_sen5x.response_types import Sen5xDeviceStatus
def test_zero():
obj = Sen5xDeviceStatus(0x00000000)
assert type(obj.value) is int
assert obj.value == 0
assert obj.flags == []
assert obj.fan_error is False
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import act_fn, print_values
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
""" ****************** Modified (Michael Klachko) PNN Implementation ******************* """
class Perturb... |
from django import forms
from django.forms import ModelForm
from departamento.models import Departamento
class RegisterDepartamento(forms.ModelForm):
class Meta():
model=Departamento
fields=["nombre","edificio"]
|
"""
TODO: Come back and get this working in the container
import subprocess
import pytest
import filecmp
def test_integration():
subprocess.run("python3 report_generator -file1 /Users/cameron/Documents/GitHub/report_generator/tests/integration/fixtures/students.csv -file1_cols fname lname cid -file2 /Users/cam... |
#!/usr/bin/env python3
#
# Licensed to you under the MIT license. See the LICENSE file in the
# project root for more information.
import copy
import os
import subprocess
import sys
from miktex.packaging.info import inifile
from miktex.packaging.info import md5
from miktex.packaging.info import texcatalo... |
#!/usr/bin/python3
"""
@Author : Zhaohui Mei(梅朝辉)
@Email : mzh.whut@gmail.com
@Time : 2018/11/16 20:52
@File : forms.py
@Version : 1.0
@Interpreter: Python3.6.2
@Software: PyCharm
@Description: 表单
"""
from flask_ckeditor import CKEditorField
from flask_wtf import FlaskForm
from wtforms impor... |
from hantext.hantext_model import hantext
from hantext.hantext_config import FLAGS
from utils.load_data_helper import load_pickle_data, load_meta_data, load_word_embeddings, load_label_embeddings
from metric.measure import measure_multi_label, measure_ex
import tensorflow as tf
from collections import OrderedDict
... |
#!/usr/bin/env python3
import pathlib
import pickle
from typing import Tuple
from loguru import logger
import numpy as np
import torch
from nqs_playground import *
# Fix random number generator seeds for reproducible runs
np.random.seed(1273982371)
torch.manual_seed(378549284)
manual_seed(5772842)
CURRENT_DIR = pa... |
class BaseExpression:
"""
Class representing a expression node in the AST of a MLP
"""
def __init__(self):
self.indice = -1
self.identifier = None
self.identifierName = None
self.identifierList = None
def getSymbol(self):
return self
def getSymbolName(se... |
# =========================================================================================
# Copyright 2015 Community Information Online Consortium (CIOC) and KCL Software Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... |
# -*- mode: python -*-
import sys
sys.setrecursionlimit(5000)
block_cipher = None
import pyautogui
import keyboard
import asyncio
import tkinter as tk
from tkinter import ttk
from tkinter import *
import threading
import multiprocessing
import time
import os
import psutil
global iteration
iteration = 0
def checkIf... |
from logging import getLogger
from numpy import isnan, array, where
from plotly.offline import plot
from scipy.stats import ttest_rel
from wonambi.trans import select
from copy import deepcopy
from collections import Mapping
lg = getLogger(__name__)
FONT = dict(
family='verdana',
size=9.34,
color='#000'... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 19 11:33:20 2017
Module for loading training corpus in different formats.
@author: Álvaro Barbero Jiménez
"""
import pandas as pd
import json
class Corpus:
"""Class representing a corpus of documents.
Behaves like an iterable of documen... |
#script to check if NeXML file includes MIAPA
|
"""This module contains the general information for HuuFirmwareUpdater ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import ImcVersion, MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class HuuFirmwareUpdaterConsts():
ADMIN_STATE_TRIGGER = "trigger"
ADMIN_STATE_TRIGGERED ... |
"""
SynthTIGER
Copyright (c) 2021-present NAVER Corp.
MIT license
"""
import imgaug.augmenters as iaa
import numpy as np
from synthtiger.components.component import Component
class CoarseDropout(Component):
def __init__(
self,
p=(0.05, 0.25),
size_px=None,
size_percent=None,
... |
import asyncio
import gc
from tsukino import Tsukino
Tsukino().run()
asyncio.set_event_loop(asyncio.new_event_loop())
print("Cleaning up... ", end='')
gc.collect()
print("Done.") |
weight=float(input('weight(kg): '))
height=float(input('height(meter): '))
bmi=weight/height**2
if bmi<18.5:
print('under weight')
elif bmi<25:
print('normal')
elif bmi<30:
print('over weight')
elif bmi<35:
print('obese')
else:
print('extremly obese')
|
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
vowels.sort()
# print vowels
print('Sorted list:', vowels)
# take second element for sort
def order_from_second_el(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
rand... |
#!/usr/bin/env python
import datetime
import os
import tornado.ioloop
import tornado.web
from tornado.httpserver import HTTPServer
import json
import database
import config
from custom_exceptions import *
def internal_error(self, e):
print e
self.set_status(500)
self.write('An internal error occurred.')
... |
import getpass
import json
import logging
import logging.config
import os
import sys
IS_WIN32_ENV = sys.platform == "win32"
def setup_logging(default_path=os.path.abspath(os.path.expanduser('~/.blitz-tui.json')), log_level="INFO"):
"""Setup logging configuration"""
path = default_path
if os.path.exists(p... |
import energiaCinetica as eC
import energiaPotencial as eP
import energiaTotal as eT
import raioOrbita as rO
import ComprimentoOndaTransição as cPT
import ComprimentoOndaTransicaoSerie as cPTS
import energiaFoton as eF
def getInputEnergy(n):
try:
value = float(n.replace(',','.'))
except Valu... |
from tracardi.service.storage.factory import storage_manager
async def load_by_profile(profile_id: str):
return await storage_manager('console-log').load_by("profile_id", profile_id)
async def load_by_event(event_id: str):
return await storage_manager('console-log').load_by("event_id", event_id)
|
numero = input("Digite um número: ")
print("Número invertido: ", numero[:: -1])
|
# -*- coding: utf-8 -*-
# Generated by Django 2.0.2 on 2018-02-16 11:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("woodcutter", "0008_auto_20180215_1618"),
]
operations = [
migrations.AddField(
model_name="gamelog",
... |
import discord
class Select(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.select(
placeholder="Please select one",
options=[
discord.SelectOption(label='no'),
discord.SelectOption(label='yes'),
discord.SelectOption... |
"""
Copyright 2013 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... |
"""Get publishers for STA-news files"""
import os
import xml.etree.ElementTree as ET
from collections import defaultdict
import pickle
def get_publishers(path):
ns = "{http://www.tei-c.org/ns/1.0}"
tree = ET.parse(path)
pubs = []
for publisher in tree.iter(ns + 'publisher'):
pubs.append(publi... |
import puzzleinput
import math
def rotate(x2, y2, degrees):
angle = math.radians(degrees)
cos = math.cos(angle)
sin = math.sin(angle)
x3 = cos * x2 - sin * y2
y3 = sin * x2 + cos * y2
return round(x3), round(y3)
x = 10
y = -1
traveled_x = 0
traveled_y = 0
for line in puzzleinput.lines:
a... |
from uuid import uuid4
import factory
import factory.django
from django.contrib.auth import get_user_model
import accounts.models
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: "testes-%s" % n)
password = factory.PostGenerationMethodCall("set_password", "testes")... |
# -*- coding: utf-8 -*-
# Copyright Hannah von Reth <vonreth@kde.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of condi... |
from .base import Trait
__version__ = "0.0.1"
__all__ = ("Trait",)
|
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
from numpy import array, log
from numpy.random import random
from pandas import DataFrame, read_hdf
import subprocess
from time import time, sleep
from os.path import isfile
import logging
from ... |
'''
Instructions for Hangman Game
-----------------------------------
'''
'''
Hello, and welcome to our Hangman Python Game! To play the game, just run it through the main file. For the actual game, you would play it how you would your typical Hangman game. In terms of the actual game translated to code, you will get ... |
from collections import deque
def bfs(V, edges):
waiting = deque()
done = [-1] * V
done[0] = 0
for n in edges[0]:
waiting.append([n, 0])
while len(waiting):
cur = waiting.popleft()
cur_node = cur[0]
cur_dist = cur[1]
if done[cur_node] == -1:
done... |
#!/usr/bin/env python3
import unittest
import subprocess as sub
from bin import sp_version
class TestSPVersion(unittest.TestCase):
def test_no_args(self):
output = sub.check_output(sp_version.__file__, timeout=10)
for line in output.stderr.read().decode('utf-8').splitlines():
print(lin... |
import csv
class report_selector(object):
def __init__(self):
self.report_list = {} #fill this dictionary with the headers in the CSV as dict keys
self.reports_to_run = []
def initalize_lists(self, infile):
with open(infile, 'rU') as csvfile: #open the MSAinputs file to create a dictionary with report names as ... |
"""
The pre-trained models produce embeddings of size 512 - 1024. However, when storing a large
number of embeddings, this requires quite a lot of memory / storage.
In this example, we convert float embeddings to binary hashes using binary passage retriever (BPR).
This significantly reduces the required memory / stora... |
from datetime import datetime, timezone
from typing import List
import yaml
class ConfigurationModel:
def __init__(self):
self.mongo_config: MongoConfigurationModel = None
self.sources: int = None
self.attributes: List[str] = None
self.measurements_in_block: int = None
self... |
import json
def main():
lines = []
for i in range(10):
with open("/home/qinyuan/zs/data/zsre/relation_splits/train.{}".format(i)) as fin:
lines += fin.readlines()
with open("/home/qinyuan/zs/data/zsre/relation_splits/dev.{}".format(i)) as fin:
lines += fin.readlines()
... |
from collections import namedtuple, OrderedDict
from ipaddress import ip_address
import pytest
import requests
from syncipy.syncipy import Syncipy
RequestsMockReponse = namedtuple('RequestResponse', ['text', 'raise_for_status'])
class RequestsMock():
def __init__(self, responses):
self.responses = resp... |
import pytest
import os
import uuid
import flask
from mock import patch
from snapshottest import snapshot
from lmsrvlabbook.tests.fixtures import fixture_working_dir_env_repo_scoped, fixture_working_dir
from gtmcore.inventory.inventory import InventoryManager
from gtmcore.dataset.io.manager import IOManager
from gtmc... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# !python -m venv .env
# !source .env/bin/activate
# !pip install transformers
# !pip install accelerate
# get_ipython().run_line_magic('load_ext', 'autoreload')
# get_ipython().run_line_magic('autoreload', '2')
# In[4]:
#!/usr/bin/env python
# coding=utf-8
# Copyrig... |
from Keys import *
import requests
BASE_URL = "http://127.0.0.1:5000"
Antrang = requests.get(f"{BASE_URL}/generate-keys").json()
Antrang_private = Antrang["private_key"]
Antrang_public = Antrang["public_key"]
Member = requests.get(f"{BASE_URL}/generate-keys").json()
Member_private = Member["private_key"]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Robot import Robot
# 全局变量
MAX_EPISODES = 500
MAX_EP_STEPS = 200
# 环境设置
robot = Robot()
# 学习方法
method = DDPG()
# 训练
for i in range(MAX_EPISODES):
# s = robot.render()
for j in range(MAX_EP_STEPS):
s = robot.reset()
|
from __future__ import annotations
import typing
import stringcase
from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
import hexa.plugins.connector_dhis2.models
from hexa.catalog.sync import DatasourceSyncResult
def _match_reference(
instance: hexa.plugins.connector_dhis2.models... |
#! env/bin/python3.6
# -*- coding: utf8 -*-
"""Инициализация пакета API версии 0."""
|
import tempfile
import pytest
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from django.core.files import File
from vr.server import models
from vr.server.tests import randurl
from vr.common.utils import randchars
pytestmark = pytest.mark.usefixtures('postgresql')
pytestmark = ... |
from django.test import TestCase
from mixer.backend.django import mixer
from articles.models import Article, Tag, Subscriber_request
from users.models import ArticlesUser
# Использование mixer pip install mixer
# Successfully installed mixer
# mixer http://klen.github.io/mixer.html
# 1 вариант Использования mixer
cla... |
import argparse
import json
import pprint
from collections import OrderedDict
import boto3
import pytest
from chili_pepper.main import CLI
from conftest import create_app_structure, create_chili_pepper_s3_bucket
@pytest.mark.parametrize("runtime", ["python2.7", "python3.6", "python3.7"])
def test_deploy(tmp_path, r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from . import http
def _param(param, value):
"""
create 'parameter=value'
"""
return "{0}={1}".format(param, value)
def _andparam(params):
"""
string join parameter list with &
"""
return "&".join(params)
def _query(char):
"""
... |
from skmultiflow.trees.variance_reduction_split_criterion \
import VarianceReductionSplitCriterion
import numpy as np
# This class extends VarianceReductionSplitCriterion since it just computes
# the SD differently than its Ancestor (considering multiple targets)
class IntraClusterVarianceReductionSplitCriterion(... |
word = input("Your Word: ")
i = 0
i1 = 0
index = len(word)//2
remainder_of_index = index % 2
if remainder_of_index == 0:
while i <= index:
if i == index:
word = word.replace(word[i], "", 1)
# break
i += 1
elif remainder_of_index == 1:
while i1 <= index:
if i1 ==... |
from .__init__ import *
def gen_func(maxd=100,
maxa=100,
maxn=100,
format='string'):
d = random.randint(-1 * maxd, maxd)
a1 = random.randint(-1 * maxa, maxa)
a2 = a1 + d
a3 = a2 + d
n = random.randint(4, maxn)
apString = str(a1) + ', ' + str(a2) + ', ' + ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Common Python library imports
# Pip package imports
from flask_admin import AdminIndexView as BaseAdminIndexView, expose
# Internal package imports
from ..security import AdminSecurityMixin
class AdminDashboardView(AdminSecurityMixin, BaseAdminIndexView):
@expose(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.