content
stringlengths
5
1.05M
from django.db.models import Q from django.contrib.auth.models import User from django_jinja import library from remo.base.utils import get_object_or_none from remo.voting.models import Vote @library.filter def get_users_voted(poll): """Return the number of users voted to the specific poll.""" return poll....
# -*- coding: utf-8 -*- from sqlalchemy import \ Table, Column, Integer, String, Boolean, MetaData, \ ForeignKey, DateTime, UniqueConstraint from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.associationproxy import association_proxy from datetime import datetime from utils import Ap...
class PalParserException(Exception): """ An error occurred while parsing a Pal input file """ class PalGeneratorException(Exception): """ An error occurred while generating a Pal output file """ class PalWriterException(Exception): """ An error occurred while writing the contents of a Pal outp...
import logging import math import typing import PySimpleGUI as sg import numpy as np import pandas as pd import scipy.stats import serial import serial.tools.list_ports from serial import Serial, SerialException from src.model.Model import Model from src.util import Global from src.util.SetInterval import SetInterval...
#################################################### # SOLUTION OF THE NS EQS USING TENSORFLOW ########## #################################################### # Third-party libraries import tensorflow as tf # Libraries from comp_conv import kernel_1 from nn import fnn # Heat model def heat_model_fn(t, ra...
#!/usr/bin/python # Copyright (c) 2018 Intel Corporation # # 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,...
from setuptools import setup from os import path import keepercommander here = path.abspath(path.dirname(__file__)) # Get the long description from the README.md file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() install_requires = [ 'colorama', 'pycryptodom...
# Generated by Django 2.1 on 2018-11-30 10:15 from django.db import migrations def convert_datasets(apps, schema_editor): # class variables copied from (old) ValidationRun class: ## datasets C3S = 'C3S' ISMN = 'ISMN' GLDAS = 'GLDAS' SMAP = 'SMAP' ASCAT = 'ASCAT' REF_DATASETS = ( ...
# Logging.py # # helper for logging import logging FORMAT='%(asctime)-15s %(levelname)-10s %(name)-10s %(message)s' def add_logging_options(parser): """add logging options (-v, -q, -L) to an argparse""" parser.add_argument('-v', '--verbose', action='count', default=0, help="be more verbo...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='random-gen', version='1.0.0', author="hp310780", description="Module to generate random numbers along a probability distribution", long_description=long_description, long_descrip...
#! /usr/bin/env python3 """ TST calculations for: nC5H11 <=> C2H4 + nC3H7 sC5H11 <=> C3H6 + C2H5 """ from me2d import RoVib from me2d import tstrates, equilibrium_consts_12, name2weight nc5h11 = RoVib(\ nsym = 1, rotA = 0.609391, rotB2D = 0.0654364, freq = [113.598, 120.817, 184.873, 247.846, 401.83...
# coding: utf-8 # 本脚本copy到工程目录下,与工程文件同级即可 import sys import time import re import requests import json import os import smtplib import platform from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from release_conf import config # @params selectType 1:dev-test,2:dev-online,3:rc-online,4...
from BaseClass import BaseClass class PythonClass(BaseClass): __instance__ = None def __init__(self): if PythonClass.__instance__ is None: PythonClass.__instance__ = self super().__init__() else: pass @staticmethod def getInstance(): if not Pyt...
import datetime from django.db import models from django.utils import timezone # SublimeCodeIntel # 只能提示插件 # http://www.cnblogs.com/dolphin0520/archive/2013/04/29/3046237.html # 重启sublime,打开个python文件,按ctrl+shift+space,这时候第一次运行会去下载一些东西,可以按ctrl+~来看进度 之后就ok了 # class Employee(models.Model): question_text = models.Cha...
""" DB Helper Author: Irfan Chahyadi Source: github.com/irfanchahyadi/Odong2Bot """ import pymysql, json, dotenv, os from datetime import datetime CLEAR_MENU = {'State': '', 'Sort': '', 'Filter': '', 'Search':'', 'Page': 1, 'Address': '', 'Lat': '', 'Lon': '', 'Note': ''} dotenv.load_dotenv() class dbHelper(): def...
def create_url_for_helper(name, *parts, **defaults): def url_for_helper(self, *args, absolute=False, **kwargs): params = dict(defaults) params.update(kwargs) _parts = params.pop('parts', {}) _parts.update(dict(zip(parts, map(str, args)))) if _parts: params['parts'...
# Copyright 2021 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, ...
# flake8: noqa # @TODO: code formatting issue for 20.07 release from typing import Callable, Dict, Optional from collections import defaultdict import torch from torch.optim import Optimizer class Lookahead(Optimizer): """Implements Lookahead algorithm. It has been proposed in `Lookahead Optimizer: k steps ...
from decimal import Decimal from gdax.authenticated_client import AuthenticatedClient from MyFillOrderBook import MyFillOrderBook import config # Log my Keys my_user_id = config.my_user_id myKeys = config.live auth_client = MyFillOrderBook(myKeys['key'], myKeys['secret'], myKeys['passphrase']) #offset = 1 #close_...
# # Load CSV tables from GS to BigQuery # # Provide schema JSONs in schema_path # Run from current directory # import os import sys import getopt import json # ---------------------------------------------------- ''' default config values To override default config values, copy the keys to be overriden to a json fil...
"""The reduction channel.""" import numpy as np from scipy.sparse import identity from toqito.states import max_entangled def reduction(dim: int, k: int = 1) -> np.ndarray: r""" Produce the reduction map or reduction channel. If :code:`k = 1`, this returns the Choi matrix of the reduction map which is ...
import re from enum import Enum class WebhookTopicType(str, Enum): ping = "ping" connections = "connections" oob_invitation = "oob_invitation" connection_reuse = "connection_reuse" connection_reuse_accepted = "connection_reuse_accepted" basicmessages = "basicmessages" issue_credential = "i...
#!/usr/bin/python3 ''' main cli for spotiplay rooms ''' from __future__ import absolute_import, unicode_literals import socket import json import sys import time from multiprocessing import Process from Crypto.Cipher import AES from spotiplay.strategy import get_pytify_class_by_platform from spotiplay.song_list import...
#%% """ example_fullrun.py ================== This file demonstrates a minimal example run of of the QPCR Analyzer, showing how to use the following: 1. QPCRExtracter to extract data from a BioRad output file. 2. BioRadMapper to map the extracted file to ODM format. 3. QPCRPopulator to create the full QPCR report an...
from sqlalchemy import create_engine import pandas as pd import numpy as np from importlib import reload import collections from pandas import json_normalize import json import argparse import sys from sqlalchemy import create_engine import sqlite3 from importlib import reload import os #def load_dataset(dataset_path)...
from PIL import Image, ImageEnhance, ImageFilter import numpy as np from utilities_d_v2 import * from io import BytesIO import cv2 as cv ''' file che contiene le funzioni che applicano all'immagine le trasformazioni elementari come se fossero filtri, quindi sono scalabili rispetto ad alpha e intensity ''' # modifica ...
# -*- coding: utf-8 -*- """ Created on Sat Aug 18 14:40:28 2018 @author: yoelr """ import numpy as np import pandas as pd from graphviz import Digraph from ._exceptions import DesignWarning, _try_method from ._flowsheet import find, save_digraph from ._graphics import Graphics, default_graphics from ._stream import St...
class Support(object): def __init__(self): self._caseType = None @property def caseType(self): print("getter of caseType called") return self._caseType @caseType.setter def caseType(self, value): print("setter of caseType called") self._caseType = value ...
''' 文件已废弃 ''' import urllib.parse import base64 import abc def decorator(func): def _f(raw): decoded_data: bytes = func(raw) if decoded_data == raw: raise Exception else: return decoded_data return _f class MetaDecoder(metaclass=abc.ABCMeta): @staticmethod @decorator @abc.abstrac...
# Topic: Customized library file to connect to databases using mysql library # Ask user questions for information and connect to database # Author: Xuhua Huang # # Last updated: Aug 8, 2021 # Created on: Aug 8, 2021 import mysql.connector # -----------------------------------------------------------------------------...
# -*- coding: utf-8 -*- """ Created on Tue May 31 16:56:03 2016 @author: login """ from GEO_Database import GEO_Database mystic_lake = GEO_Database(name="test_db", TestBool=True, BuildBool=True) mystic_lake.read_combined_URL_list() mystic_lake.download_data(type="metadata") mystic_lake.write_metadata_table(tags = ['...
from PySide6.QtWidgets import QPushButton from PySide6.QtCore import Qt class SizeGrip(QPushButton): def __init__(self, parent, left): super(SizeGrip, self).__init__(parent) self.setCursor(Qt.SizeAllCursor) self.parent = parent self.mouse_being_pressed = False ...
import textwrap from unittest import mock from django.contrib.sessions.models import Session from django.http.response import HttpResponse from django.test import TestCase from bc.cases.backends.respond.client import RespondClientException from bc.cases.utils import format_case_reference from bc.home.models import Ho...
# -*- coding: utf-8 -*- """ Created on Mon May 4 10:11:53 2020 @author: CJ ROCKBALL """ import numpy as np from bokeh.layouts import gridplot, column, Spacer from bokeh.models import CustomJS, Slider, TextInput, DataRange1d, LabelSet from bokeh.plotting import ColumnDataSource, figure, output_file, show ...
import requests import json # cell 1 - search companies based on key words, search query should obey ISO 8601 format open_corp_search_url = "https://api.opencorporates.com/v0.4/companies/search?q=vancity" r1 = requests.get(open_corp_search_url) print r1.status_code print r1.json() print # cell 2 - get detailed inf...
# fungsi binary and operator # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_and(a: int, b: int) -> str: """ Ambil 2 bilangan bulat, ubah menjadi biner, mengembalikan bilangan biner yaitu hasil dari binary_and operasi pada bilangan bulat yang disediakan. >>> b...
import param class HoloViewsFramePlotMethods(HoloViewsSeriesPlotMethods): by = param.String(default=None) def __call__(self, x=None, y=None, kind='line', ax=None, subplots=False, sharex=None, sharey=False, layout=None, figsize=None, use_index=True, title=None, grid=False, ...
import pytest from labdrivers.srs.sr830 import sr830 LOCKIN_GPIB_ADDR = 8 def test_sync_filter(): lock_in = sr830(LOCKIN_GPIB_ADDR) lock_in.sync_filter = True assert int(lock_in.sync_filter) == 1 lock_in.sync_filter = False assert int(lock_in.sync_filter) == 0 with pytest.ra...
from torch.nn.modules import LSTM import torch.nn as nn import numpy as np import torch from torch.autograd import Variable class PriorLSTM(nn.Module): def __init__(self,prior,input_size=52686, output_size=2976,hidden_size=128,num_layers=16,batch_first=True, dropout=0.1): super(PriorLSTM,...
from savu.plugins.plugin_tools import PluginTools class GetDataStatisticsTools(PluginTools): """Collects data global statistcs (max, min, sum, mean) and put it in metadata. """ def define_parameters(self): """ out_datasets: visibility: datasets dtype: [list[],lis...
from .drop_last import drop_last from ramda.private.asserts import assert_iterables_equal def drop_nocurry_test(): assert_iterables_equal(drop_last(2, [1, 2, 3, 4]), [1, 2]) def drop_curry_test(): assert_iterables_equal(drop_last(2)([1, 2, 3, 4]), [1, 2])
from output.models.nist_data.list_pkg.token.schema_instance.nistschema_sv_iv_list_token_length_2_xsd.nistschema_sv_iv_list_token_length_2 import NistschemaSvIvListTokenLength2 __all__ = [ "NistschemaSvIvListTokenLength2", ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 14 12:41:00 2019 @author: ziqi """ import sys, os dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(dir_path) sys.path.insert(0, dir_path + "/model/") from mol_tree import MolTree import time from transfer i...
""" Copyright (c) 2017 Patrick Dill, a/k/a reshanie 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, publis...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu> # # Distributed under terms of the MIT license. """Definition of the class representing Lagrange basis""" # TODO: complete documentation # TODO: find better way to carry out calculations. Current way...
from django.conf import settings sph_settings_defaults = { # Only settings for the 'community' applications are defined here, # (or global settings) -- all other defaults should be added using # the add_setting_defaults method ! 'django096compatibility': False, 'community_avatar_de...
"""Tests for the Cooperator strategy.""" import axelrod as axl from .test_player import TestPlayer C, D = axl.Action.C, axl.Action.D class TestCooperator(TestPlayer): name = "Cooperator" player = axl.Cooperator expected_classifier = { "memory_depth": 0, "stochastic": False, "ma...
""" This is the ABNF grammar, expressed in ABNF, plus the core rules. Collected rules from RFC 5234 https://tools.ietf.org/html/rfc5234 """ from ..parser import Rule as _Rule from .misc import load_grammar_rules @load_grammar_rules() class Rule(_Rule): """Rule objects generated from ABNF in RFC 5234.""" gr...
#!/usr/bin/python #------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this f...
#! usr/bin/python # -*- coding: utf-8 -*- import os from os.path import join, dirname from dotenv import load_dotenv from flask import Flask, request, jsonify from sqlalchemy import create_engine from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import scoped_session, sessionmaker dotenv_path = join(dirname...
# -*- coding: utf-8 -*- import scrapy import json import re from tangspiderframe.items import TangspiderframeItem class TextChinaDxyLinkSpider(scrapy.Spider): name = 'text_china_dxy_link' allowed_domains = ['ask.dxy.com'] def __init__(self, category=None, *args, **kwargs): super(TextChinaDxyLinkS...
from setuptools import setup import re requirements = [] with open('requirements.txt') as f: requirements = f.read().splitlines() with open('ipyc/__init__.py') as f: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) with open('README.rst') as f: readme = f.read...
from flask import render_template, current_app, session, g, abort, jsonify, request from info import constants, db from info.models import News, User, Comment, CommentLike from info.modules.news import news_blu from info.utils.common import user_login_data from info.utils.response_code import RET @news_blu.route('/f...
"""Tests for brim.stats.""" """Copyright and License. Copyright 2012-2014 Gregory Holt 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...
# Fetches GeoJSON from a featureServer URL # Step 2: append ?f=pjson and parse for the `serviceItemId` value. also check `supportedQueryFormats` for `geoJSON`. possibly also save the name and id of this layer and increment the /0 to get more if any #Step 3: fetch geoJSON data and store in cache folder (or somewhere, p...
import krpc import math import time # http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/ class PIDController(object): """ A robust PID """ def __init__(self, input, setpoint, kp, ki, kd, outmin = 0, outmax = 0): self.last_time = time.time() self.i_term = 0 ...
def counter(fn): def _counted(*largs, **kargs): _counted.invocations += 1 fn(*largs, **kargs) _counted.invocations = 0 return _counted
""" Question : http://rosalind.info/problems/ba4a/ Algorithm Steps 1- Covert the RNA Codon table to a list [[key1,val1],[key2,val2],..] 2- convert every key to a value and save it to a string """ #####Converting RNA Table to list like def conv(): rna = [] rnaCodon = open('RNA_codon_table.txt', 'r') f...
import numpy as np import matplotlib.pyplot as plt import cv2 # helper functions # convienient way to display inline images def imshow(img, title = ''): # hide the x and y axis for images plt.axis('off') # RGB images are actually BGR in OpenCV, so convert before displaying if len(img.shape) == 3: ...
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket import json clients = [] class SimpleChat(WebSocket): def handleMessage(self): data = self.data data = json.loads(data) print data if data['action']=='5hKhnlBxkPQkuGAqN6k1ksR3yfgNtQTHA2LwtykKZcGAfe5a0EhXh79hgRGb62fWcEBwfj8E5infOb5M5QtuE' and...
from . import AresHtmlAlert from . import AresHtmlButton from . import AresHtmlCheckBox from . import AresHtmlContainer from . import AresHtmlEvent from . import AresHtmlFiles from . import AresHtmlHRef from . import AresHtmlImage from . import AresHtmlInput from . import AresHtmlList from . import AresHtmlNa...
### # File: getphotos.py # Authors: Divya Bhagavathiappan (divya@hunch.ly) and Justin Seitz (justin@hunch.ly) # Last modified: 2021-02-19 ### import json from entities import * from MaltegoTransform import * from config import * from subprocess import Popen, PIPE # initialize the transform object transform = MaltegoT...
import sys import argparse import numpy as np import matplotlib.pyplot as plt from filterpy.kalman import KalmanFilter from filterpy.common import Q_discrete_white_noise def kalman_filter_const_acc(z, P=0.5, Q=0.5, R=10.0, dt=0.5): """ Args: z: (n_time_steps, 3*n_pts) ndarray of pts to be tracked P: error...
import os from pathlib import Path import subprocess as sp import sys from typing import Dict, List, Optional, Tuple, Union from pyscreener.docking.base import Screener DOCK6 = Path(os.environ['DOCK6']) DOCK6_PARAMS = DOCK6 / 'parameters' VDW_DEFN_FILE = DOCK6_PARAMS / 'vdw_AMBER_parm99.defn' FLEX_DEFN_FILE = DOCK6_P...
import unittest from MindwavePacketPayloadParser import MindwavePacketPayloadParser from MindwaveDataPoints import RawDataPoint, PoorSignalLevelDataPoint,\ MeditationDataPoint, AttentionDataPoint, EEGPowersDataPoint, BlinkDataPoint class ParseRawValueTest(unittest.TestCase): @classmethod def setUpClass(c...
''' Convert a pkl file into json file ''' import sys import os import _pickle as pickle #import pickle import json import numpy as np # deprecated def convert_dict_to_json(file_path): target_file_path = '%s.npy' % file_path # with open(file_path, 'rb') as fpkl, open('%s.json' % file_path, 'w') as...
from sklearn.pipeline import Pipeline from opaque.locations import BACKGROUND_DICTIONARY_PATH from opaque.nlp.featurize import BaselineTfidfVectorizer from opaque.ood.svm import LinearOneClassSVM class GroundingAnomalyDetector: def __init__(self, featurizer, out_of_dist_classifier, memory=None): self.pip...
imie = "JAKUB" nazwisko = "GÓRNICZ" print(imie.capitalize(), nazwisko.capitalize())
from output.models.nist_data.list_pkg.normalized_string.schema_instance.nistschema_sv_iv_list_normalized_string_length_2_xsd.nistschema_sv_iv_list_normalized_string_length_2 import NistschemaSvIvListNormalizedStringLength2 __all__ = [ "NistschemaSvIvListNormalizedStringLength2", ]
#! /usr/bin/env python3 # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
from tello import Tello import sys from datetime import datetime import time import TelloPro tello = Tello() command_lst = [] command_lst.append(TelloPro.get_instance('takeoff',-1)) #의미 없음 command_lst.append(TelloPro.get_instance('up',50)) command_lst.append(TelloPro.get_instance('down',30)) command_lst.append(TelloP...
# -*- coding: utf-8 -*- """ Oscilloscope with logging (graphing by Bokeh) Implemented with producer/consumer model Main thread : data_producer and a Bokeh server for graphing Child thread : Logger (consumer) """ import createc.utils.data_producer as dp from createc.Createc_pyCOM import CreatecWin...
# import classes and functions from pytorch_pfn_extras.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA from pytorch_pfn_extras.training.triggers.interval_trigger import IntervalTrigger # NOQA from pytorch_pfn_extras.training.triggers.manual_schedule_trigger import ManualScheduleTrigger # ...
def count(test_string, hands): runs = 0 last_group = None for c in test_string: for group, chars in enumerate(hands): if c in chars: if last_group == group: runs += 1 last_group = group break else: la...
''' the script to prune the datastore ''' import logging import random from typing import List, Dict import warnings from tqdm import tqdm import numpy as np import sklearn import matplotlib.pyplot as plt from copy import deepcopy import time from sklearn.cluster import Birch, DBSCAN, SpectralClustering from multipro...
import numpy as np from bokeh.plotting import figure,output_file,show class PolarPlot: def __init__(self, theta0=0, rmax=1.0, clockwise=True, ntgrid=12, nrgrid=4, **kwargs): kwargs['x_axis_label'] = None kwargs['y_axis_label'] = None kwargs['x_axis_type'] = 'linear' kwargs...
from functools import partial from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from . import pipeline_blocks as blocks def lightGBM(config, train_mode, suffix=''): if train_mode: features, features_valid = blocks.feature_...
class MultiKeyDictionaryError(KeyError): def __init__(self, ex): super().__init__(ex) class KeyNotFound(MultiKeyDictionaryError): def __init__(self, ex): super().__init__(ex) class WrongKeyType(Exception): def __init__(self, ex): super().__init__(ex) class WrongHttpHeaderDataTy...
import chainer import chainer.functions as F import chainer.links as L class CBR(chainer.Chain): def __init__(self, ch0, ch1, bn=True, sample='down', activation=F.relu, dropout=False): self.bn = bn self.activation = activation self.dropout = dropout layers = {} w = chainer....
from __future__ import annotations from .utils import log from email.message import EmailMessage import smtplib import ssl from typing import Optional # TODO: make this async # https://realpython.com/python-with-statement/#creating-an-asynchronous-context-manager # https://docs.python.org/3/library/asyncio.html # htt...
# api_v1/urls from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from . import views from rest_framework.schemas import get_schema_view schema_view = get_schema_view(title="Job Manager API v1") urlpatterns = [path("test_l2a/", views.TestL2A.as_view(), name="test-l2a")] urlpa...
import numpy as np import torch from easydict import EasyDict from ding.torch_utils import to_dtype, to_ndarray from ding.utils import deep_merge_dicts def pack_birdview(data, packbit=False): if isinstance(data, dict): if 'obs' in data: pack_birdview(data['obs']) if 'next_obs' in data...
"""Configure Kea's server-id.""" # pylint: disable=invalid-name,line-too-long import pytest import misc import srv_msg import srv_control @pytest.mark.v6 @pytest.mark.kea_only @pytest.mark.server_id def test_v6_server_id_llt(): misc.test_setup() srv_control.config_srv_subnet('3000::/64', '3000::1-3000::ff...
""" SoilGrids See: https://maps.isric.org/ """ from podpac.data import WCS class SoilGridsBase(WCS): """ Base SoilGrids WCS datasource. """ format = "geotiff_byte" max_size = 16384 _repr_keys = ["layer"] class SoilGridsWRB(SoilGridsBase): """ SoilGrids: WRB classes and probabilities (WCS) ""...
""" 1D problem - Using custom class =============================== This example implements a PDE that is only defined in one dimension. Here, we chose the `Korteweg-de Vries equation <https://en.wikipedia.org/wiki/Korteweg–de_Vries_equation>`_, given by .. math:: \partial_t \phi = 6 \phi \partial_x \phi - \parti...
#!/usr/bin/env python ## VD_2241 import rospy from geometry_msgs.msg import Twist from turtlesim.msg import Pose import math import time import sys robot_x = 0 robot_y = 0 PI = 3.1415926535897 choice =1 def node_turtle_revolve(lin_vel, ang_vel): global robot_x, robot_y, present_time,choice rospy.init_node('no...
depths = [int(x.strip()) for x in open('../input.txt', 'r').readlines()] prev = None increases = 0 for d in depths: if prev is None: prev = d continue if d > prev: increases += 1 prev = d print(increases)
from datetime import datetime, timedelta from unittest.mock import Mock, patch from bravado.exception import HTTPError from django.utils.timezone import now from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo from app_utils.testing import NoSocketsTestCase, queryset_pks from ..models import (...
#!/usr/bin/env python3 # # -*- coding: utf-8 -*- """ The encrypt command available when running the CLI. Responsible for encrypting strings. ________________________________________________________________________________ Created by brightSPARK Labs www.brightsparklabs.com """ # standard library from pathlib import...
import time import hashlib import requests import random import string import getopt import http.cookiejar import sys import urllib.parse import urllib.request from http.cookies import SimpleCookie from json import loads as json_loads from os import environ def gen_anti_code(code): _headers = {"Referer": 'https://re...
#!/usr/bin/env python import os import sys def main(): orig_folder = sys.argv[1] # use gnrs/ec2_data/pl_data_new_100K or *_1M final_folder = sys.argv[2] # final_requests = int(sys.argv[3]) orig_requests = 1000000 print 'Initial number of requests is 1M' num_names = 10000 ## hardcoded ...
import json import os import pandas as pd from dagster import EventMetadata from dagster.core.asset_defs import build_assets_job from dagster.utils import file_relative_path from dagster_dbt import dbt_cli_resource from dagster_dbt.asset_defs import load_assets_from_dbt_manifest from dagster_pyspark import pyspark_res...
#!/ usr/bin/env # coding=utf-8 # # Copyright 2019 ztosec & https://www.zto.com/ # # 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 r...
import pytest import torch from nequip.data import AtomicData from nequip.nn import ( AtomwiseLinear, AtomwiseReduce, PerSpeciesScaleShift, SequentialGraphNetwork, ) from nequip.nn.embedding import ( OneHotAtomEncoding, ) from torch_geometric.data import Batch @pytest.fixture(scope="class", param...
from datetime import date from os import makedirs from os.path import join import re from subprocess import run, PIPE from sys import argv def main(sootsai): kiatko = [] for panpun in [11, 12, 13, 14]: kiatko.append( run([ 'docker', 'ps', '--filter', 'ancest...
import glob import logging import os.path from abc import abstractmethod from typing import Dict, Iterator, List, Optional, Type, Union from common import directories, file_utils from common.commands.database import DatabaseUploadCommand from common.types import ( Context, EntityExtractionResult, EntityLoc...
"""hass_smartthings_remove""" import os from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join("README.md"), 'r') as fh: long_description = fh.read() setup(name='hass_smartthings_remove', version="1.0.1", description='Utility that remove...
import unittest from unittest import mock import cherry class ApiTest(unittest.TestCase): @mock.patch('cherry.api.Classify') def test_classify_api(self, mock_classify): cherry.classify(['random string'], model='harmful') mock_classify.assert_called_once_with( N=20, model='harmful'...
from zipfile import ZipFile import os from Utils.helpers import random_string from obfuscation.main import Obfuscator,ValidateGlobalVars,parse,unparse def zip_dir(base_dir: str,zip_name: str,zip_password: str) -> str: zf = ZipFile(zip_name,"a") for dirname, subdirs, files in os.walk(base_dir): zf.write(...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...