content stringlengths 5 1.05M |
|---|
from celery import Celery
from flask import render_template
from flask_mail import Message
import celery_conf
app = Celery(__name__)
#从配置文件拿到celery的配置文件
app.config_from_object(celery_conf)
# @app.tasks
# def send_email(reciver,url,u_id,mail, cache):
#
# msg = Message("欢迎注册爱鲜蜂后台管理",
# ... |
"""Contains the schemas for the tables in the database.
"""
from . import engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Boolean
Base = declarative_base()
class User(Base):
"""Represents the contents of the user table.
"""
__tablename__ = "user"
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-12 18:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks
import wagtailstreamfieldforms.blocks
class Migra... |
# count valid passwords according to company policy:
# i.e. given a list of strings in the form "policy char: password"
# does the password contain a number of the characters char that fall within the bounds of the policy
# for example:
# 1-3 a: abcde is *valid* because the password contains 1 'a' (between 1... |
import os
from pint import UnitRegistry
# load up the registry to be used everywhere
ureg = UnitRegistry()
# add currency as a type of unit since it is not part of the default
ureg.define('usd = [currency]')
Q_ = ureg.Quantity
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
CREDIT = "CREDIT"
CHECKING = "CHECK... |
from sqlalchemy import (create_engine, Column, Integer, MetaData,
select, String, Table)
meta = MetaData()
artists = Table('artists', meta,
Column('ArtistId', Integer, primary_key=True),
Column('Name', String)
)
DATABASE_FILE = 'sqlalchemy.db'
d... |
from typing import Union, List, Callable, Any, Iterable
from collections import OrderedDict
from .interact_in import InteractIn
from .interact_out import InteractOut
from ..defaults import INTERACT_SUBDOMAIN
class BaseInteract:
def __init__(self):
self.id = None
self.inputs_args = None
se... |
#!/usr/bin/env python3
"""
License statement applies to this file (glgen.py) only.
"""
"""
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 limit... |
import torch.nn as nn
from torch.autograd import Variable
import torch
from immediate_sensitivity_primitives import grad_immediate_sensitivity
import numpy as np
# returns counts rather than counts over thresh
def merlin(model, inputs, labels, lf):
if type(inputs) == np.ndarray:
inputs = torch.from_numpy... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-01 12:35
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import Q
def update_caches(apps, schema_editor):
from wagtail_svgmap.models import ImageMap
for image_map in ImageMap.objects.filter(Q... |
from discrete_world.space import infiniteTimeSpace
from discrete_world.mdp import infiniteTime
from utilities.counters import Timer
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib as mpl
from matplotlib.colors import ListedColormap,LinearSegmentedColormap
from utilities.utilities import nor... |
import json
from io import StringIO
import pytest
from django.core.management import call_command
from node.core.utils.cryptography import get_node_identifier
@pytest.mark.usefixtures('rich_blockchain')
def test_list_nodes(test_server_address, force_smart_mocked_node_client):
out = StringIO()
call_command('... |
from multimodal.image_analysis import ImageAnalysisCache
IMAGE_ANALYSIS_CACHE = ImageAnalysisCache.load()
|
def twoPolygons(p1, p2):
def doubleSquare(polygon):
square = 0
for i in range(len(polygon)):
a = polygon[i]
b = polygon[(i + 1) % len(polygon)]
square += a[0] * b[1] - a[1] * b[0]
return square
return doubleSquare(p1) == doubleSquare(p2)
|
from contextlib import contextmanager
import itertools
import json
import os
import signal
from typing import Dict, List, Union, Undefined, Any, Tuple
from .exceptions import AdamaError
def location_of(filename):
return os.path.dirname(os.path.abspath(filename))
def interleave(a, b):
""" '+', [1,2,3] -> [... |
import psycopg2
dbname = 'vvqfwreu'
user = 'vvqfwreu'
password = 'x2V1_pasp_QsYLoNKDjsAUyUyRV1WDui'
host = 'ruby.db.elephantsql.com'
pg_conn = psycopg2.connect(dbname = dbname, user = user,
password = password, host = host)
pg_curs = pg_conn.cursor()
create_table_statement = """
CREAT... |
# To import required modules:
import numpy as np
import time
import os
import sys
import matplotlib
import matplotlib.cm as cm #for color maps
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec #for specifying plot attributes
from matplotlib import ticker #for setting contour plots to log scale
im... |
#! /usr/bin/env python
usage = """%prog Version of 26th May 2010
(c) Mark Johnson
Extracts a grammar from a CHILDES file
usage: %prog [options]"""
import optparse, re, sys
import lx, tb
def read_childes(inf):
"""Reads a CHILDES file, and yields a dictionary for each record
with key-value pa... |
"""
Copyright 2019 Samsung SDS
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 applic... |
# The network config (links to the net) we use for our simulation
sumoConfig = "A9_conf.sumocfg"
# The network net we use for our simulation
sumoNet = "A9.net.xml"
mqttUpdates = False
mqttHost = "localhost"
mqttPort = "1883"
# should it use kafka for config changes & publishing data (else it uses json file)
kafkaUpd... |
print long
print long(3.0)
print long(3)
print type(long(3.0))
print type(long(3))
|
import csv
import os
filename = input("what is the name of the exported CSV file: ")
print(filename)
with open(filename,'r') as f:
reader = csv.reader(f)
next(f)
next(f)
for row in reader:
date = row[0]
hour = row[2]
minute = row[3]
level = row[4]
levelText = row[... |
import numpy as np
import xlearn as xl
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load dataset
iris_data = load_iris()
X = iris_data['data']
y = (iris_data['target'] == 2)
X_train, \
X_val, \
y_train, \
y_val = train_test_split(X, y, test_size=0.3, random_sta... |
import click
from . import wrapboto
from .config import read_config
from .commands import config, cluster, apply, create, update, delete, describe, get, logs, stop, top
from .colorize import HelpColorsGroup
@click.group(cls=HelpColorsGroup)
@click.pass_context
def cli(ctx):
aws_credentials = {}
for k, v in ... |
import torch
import torch.nn as nn
class DQN(nn.Module):
def __init__(self, width, input_dim, output_dim, path=None, checkpoint=1):
super(DQN, self).__init__()
self._input_dim = input_dim
self._output_dim = output_dim
self._width = width
self.model_definition()
i... |
import Classes.DType as Type
import config
from Assembly.CodeBlocks import (createFloatConstant, createIntrinsicConstant,
createStringConstant, extra_parameterlabel,
functionlabel, fncall)
from Assembly.Registers import (norm_parameter_registers,
... |
import random
from impbot.core import base
from impbot.handlers import command
class RouletteHandler(command.CommandHandler):
def run_roulette(self, message: base.Message, points: int) -> str:
starting_points = int(self.data.get(message.user.name, default="0"))
if starting_points < points:
... |
"""Test asyncpraw.models.front."""
from .. import IntegrationTest
class TestFront(IntegrationTest):
async def test_best(self):
with self.use_cassette():
submissions = await self.async_list(self.reddit.front.best())
assert len(submissions) == 100
async def test_controversial(self):... |
import math
from distutils.version import LooseVersion
import numpy
import pytest
import scipy
import sympy
from mpmath import mp
import orthopy
import quadpy
def test_golub_welsch(tol=1.0e-14):
"""Test the custom Gauss generator with the weight function x**2.
"""
alpha = 2.0
# Get the moment corre... |
test = { 'name': 'q1_6',
'points': 2,
'suites': [ { 'cases': [ { 'code': '>>> '
'len(simulation_results_without_jokers)\n'
'100000',
'hidden': False,
... |
from entity import Item
from tool4time import get_timestamp_from_str, is_work_time, now_stamp, get_datetime_from_str, now
def todo_item_key(item: Item):
value = get_timestamp_from_str(item.create_time)
day_second = 60 * 60 * 24
if item.work:
# 如果处于工作时间段, 则相应时间段的任务相当于30天后提交的任务
# 否则相当于30天以前提... |
"""
Copyright 2019 Skyscanner 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 in writing, software dis... |
import requests
from flask import request, url_for
from ..core import server
URL_JOONYOUNG = 'https://hooks.slack.com/services/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'
class Field():
title = ''
value = ''
short = False
def __init__(self, title='', value='', short=False):
self.title = ... |
#!/usr/bin/env python
#coding:utf-8
# Created: 15.11.2010
# Copyright (C) 2010, Manfred Moitzi
# License: MIT License
__author__ = "mozman <mozman@gmx.at>"
import unittest
from dxfwrite.dimlines import _DimStyle
class TestDimStyle(unittest.TestCase):
def test_get_value(self):
style = _DimStyle('test', l... |
# -*- coding: utf-8 -*-
#@+leo-ver=5-thin
#@+node:ekr.20201129023817.1: * @file leoTest2.py
#@@first
"""
Support for Leo's new unit tests, contained in leo/unittests/test_*.py.
Run these tests using unittest or pytest from the command line.
See g.run_unit_tests and g.run_coverage_tests.
This file also contains classe... |
# # Sample Data
# servers_memory = [
# 32, 32, 32, 16
# ]
# servers_cpu = [
# 10, 12, 8, 12
# ]
# tasks_memory = [
# 4, 8, 12, 16, 2,
# 8, 16, 10, 4, 8
# ]
# tasks_cpu = [
# 2, 4, 12, 8, 1,
# 2, 4, 4, 2, 2
# ]
# task_anti_affinity = [(1, 4), (3, 7), (3, 4), (6, 8)]
if __name__ == "__main__"... |
#!/bin/env python3
# -*- coding: utf-8 -*-
# This little script gets XML data from CPTEC / INPE (Forecast Center
# of Time and Climate Studies of the National Institute for Space Research)
# for Brazilian cities and print the result at the terminal.
import urllib.request
import xml.etree.ElementTree
import sys
import... |
# -*- coding: utf-8 -*-
# Copyright 2018-2021 releng-tool
from releng_tool.util.file_flags import FileFlag
from releng_tool.util.file_flags import process_file_flag
from tests import prepare_workdir
import os
import unittest
class TestFileFlags(unittest.TestCase):
def test_ff_create(self):
with prepare_wo... |
import unittest
class TestDiagonalCosmoBNNPrior(unittest.TestCase):
"""A suite of tests alerting us for breakge, e.g. errors in
instantiation of classes or execution of scripts, for DiagonalBNNPrior
"""
def test_tdlmc_diagonal_cosmo_config(self):
"""Tests instantiation of TDLMC diagonal Config... |
from __future__ import division
import sys
import argparse
import torch
import os
import torch.nn as nn
import torch.optim as optim
import numpy as np
import json
import pickle
from sklearn.metrics import average_precision_score
from torch.utils.data import Dataset, DataLoader
from dataloader import Loader
from model ... |
import requests
import psycopg2
import psycopg2.extras
import urllib.parse as urlparse
import os
from lotify.client import Client
URL = urlparse.urlparse(os.getenv('DATABASE_URL'))
DB_NAME = URL.path[1:]
USER = URL.username
PASSWORD = URL.password
HOST = URL.hostname
PORT = URL.port
class Database:
conns = []
... |
"""Compose. A command line utility for making React.js componets.
Composes helps you to create the structure for a React.js component,
following the View-Actions-index pattern.
"""
import argparse
import os.path
import re
import sys
from pathlib import Path
from typing import Dict, TextIO
INDEX = """\
import React fr... |
import argparse
import cv_generator.themes
import logging
import os
import random
# Create the ArgumentParse and parse the arguments inside `args`
parser = argparse.ArgumentParser(description='Run CV Generator')
parser.add_argument('--cv-file', required=True, help='Relative or absolute path to the raw .json or .yaml r... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import re
class Autoconf(AutotoolsPackage, GNUMirrorPackage):
"""Autoconf -- system configuration part of autotools"... |
from xmlrpc.client import ServerProxy
url = "http://localhost:8080"
proxy = ServerProxy(url)
# text = u"This is my home"
# params = {"text":text, "align":"false", "report-all-factors":"false"}
#
# result = proxy.translate(params)
#
# print result['text']
#
# if 'id' in result:
# print "Segment ID:%s" % (result['... |
#!/usr/bin/env python
from functools import wraps
import types
import json
from flask import Flask, request, Blueprint, _request_ctx_stack
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, current_user
from flask_principal import identity_chang... |
import pickle
import pandas as pd
from os import path
from scripts.config import params
from scripts.assemble_web_data import percentile, rescale_tsne
def assemble_web_data(raw_dir, processed_dir):
with open(path.join(processed_dir, 'x2i.pickle'), 'rb') as handle:
x2i = pickle.load(handle)
tsne_emb = ... |
n, k = list(map(int, input().split()))
time = 240
diff = time-k
t=0
prob = 0
for i in range(1,n+1):
if (t+5*i)<=diff:
t = t+5*i
prob +=1
print(prob)
|
import numpy as np
import logging
from ncon import ncon
from . import umps_mpoevolve
from . import mcmps_mpoevolve_real
from .McMPS import McMPS
from .UMPS import UMPS
version = 1.0
parinfo = {
"mps_chis": {
"default": range(1,31),
"idfunc": lambda dataname, pars: True
},
"ground_umps_chis... |
import lpaste.lpaste
__name__ == '__main__' and lpaste.lpaste.main()
|
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
table = set()
for num in nums:
if num in table:
return True
else:
table.add(num)
return False
|
from aapt2 import aapt
def test_version():
print(aapt.version())
def test_pkg_info():
print(aapt.get_apk_info("$HOME/Downloads/zzt.apk"))
def test_pkg_info():
print(aapt.ls("$HOME/Downloads/zzt.apk"))
|
import pytest
def test_save_when_pk_exists(user_model):
sam = user_model(id=1, name="Sam", height=178.6, married=True)
# The primary key value is not empty, the force_insert is False,
# this is the update logic, but there is no data in the cache,
# so the save does not take effect.
assert sam.save... |
import click
from cloup import option, option_group
global_options = option_group(
"Global options",
option(
"-c",
"--config_file",
help="Specify the configuration file to use for render settings.",
),
option(
"--custom_folders",
is_flag=True,
help="Use t... |
#!/usr/bin/env python2
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The unittest of experiment_file."""
from __future__ import print_function
import StringIO
import unittest
from experiment_fi... |
import time
import sys
commands = {
'OUTPUT_RESET': 'A2',
'OUTPUT_STOP': 'A3',
'OUTPUT_POWER': 'A4', # seems to max out around 0x1F with 0x20 backwards
'OUTPUT_SPEED': 'A5',
'OUTPUT_START': 'A6',
'OUTPUT_POLARITY': 'A7', # 0x01 forwards, 0x00 toggle, 0xFF backwards
}
motors = {
'A': 1,
... |
import torch
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module()
class LapLoss(torch.nn.Module):
def __init__(self,
max_levels=5,
channels=1,
device=torch.device('cuda'),
loss_weight=1.0):
super(LapLo... |
"""Module to train tic-tac-toe program."""
import numpy as np
import pickle
import os
from checkwin import checkwin
from decideplay import decideplay
from evalboard import recall_board, diffuse_utility, nd3_to_tuple, tuple_to_nd3
from transform import board_transform, board_itransform
from updateboard import make_move... |
from . import sly
|
import os
import shutil
from .base import GnuRecipe
class LaceRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(LaceRecipe, self).__init__(*args, **kwargs)
self.sha256 = '45e546e306c73ceed68329189f8f75fe' \
'cee3a1db8abb02b5838674a98983c5fe'
self.name = 'l... |
# -*- coding: utf-8 -*-
"""
Created on 21 August 2017
@author: dgrossman
"""
import logging
import threading
import time
from functools import partial
import pika
class Rabbit(object):
'''
Base Class for RabbitMQ
'''
def __init__(self):
self.logger = logging.getLogger('rabbit')
def make... |
#!/usr/bin/env python
#version: 2.5 beta
import threading
import argparse
import random
import atexit
import socket
import socks
import time
import ssl
import sys
import os
start_time = 0
active_connections = 0
connection_limit = 0
active_threads = 0
max_threads = 100
delay = 1
ups = 0
total_ups = 0
dps = 0
total_dps... |
from django.conf.urls import patterns, url
from webui.views.dashboard import DashboardView
from webui.views.login import LoginView
from webui.views.logs import LogsView
urlpatterns = patterns(
'webui.views',
url(r'^$', DashboardView.as_view(), name='dashboard'),
url(r'^signin/$', LoginView.as_view(), name... |
from rest_framework.test import APIClient, APITestCase
from rest_framework import status
from django.contrib import auth
from django.contrib.auth.models import Group
from contest.models import Contest, Task, TestCase
import datetime
class TaskTestCase(APITestCase):
@classmethod
def setUpTestData(cls):
... |
# -*- coding: utf-8 -*-
# Copyright 2019, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
QasmSimulator Integration Tests
"""
import multiprocessing
from test.terra.utils import common
from test.terra.utils imp... |
# Generated by Django 2.2.4 on 2019-10-15 19:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crud_lugar', '0004_auto_20191015_1501'),
]
operations = [
migrations.AlterField(
model_name='evento',
name='hora_fin... |
import sys
import os
import datetime
import pickle
import textwrap
from prompt_toolkit import Application
from prompt_toolkit.layout.containers import VSplit, HSplit, Window
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
from prompt_toolkit.layout.margins import ScrollbarMargin
from pro... |
# Based on audio_to_midi_melodia github repo by Justin Salamon <justin.salamon@nyu.edu>
import time
import argparse
import os
import numpy as np
from scipy.signal import medfilt
#import __init__
import pyaudio
import sys
import aubio
from aubio import sink
from songmatch import *
from song import *
from operator import... |
from tqdm import tqdm
import time
import logging
import os
import email
from abc import ABC, abstractmethod
import mailbox
from mailbox import mboxMessage
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import requests
import yaml
from bs4 import Be... |
# The following g++ options are those that are not enabled by
#
# -Wall -Wextra -Werror -Weffc++
#
# The above options are recommended to be in SContruct/Makefile, and the options
# below are enabled as much as practical. If a particular option causes
# false-positives in one or a few files, then the issue can be resol... |
## Testing matplotlib
## code from NNFS
## My own comments are marked with ##
## My own code start with ##-- and ends with --##
import random
import numpy as np
##--
from matplotlib import pyplot as plt, patches
# --##
from nnfs.datasets import spiral_data
dropout_rate = 0.5
# Example output containing... |
#!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
./server.py [ssl]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import ssl
class ServerHandler(BaseHTTPRequestHandler):
def _set_response(self, code):
self.send_response(code)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtCore, QtWidgets
from {{cookiecutter.repo_name}}_ui import Ui_MainWindow
__version__ = "{{cookiecutter.version}}"
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
... |
import os
from os import listdir
from os.path import isfile, join
import json
mypath = 'D:\data\smiles'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f)) and f.startswith('SMILE_')]
counter_all = 0
file_counter = 0
FULL_URI_LIST = []
with open('FULL_URI_LIST', 'w') as f:
f.write('')
f.close()... |
# -*- coding: utf-8 -*-
from allink_core.core.models.managers import AllinkCategoryModelQuerySet
class PartnerQuerySet(AllinkCategoryModelQuerySet):
pass
PartnerManager = PartnerQuerySet.as_manager
|
#!/usr/bin/env python3
################################################################################
### cif2xyz file converter based on openbabel, script by RS ####################
################################################################################
import sys
import os
import subprocess
def float_w_br... |
from django.db import models
from school_backend.models.school import School
from django.core.exceptions import ValidationError
import uuid
from rest_framework import serializers, viewsets
## Refuse new students if the limit has been reached
def restrict_amount(value):
if Student.objects.filter(school=value).count... |
# 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, ... |
"""
Handles communication with Nordic Power Profiler Kit (PPK) hardware
using Segger's Real-Time Transfer functionality.
"""
import time
import struct
import re
import math
class PPKError(Exception):
"""PPK exception class, inherits from the built-in Exception class."""
def __init__(self, error=None):
... |
# -*- coding: utf-8 -*-
"""Generate the Resilient customizations required for fn_qradar_asset"""
from __future__ import print_function
from resilient_circuits.util import *
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_qradar_asset package"""
reload_params = {"package": u"fn_qra... |
import numpy as np
from PIL import Image
class processed_image():
def __init__(self,path):
self.img = np.array(Image.open(path).convert('L'), 'f')
self.height,self.width = self.img.shape
self.all_lines = [set() for i in range(self.width)]
self.line = [-1] * self.width
def show_... |
import asyncio
import functools
import shlex
from typing import Tuple
async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
args = shlex.split(cmd)
process = await asyncio.create_subprocess_exec(
*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await ... |
def predict(text):
print(text)
return [1,0,0,1,1] |
print("today is 2018-8-5 ")
|
# coding: utf-8
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import unittest
from auto_nag.mail import replaceUnicode
class TestMail(unittest.TestCase):
def ... |
# Typeshed definitions for multiprocessing.managers is incomplete, so ignore them for now:
# https://github.com/python/typeshed/blob/85a788dbcaa5e9e9a62e55f15d44530cd28ba830/stdlib/3/multiprocessing/managers.pyi#L3
from multiprocessing.managers import ( # type: ignore
BaseManager,
)
import pathlib
from typing impo... |
import FreeCAD
import FreeCADGui as Gui
try:
# ############################################################################
# This part of code has been created by Werner Mayer (wmayer) at forum:
# https://forum.freecadweb.org/viewtopic.php?p=187448#p187448
# ######################################################... |
def test_num(test):
test_set = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
for num in test_set:
if test % num != 0:
return False
return True
for x in range(2520, 10000000000, 2520):
if test_num(x):
print("Answer 5:", x)
break
|
from neo4jrestclient.client import GraphDatabase
class Database(object):
def __init__(self, uri, user, password_):
self.db = GraphDatabase(uri, username=user, password=password_)
def close(self):
self.db.close()
def _create_node(self,_label,_name):
# Create one node with... |
# Utilities
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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, c... |
import logging
from django.http import Http404
from django.shortcuts import render_to_response
from gibbs.forms import CompoundForm
from gibbs import reaction
from gibbs import conditions
def CompoundPage(request):
"""Renders a page for a particular compound."""
form = CompoundForm(request.GET)
if not for... |
import ctypes
from .. import utils
NULL_BYTE = b"\x00"
class RawVLRHeader(ctypes.LittleEndianStructure):
""" Close representation of a VLR Header as it is written
in the LAS file.
"""
_fields_ = [
("_reserved", ctypes.c_uint16),
("user_id", ctypes.c_char * 16),
("record_id",... |
"""Mixin for shortcut for users resource requests."""
from typing import Optional, Tuple
from uuid import UUID
from botx.bots.mixins.requests.call_protocol import BotXMethodCallProtocol
from botx.clients.methods.v3.users.by_email import ByEmail
from botx.clients.methods.v3.users.by_huid import ByHUID
from botx.client... |
#! /usr/bin/env python
# Usage: dgslandmarks2ndeobj_params.py <dgsfile> <texchan>
# to load landmarks and scalefactor from a .dgsfile
#
# <texchan> e.g. CR03_SPAR_01H_tex
import sys
import json
import dg_file as dgf
import dg_eval
dgsname=sys.argv[1]
texchan=sys.argv[2]
(md,wfmdict)=dgf.loadsnapshot(dgsname)
(ndi... |
import argparse, json
import simpleamt
if __name__ == '__main__':
parser = argparse.ArgumentParser(parents=[simpleamt.get_parent_parser()])
args = parser.parse_args()
mtc = simpleamt.get_mturk_connection_from_args(args)
reject_ids = []
if args.hit_ids_file is None:
parser.error('Must specify --hit_ids_... |
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from ridi_django_oauth2.managers import RidiUserManager
class RidiUser(AbstractBaseUser):
u_idx = models.IntegerField(primary_key=True, editable=False, verbose_name='u_idx')
USERNAME_FIELD = 'u_idx'
objects = RidiUs... |
#!/usr/bin/env python3
import csv
import matplotlib.pyplot as plt
def factor_quartiles_graph(input_file, output_file):
with open(input_file, 'r') as csvfile:
plots = csv.reader(csvfile, delimiter=';')
rows = []
x=[]
y=[]
for row in plots:
rows.append(row)
... |
#!/usr/bin/env python2
# Copyright (c) 2019 Erik Schilling
# 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 ... |
"""
Created on Dec 29, 2016
@author: andrew
"""
import asyncio
import logging
import aiohttp
from discord.ext import commands
import credentials
from cogsmisc.stats import Stats
log = logging.getLogger(__name__)
DBL_API = "https://discordbots.org/api/bots/"
class Publicity(commands.Cog):
"""
Sends update... |
import FWCore.ParameterSet.Config as cms
from DQM.GEM.GEMDQMHarvester_cfi import *
from DQMOffline.Muon.gemEfficiencyHarvesterCosmics_cfi import *
gemClientsCosmics = cms.Sequence(
GEMDQMHarvester *
gemEfficiencyHarvesterCosmics *
gemEfficiencyHarvesterCosmicsOneLeg
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.