content stringlengths 5 1.05M |
|---|
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def openalSoft():
http_archive(
name="openal_soft" ,
build_file="//bazel/deps/openal_soft:build.BUILD" ,
sha256="0... |
import time
import re
import requests
compounds = {
'Water': 'C7732185',
'Nitrogen': 'C7727379',
'Hydrogen': 'C1333740',
'Oxygen': 'C7782447',
'Carbon monoxide': 'C630080',
'Carbon dioxide': 'C124389',
'Methane': 'C74828',
'Ethane': 'C7... |
# 随机森林
import re
import time
import argparse
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
import joblib
import rasterio
from tqdm import tqdm
import os
import torch
from dataloaders.TileMLDatasets import TileMLTrainDataset
import utils
NUM_WORKERS = 4
CHIP_SIZE = 256
PADD... |
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from homepage.models import *
from manager import models as mmod
from . import templater
def process_request(request):
'''Get products from the DB'''
if request.urlparams[0] == 'all':
... |
import random, math
def poisson_random_number(lamb):
x = 0
p = math.exp(-1*float(lamb))
s = p
u = random.uniform(0,1)
while u > s:
x += 1
p = p*lamb/x
s = s + p
return x
def probability_threshold(lamb,prob):
vals = []
for i in range(0,10000):
vals.append(poisson_random_number(lamb))
v... |
from __future__ import absolute_import
import json
from django.conf import settings
from django.contrib.admin import ModelAdmin
from django.utils.encoding import force_text
from polymorphic.formsets import (
BasePolymorphicInlineFormSet, BaseGenericPolymorphicInlineFormSet)
from polymorphic.models import Polymorph... |
import time
import sys
from threading import Thread
from pymalloc import lots_of_allocs
def main():
start = time.time()
num_threads = int(sys.argv[1])
# If there's only one-thread, just run in main thread:
if num_threads == 1:
lots_of_allocs()
else:
threads = [Thread(target=lots_o... |
from typing import Optional, List, Union
from pydantic import BaseModel
from telegraph_api.models import Node
class Page(BaseModel):
""" PyDantic model for telegra.ph Page """
path: str
""" Path to the page. """
url: str
""" URL of the page. """
title: str
""" Title of the page. """
... |
import pytest
import sqlalchemy
import zope.sqlalchemy
import sample.application
import sample.scripts.database
@pytest.fixture(scope='session')
def _sqlite_setting():
return 'sqlite:///test.sqlite3'
@pytest.fixture(scope='session')
def _recreate_database():
sample.scripts.database._recreate(
'test... |
import json
from pony import orm
db = orm.Database()
from .meme import Meme
from .image import Image
from .question import Question
with open('config/db.json') as f:
config = json.load(f)
db.bind(provider='postgres',
user=config['user'],
password=config['password'],
host=... |
# naiveBayes.py
# -------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (kle... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
TITLE_CHOICES = (
('MR', 'Mr.'),
)
class Contact(models.Model):
name = models.CharField(_('name'), max_length=150)
email = models.EmailField(_('email'), max_length=255)
subject = models.CharField(_('subject'), max_len... |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
created by Fangyang on Time:2019/11/10
'''
__author__ = 'Fangyang'
import sys
from PyQt5.QtWidgets import (
QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QApplication
)
class Example(QWidget):
def __init__(self):
super().__init__()
self.in... |
import datetime
import os
import re
import requests
import xml.etree.ElementTree as ET
from flask import Flask
from flask import g
from flask import make_response
from flask import render_template
from flask import request
from flask import url_for
from flask import jsonify
from flask import send_file
from flask.ext.s... |
import time
import hug
from hug_explainable import explainable_toggle
@hug.get()
def my_endpoint(hug_timer, explain: explainable_toggle=explainable_toggle(False)):
results = {'took': hug_timer}
with explain('Sleeping for allocated time:', 1):
time.sleep(1)
explain.explained(results)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
BACpypes PCI Testing
--------------------
"""
import unittest
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.comm import PCI
# some debugging
_debug = 0
_log = ModuleLogger(globals())
@bacpypes_debugging
class TestPCI(unittest.TestCa... |
from os import listdir
from xml.etree import ElementTree
from numpy import zeros
from numpy import asarray
from mrcnn.utils import Dataset
from mrcnn.config import Config
from mrcnn.model import MaskRCNN
categories = ['D00', 'D10', 'D20', 'D40']
# class that defines and loads the kangaroo dataset
class KangarooData... |
import typing
import httpx
import pytest
pytestmark = pytest.mark.asyncio
@pytest.mark.parametrize(
"start_url, urls",
[
pytest.param(
"http://florimondmanca.com",
[("http://florimond.dev/", 301)],
id="home",
),
pytest.param(
"http://bl... |
pyvista.global_theme.color = 'red'
pyvista.global_theme.background = 'white'
pyvista.global_theme.axes.show = False
|
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# Time: O(log n); Space: O(1)
def search_insert(nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
high = mid - 1
else:
low = mid + 1
return... |
# -*- coding:utf-8 -*-
import datetime
import logging.config
import os
import time
from flask import Flask, send_from_directory, g, request, Response, Blueprint
from flask_restplus import Api, Namespace
from werkzeug.exceptions import default_exceptions, HTTPException
from werkzeug.utils import find_modules, import_st... |
"""
This module exports types and functions used for ``SELECT`` queries.
Main purpose is providing a type which contains information of selecting columns,
i.e. which columns are selected and how they are expressed in the query.
Using the same instance of the type in both of query genration and reading results ena... |
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import pickle
dataset = pd.read_csv(r'C:\Users\user\Desktop\Machine Learning\Iris\Iris.csv')
df = pd.DataFrame(dataset)
categories = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
for i in range(df.shape[0]):
df.iloc[i, ... |
from bfstpw.models import ForumThread, ForumPost
from datetime import datetime
from django.conf import settings
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.http import HttpResponseRedirect
from django.shortcuts import render, ge... |
# inspired by https://www.codementor.io/mustafakharnoub/teach-your-kids-to-build-their-own-game-with-python-1-10vphy48to
import turtle
pen = turtle.Turtle()
pen.pendown()
for side in range(3):
pen.forward(100)
pen.right(90)
pen.forward(100)
player = turtle.Turtle()
player.shape("circle") # choices: arrow turtle... |
"""
fxpmath
---
A python library for fractional fixed-point arithmetic.
---
This software is provided under MIT License:
MIT License
Copyright (c) 2020 Franco, francof2a
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software... |
import os
import tweepy
import tweetPublish
# authorization tokens
consumer_key = os.environ['twitter_api_key']
consumer_secret = os.environ['twitter_api_secret_key']
access_key = os.environ['twitter_access_token']
access_secret = os.environ['twitter_access_token_secret']
# StreamListener class inherits from tweepy.... |
def addTextToImage(img, bits, txt, debug):
replaceIndex = 7 - bits
counter = 0
if debug: print('Applying changes on {} bit'.format(replaceIndex))
for x in range(0, img.shape[0]):
for y in range(0, img.shape[1]):
for z in range(0, img.shape[2]):
if counter >= len(t... |
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root
OUTPUT_DIR = os.path.join(ROOT_DIR, "output")
TEST_OUTPUT_DIR = os.path.join(ROOT_DIR, "tests", "output")
TEST_RESOURCES = os.path.join(ROOT_DIR, "tests", "resources")
TEST_RESPONSES = os.path.join(ROOT_DIR, "tests", "resource... |
from src.command.command import Command
from src.error import DnfVariableNotfound
class DnfConfigManager(Command):
"""
Interface for `dnf config-manager`
"""
def __init__(self, retries: int):
super().__init__('dnf', retries)
def add_repo(self, repo: str):
self.run(['config-manage... |
import setuptools
setuptools.setup(
name="pytest-run-changed",
version="1.0.1",
url="https://github.com/moser/pytest-run-changed",
author="Martin Vielsmaier",
author_email="moser@moserei.de",
description="Pytest plugin that runs changed tests only",
long_description=open("README.md").read()... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------
# Filename: cross_correlation.py
# Author: Moritz Beyreuther, Tobias Megies, Tom Eulenfeld
# Email: megies@geophysik.uni-muenchen.de
#
# Copyright (C) 2008-2016 Moritz Beyreuther, Tobias Megies, Tom ... |
###ExonAnalyze_module
#Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - nsalomonis@gmail.com
#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... |
# -*- coding: utf-8 -*-
EMBEDDING_DIM = 18
HIDDEN_SIZE = 18 * 2
ATTENTION_SIZE = 18 * 2
POS_EMBEDDING_DIM = 2
# train.py
model_type='TGIN'
data_path='dataset'
dataset='electronics'
tri_data='wnd3_alpha_01_theta_09_tri_num_10'
n_tri=10
batch_size=128
maxlen=10
test_iter=100
save_iter=100
# model.py
n_neg = 5
use_di... |
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Iterator, List, Optional, Tuple
import gevent
from rotkehlchen.accounting.constants import FREE_PNL_EVENTS_LIMIT
from rotkehlchen.accounting.export.csv import CSVExporter
from rotkehlchen.accounting.mixins.event import AccountingEventMixi... |
from collections import Counter
import numpy as np
import json
import numpy
def voting_choicer(tok_map, labels):
label = []
prev_idx = 0
for origin_idx in tok_map:
votes = []
for l in labels[prev_idx:origin_idx]:
if l != "X":
votes.append(l)
vote_labels ... |
"""Allows the user to run the geopyspark script from its source directory."""
from geopyspark.command.configuration import main
if __name__ == "__main__":
main()
|
# Copyright 2020 Google LLC
#
# 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, ... |
import re
import numpy as np
def parse_data():
with open('2021/05/input.txt') as f:
data = f.read()
return [
((int(x1), int(y1)), (int(x2), int(y2)))
for x1, y1, x2, y2 in re.findall(r"(\d+),(\d+) -> (\d+),(\d+)", data)
]
def draw_line(field, x1, y1, x2, y2):
if abs(x2 - x1... |
# cloud_utils.py
#
# Contributing authors: Daniel Clark, Steve Giavasis, 2015
'''
'''
def pull_S3_sublist(yaml_outpath, img_type, cfg_file):
# function example use:
#
# yamlpath = os.path.join(os.getcwd(), "s3dict.yml")
#
# # Build entire filepath dictionary from S3
# s3_dict_yml = pull_S3_su... |
# 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
# d... |
#!/usr/bin/env python
# basic_alarm_a.py
"""
Copyright (c) 2015 ContinuumBridge Limited
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights... |
import time
import numpy as np
import argparse
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as Functional
import torch.utils.data as Data
from torch.autograd import Variable
import model
import dataset
import lossfunction
if __name__ == '__main__':
parser = argparse.ArgumentParser()
p... |
import argparse
import ixmp
def config():
# construct cli
parser = argparse.ArgumentParser()
db_config_path = 'Set default directory for database connection ' + \
'and configuration files.'
parser.add_argument('--db_config_path', help=db_config_path, default=None)
default_dbprops_file = '... |
from ahgl.api.models import CarouselItem
from rest_framework import serializers
from tournaments.models import ACTIVE_TOURNAMENT_STATUS
class CarouselItemSerializer(serializers.HyperlinkedModelSerializer):
tournaments = serializers.SerializerMethodField('get_tournaments')
class Meta:
model = Carouse... |
import argparse
import torch
import os
import imageio
from models.model import Generator
from utils import load_gen, get_random_noise, show_batch, latent_space_interpolation_sequence
import torch.nn.functional as F
from config import cfg
def parse_args():
parser = argparse.ArgumentParser(description='AnimeFace-DC... |
import os
import pytest
import sys
try:
import pymake
except:
msg = "Error. Pymake package is not available.\n"
msg += "Try installing using the following command:\n"
msg += " pip install https://github.com/modflowpy/pymake/zipball/master"
raise Exception(msg)
try:
import flopy
except:
msg... |
# Generated by Django 2.2.10 on 2020-04-30 17:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='AuthorizedUsers',
new_name='AuthorizedUser',
... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2017, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistri... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-02 14:08
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('teams', '0010_remove_team_members'),
]
operations = [
migrations.RenameField(
... |
"""Module containing the specific Transient Analysis Solution class."""
from ansys.dpf.post.dpf_solution import DpfMecanicSolution, DpfThermalSolution
class TransientAnalysisSolution(DpfMecanicSolution):
"""Transient solution class, which will provide all the API for Transient analysis."""
class ThermalTransie... |
# %%
# csv: https://docs.python.org/3/library/csv.html
# importando módulo csv
import csv
# %%
# leyendo archivo csv
with open("datasets/googleplaystore.csv", encoding='utf-8') as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ',')
for linea_csv in csv_reader:
print(linea_csv)
# %%
# leyendo ... |
# -*- coding: UTF-8 -*-
# Code generated by lark suite oapi sdk gen
from typing import Callable
from ....config import Config
from ....context import Context
from ....event.event import set_event_callback
from .model import *
class MeetingRoomStatusChangedEventHandler(object):
def __init__(self, callback):
... |
import asyncio
from ssdaq.core.receiver_server import ReceiverServer
from .mon_sender import ReceiverMonSender
from ssdaq.data import TelData
from ssdaq.core.utils import get_utc_timestamp
import MySQLdb
import os
class TelDataReceiver(ReceiverServer):
def __init__(
self, ip: str, port: int, publishers: l... |
# MIT License
#
# Copyright (c) 2017 Satellogic SA
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... |
from LambdaPage import LambdaPage, S3LambdaPageCache
def hello(event):
return 200, '{"message": "hello world"}'
def lambda_handler(event, context):
cache = S3LambdaPageCache(bucket='lambda-page-cache-example', max_age=300) # be sure this S3 bucket exists
page = LambdaPage(cache=cache)
page.add_endp... |
# -*- coding: utf8- -*-
import unittest
import sys
from androguard.core import mutf8
from androguard.core.bytecodes import dvm
from androguard.core.analysis import analysis
class StringTest(unittest.TestCase):
def testDex(self):
with open("examples/tests/StringTests.dex", "rb") as fd:
d = d... |
import os
from typing import Iterable, List, Union
import numpy as np
from absl import logging
def try_register_config_dir(key, path):
"""
Attempt to regiester a configuration directory or warn if failed.
e.g. kblocks/configs/__init__.py calls
`try_register_config_dir("KB_CONFIG", KB_CONFIG_DIR)`
... |
from datetime import timedelta
from functools import update_wrapper
from flask import make_response, current_app, request, url_for, jsonify
import uuid
# decorators
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
... |
# Copyright 2020 Jim Bosch
#
# 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 conditions and the following disclaimer.
#
# 2. ... |
#!/usr/bin/env python3
"""
abstraction of a boolean enumeration problem. such problems are meant to get a
single character's value in a blind system such as a blind SQLi injection.
* wanted_data_coordinates is a tuple defining the /coordinates/ of data we want
(bound to implementation of the connector). For example ... |
"""User-defined widgets."""
from PySide2 import QtWidgets, QtCore
class ClickableLineEdit(QtWidgets.QLineEdit):
"""LineEdit widget that sends a signal when clicked on it."""
clicked = QtCore.Signal()
def __init__(self, parent):
super().__init__(parent)
def mousePressEvent(self, event):
... |
#!/bin/env python
#
"""
@FILENAME@
Author: "@AUTHOR@" <@EMAIL@>
Date: @DATE@
"""
def main(args):
pass
@CURSOR@
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
#!/usr/bin/env python
#
# Copyright 2007 Doug Hellmann.
#
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and tha... |
from django.urls import path
from .views import (
PostListView,
PostCreateView,
PostUpdateView,
PostDeleteView,
PostLikesToggle,
UserPostListView,
CommentDeleteView
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>', ... |
'''
Leia 2 valores inteiros (A e B). Após, o programa deve mostrar uma mensagem "Sao Multiplos" ou "Nao sao Multiplos",
indicando se os valores lidos são múltiplos entre si.
Entrada
A entrada contém valores inteiros.
Saída
A saída deve conter uma das mensagens conforme descrito acima.
Exemplo de Entrada Exemplo de Saíd... |
# coding: utf-8
"""
functools.partial()を利用した「関数の部分適用」についてのサンプルです。
"""
import functools
from trypython.common.commoncls import SampleBase
from trypython.common.commonfunc import pr
class Sample(SampleBase):
def exec(self):
#
# 通常の関数呼び出し
#
func01('hello world', 'func01')
#... |
import Orange
import matplotlib.pyplot as plt
y = input('provide labeled ratio: (85 - 90 - 975 - super) ')
if y == '85':
names = ["Co(Extra,GBC)","Co(NB,GBC)","Co(NB,Extra)","Co(RF,GBC)","Co(Extra,RF)","Co(GBC,GBC)","Co(GBC,Extra)","Co(RF,Extra)","Self(Extra)","CoForest"]
avranks = [6.2875, 7.2625, 7.325, ... |
import pandas as pd
import os
base_path = os.path.join("full_datasets", "reddit_jokes", "reddit_cleaning")
train = pd.read_csv(os.path.join(base_path, "output/train.csv"), encoding="utf-8")
dev = pd.read_csv(os.path.join(base_path, "output/dev.csv"), encoding="utf-8")
test = pd.read_csv(os.path.join(base_path, "output... |
"""
Menu Validator.
This module provides validator for menu data.
"""
from typing import Any
from project.utils import validation_utils
def validate_save_data(form_data: dict[str, Any]) -> None:
"""
Validate page insert data.
"""
validation_utils.validate_form_data_fields(
form_data,
... |
from django.shortcuts import render, get_object_or_404
def get_redirected(queryset_or_class, lookups, validators):
"""
Calls get_object_or_404 and conditionally builds redirect URL
"""
obj = get_object_or_404(queryset_or_class, **lookups)
for key, value in validators.items():
if value != g... |
import sys,os
from numpy import *
from subprocess import *
from glob import glob
doResume=1
showisq=1
showlen=0
rdelete=1
fixmasks=1
vmsFix=lambda wholeFile: '\\;'.join(wholeFile.split(';'))
megsize=lambda fileName: os.path.getsize(fileName)/1e6
if len(sys.argv)<2:
for rt,drs,files in os.walk(os.getcwd(),topdown=Fals... |
class OverviewPageTemplates:
activities_list_section_title = "Activities list"
activities_list_table = (
"{|class='wikitable sortable'\n"
"|-\n"
'! scope="col" | Organisation\n'
'! scope="col" | Platform\n'
"|-\n"
"|}\n"
)
oeg_page = "Organised_Editing/Act... |
from datetime import datetime
import re
from argparse import Namespace, ArgumentParser
from os.path import join
from typing import Optional, Sequence, Dict
from luh3417.luhfs import Location, parse_location
from luh3417.luhsql import create_from_source
from luh3417.restore import read_config
from luh3417.utils import ... |
from itertools import product
from typing import List, Optional, Dict, Tuple
from matplotlib.axes import Axes
from mpl_format.axes.axes_formatter import AxesFormatter
from mpl_format.text.text_utils import map_text, wrap_text
from pandas import Series, isnull, DataFrame, pivot_table, notnull
from probability.distribut... |
#!/usr/bin/env python3
#add a linear shift on elev2D based on lat
from pylib import *
#input
lats=[0, 27, 28, 32, 33, 90]
msl_shifts=[-0.25, -0.25, 0.0, 0.0, 0.56, 0.56]
#read grid and elev
if os.path.exists('../hgrid.npz'):
gd=loadz('../hgrid.npz').hgrid
else:
gd=read_schism_hgrid('../hgrid.gr3')
C=ReadNC('ele... |
import sys
from http.server import HTTPServer
from threading import Thread, current_thread
from http.server import BaseHTTPRequestHandler
class MultiThreadedHTTPServer(HTTPServer):
def process_request(self, request, client_address):
Thread(target=self.__request, args=(self.RequestHandlerClass, request, cl... |
import yaml
from jinja2 import Template
import os
from jsonrpclib import Server
import time
username = "arista"
password = "arista"
# Devices inventory
inventory_f=open('inventory.yml', 'r')
inventory_s=inventory_f.read()
inventory_f.close()
inventory=yaml.load(inventory_s, Loader=yaml.FullLoader)
# Printing some ... |
from .version import __version__
from . import numpy
from . import jax
|
import os
import pandas as pd
import time
from surprise import Dataset, KNNBaseline, Reader
from surprise.model_selection import cross_validate
import random
class KNNbase_Unlearning():
def __init__(self, shuffle=False, shards=1):
# self.user_total_num = 943
if shards <= 0:
print('sha... |
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
while True:
msg = socket.recv()
timeStr = str(time.time())
socket.send(timeStr)
|
machine = [{'s': (0, 'Выдать сдачу 0 р'), '1': (1, 'Приняты деньги'), '2': (2, 'Приняты деньги'), '5': (0, 'Выдать шоколадку')},
{'s': (0, 'Выдать сдачу 1 р'), '1': (2, 'Приняты деньги'), '2': (3, 'Приняты деньги'), '5': (1, 'Выдать шоколадку')},
{'s': (0, 'Выдать сдачу 2 р'), '1': (3, 'Приняты де... |
import sys
import multiprocessing
from src.console import Console
from nve_server import NVEServer
def server_run(device_ip = sys.argv[1], subnet = sys.argv[2]):
server = NVEServer(sys.argv[1], sys.argv[2])
server.start()
server = multiprocessing.Process(target=server_run)
console = |
# dd_models.py - Distance distribtion parametric models
# ---------------------------------------------------------------------------
# This file is a part of DeerLab. License is MIT (see LICENSE.md).
# Copyright(c) 2019-2021: Luis Fabregas, Stefan Stoll and other contributors.
import inspect
import numpy as np
impo... |
from .q_learner import QLearner
from .coma_learner import COMALearner
from .qtran_learner import QLearner as QTranLearner
from .policy_gradient_v1 import PGLearner_v1
from .policy_gradient_v2 import PGLearner_v2
from .policy_gradient_v3 import PGLearner_v3
REGISTRY = {}
REGISTRY["q_learner"] = QLearner
REGISTRY["coma... |
# VirusShare.py
# download VirusShare hashes and search for specified hashes
# Author: Sent1ent
# Version: 1.0
# Date: February 22nd, 2016
import argparse
import os
import time
from urllib.request import urlopen
def downloader(directory, iteration):
# Downloads given URL
url = 'https://virusshare.com/hashes/VirusS... |
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
# Find the total sum of all root-to-leaf numbers.
# For example,
# 1
# / \
# 2 3
# The root-to-leaf path 1->2 represents ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '360RAT_windows_dark_small.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 i... |
'''
This file runs the python implementation of the DFA and returns whether the string was accepted or not
'''
import dfa, state, sys
from termcolor import colored
def main(string) -> bool:
# empty list of states
states = []
# q0 (start state)
state1 = state.State()
state1.toggle_sta... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
# coding=utf-8
import datetime
import inspect
from io import StringIO
from unittest.mock import patch
import django.dispatch
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.management import execute_from_command_line
from django.test... |
from binascii import unhexlify
class Beacon(object):
"""
Beacon Details
"""
def __init__(self, form):
self.beacon_name = form.get('name')
self.beacon_type = form.get('type')
self.status = form.get('status')
self.description = form.get('description')
self.indoor... |
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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... |
from django.views.generic.edit import FormView
from django.contrib.auth.forms import UserCreationForm
class RegisterFormView(FormView):
form_class = UserCreationForm
# Ссылка, на которую будет перенаправляться пользователь в случае успешной регистрации.
# В данном случае указана ссылка на страницу входа д... |
import shopify
from test.test_helper import TestCase
class TenderTransactionTest(TestCase):
def setUp(self):
super(TenderTransactionTest, self).setUp()
self.fake("tender_transactions", method="GET", body=self.load_fixture("tender_transactions"))
def test_should_load_all_tender_transactions(se... |
from __future__ import print_function
import numpy as np
import pandas as pd
import regreg.api as rr
import selection.tests.reports as reports
from selection.tests.flags import SET_SEED, SMALL_SAMPLES
from selection.tests.instance import logistic_instance, gaussian_instance
from selection.tests.decorators import (wai... |
from .asset import *
|
from flask import Flask, json
companies = [{"id": 1, "name": "Company One"}, {"id": 2, "name": "Company Two"}]
# initialize Flask
# create a Flask object, and assign it to the variable name api.
api = Flask(__name__)
# declare a route for endpoint.
# When a consumer visits /companies using a GET request, the list o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.