blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
e48b036b804b5b19e1e4bd9da499b64f55ab174e
fcc955fd5b3fc997f5b1651c5c8b9032a6b9b177
/bqskit/passes/search/generator.py
e9d081a87e21f8745e3f3d6b693ef54e11204717
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
BQSKit/bqskit
cf393d75b26349f7258e9caf9d5c8fa37d0c8de6
c89112d15072e8ffffb68cf1757b184e2aeb3dc8
refs/heads/main
2023-09-01T04:11:18.212722
2023-08-29T17:34:38
2023-08-29T17:34:38
331,370,483
54
18
NOASSERTION
2023-09-14T14:33:26
2021-01-20T16:49:36
OpenQASM
UTF-8
Python
false
false
926
py
"""This module implements the LayerGenerator base class.""" from __future__ import annotations import abc from bqskit.compiler.passdata import PassData from bqskit.ir.circuit import Circuit from bqskit.qis.state.state import StateVector from bqskit.qis.state.system import StateSystem from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix class LayerGenerator(abc.ABC): """ The LayerGenerator base class. Search based synthesis uses the layer generator to generate the root node and the successors of a node. """ @abc.abstractmethod def gen_initial_layer( self, target: UnitaryMatrix | StateVector | StateSystem, data: PassData, ) -> Circuit: """Generate the initial layer for search.""" @abc.abstractmethod def gen_successors(self, circuit: Circuit, data: PassData) -> list[Circuit]: """Generate the successors of a circuit node."""
5856221a71dc642ec3f93b8731bbf1ea07fa2377
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03806/s174409855.py
f3f10e7dddb189ad08ecede3f07387e8d52479df
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
696
py
import sys input = sys.stdin.buffer.readline N, Ma, Mb = map(int, input().split()) ABC = [list(map(int, input().split())) for _ in range(N)] sumA = sum([ABC[i][0] for i in range(N)]) sumB = sum([ABC[i][1] for i in range(N)]) INF = 10 ** 15 dp = [[INF for j in range(sumB + 1)] for i in range(sumA + 1)] dp[0][0] = 0 for a, b, c in ABC: for i in range(sumA, -1, -1): for j in range(sumB, -1, -1): if dp[i][j] != INF: dp[i + a][j + b] = min(dp[i + a][j + b], dp[i][j] + c) answer = INF for i in range(1, sumA + 1): for j in range(1, sumB + 1): if dp[i][j] != INF and i / j == Ma / Mb: answer = min(answer, dp[i][j]) print(answer if answer != INF else -1)
4348f18e7053dec8ee530cf954bd323e2780a2a6
83de24182a7af33c43ee340b57755e73275149ae
/aliyun-python-sdk-drds/aliyunsdkdrds/request/v20190123/DescribeDbInstancesRequest.py
4fc670ea5087265f9b54638259b120fe48033076
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-python-sdk
4436ca6c57190ceadbc80f0b1c35b1ab13c00c7f
83fd547946fd6772cf26f338d9653f4316c81d3c
refs/heads/master
2023-08-04T12:32:57.028821
2023-08-04T06:00:29
2023-08-04T06:00:29
39,558,861
1,080
721
NOASSERTION
2023-09-14T08:51:06
2015-07-23T09:39:45
Python
UTF-8
Python
false
false
2,127
py
# 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 file # to you 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 distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkdrds.endpoint import endpoint_data class DescribeDbInstancesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Drds', '2019-01-23', 'DescribeDbInstances','drds') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_DrdsInstanceId(self): return self.get_query_params().get('DrdsInstanceId') def set_DrdsInstanceId(self,DrdsInstanceId): self.add_query_param('DrdsInstanceId',DrdsInstanceId) def get_PageNumber(self): return self.get_query_params().get('PageNumber') def set_PageNumber(self,PageNumber): self.add_query_param('PageNumber',PageNumber) def get_Search(self): return self.get_query_params().get('Search') def set_Search(self,Search): self.add_query_param('Search',Search) def get_PageSize(self): return self.get_query_params().get('PageSize') def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize) def get_DbInstType(self): return self.get_query_params().get('DbInstType') def set_DbInstType(self,DbInstType): self.add_query_param('DbInstType',DbInstType)
429edffa026b5304c1b8fa929f0ee668951964d3
43e2e801f6df426a9b923828e8ee3c0b0f022c66
/vocab.py
ea1b9279eff7d539a5a6955ac364e0923c3847ee
[ "MIT" ]
permissive
mrdrozdov/knnlm
0333eadbd1d0c6e16521475dc07d57d7dce8b02e
61419077eb7f79c3ba7a196b4cc7cf722f4ba8f4
refs/heads/master
2023-04-19T14:13:58.242980
2021-05-20T02:34:17
2021-05-20T02:34:17
317,321,152
0
0
MIT
2021-01-26T17:44:06
2020-11-30T19:12:33
null
UTF-8
Python
false
false
5,773
py
import collections class Dictionary(object): """ A mapping from symbols to consecutive integers. Taken from fairseq repo. """ def __init__( self, pad="<pad>", eos="</s>", unk="<unk>", bos="<s>", extra_special_symbols=None, ): self.unk_word, self.pad_word, self.eos_word = unk, pad, eos self.symbols = [] self.count = [] self.indices = {} self.bos_index = self.add_symbol(bos) self.pad_index = self.add_symbol(pad) self.eos_index = self.add_symbol(eos) self.unk_index = self.add_symbol(unk) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(s) self.nspecial = len(self.symbols) def __eq__(self, other): return self.indices == other.indices def __getitem__(self, idx): if idx < len(self.symbols): return self.symbols[idx] return self.unk_word def __len__(self): """Returns the number of symbols in the dictionary""" return len(self.symbols) def __contains__(self, sym): return sym in self.indices def index(self, sym): """Returns the index of the specified symbol""" assert isinstance(sym, str) if sym in self.indices: return self.indices[sym] return self.unk_index def unk_string(self, escape=False): """Return unknown string, optionally escaped as: <<unk>>""" if escape: return "<{}>".format(self.unk_word) else: return self.unk_word def add_symbol(self, word, n=1): """Adds a word to the dictionary""" if word in self.indices: idx = self.indices[word] self.count[idx] = self.count[idx] + n return idx else: idx = len(self.symbols) self.indices[word] = idx self.symbols.append(word) self.count.append(n) return idx def update(self, new_dict): """Updates counts from new dictionary.""" for word in new_dict.symbols: idx2 = new_dict.indices[word] if word in self.indices: idx = self.indices[word] self.count[idx] = self.count[idx] + new_dict.count[idx2] else: idx = len(self.symbols) self.indices[word] = idx self.symbols.append(word) self.count.append(new_dict.count[idx2]) def finalize(self, threshold=-1, nwords=-1, padding_factor=8): """Sort symbols by frequency in descending order, ignoring special ones. Args: - threshold defines the minimum word count - nwords defines the total number of words in the final dictionary, including special symbols - padding_factor can be used to pad the dictionary size to be a multiple of 8, which is important on some hardware (e.g., Nvidia Tensor Cores). """ if nwords <= 0: nwords = len(self) new_indices = dict(zip(self.symbols[: self.nspecial], range(self.nspecial))) new_symbols = self.symbols[: self.nspecial] new_count = self.count[: self.nspecial] c = collections.Counter( dict( sorted(zip(self.symbols[self.nspecial :], self.count[self.nspecial :])) ) ) for symbol, count in c.most_common(nwords - self.nspecial): if count >= threshold: new_indices[symbol] = len(new_symbols) new_symbols.append(symbol) new_count.append(count) else: break assert len(new_symbols) == len(new_indices) self.count = list(new_count) self.symbols = list(new_symbols) self.indices = new_indices self.pad_to_multiple_(padding_factor) def pad_to_multiple_(self, padding_factor): """Pad Dictionary size to be a multiple of *padding_factor*.""" if padding_factor > 1: i = 0 while len(self) % padding_factor != 0: symbol = "madeupword{:04d}".format(i) self.add_symbol(symbol, n=0) i += 1 def bos(self): """Helper to get index of beginning-of-sentence symbol""" return self.bos_index def pad(self): """Helper to get index of pad symbol""" return self.pad_index def eos(self): """Helper to get index of end-of-sentence symbol""" return self.eos_index def unk(self): """Helper to get index of unk symbol""" return self.unk_index def add_from_file(self, f): """ Loads a pre-existing dictionary from a text file and adds its symbols to this instance. """ if isinstance(f, str): try: with open(f, "r", encoding="utf-8") as fd: self.add_from_file(fd) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception( "Incorrect encoding detected in {}, please " "rebuild the dataset".format(f) ) return for line in f.readlines(): idx = line.rfind(" ") if idx == -1: raise ValueError( "Incorrect dictionary format, expected '<token> <cnt>'" ) word = line[:idx] count = int(line[idx + 1 :]) self.indices[word] = len(self.symbols) self.symbols.append(word) self.count.append(count)
0ec7be58bdfad20324b305d2f182ce221998241b
721406d87f5086cfa0ab8335a936ece839ab2451
/.venv/lib/python3.8/site-packages/opencensus/trace/config_integration.py
a0d8e5d3c146b4424f29d79fecff324c6344b651
[ "MIT" ]
permissive
MarkusMeyer13/graph-teams-presence
661296b763fe9e204fe1e057e8bd6ff215ab3936
c302b79248f31623a1b209e098afc4f85d96228d
refs/heads/main
2023-07-09T03:34:57.344692
2021-07-29T07:16:45
2021-07-29T07:16:45
389,268,821
0
0
MIT
2021-07-29T07:16:46
2021-07-25T05:23:08
Python
UTF-8
Python
false
false
1,330
py
# Copyright 2017, OpenCensus 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib import logging log = logging.getLogger(__name__) def trace_integrations(integrations, tracer=None): """Enable tracing on the selected integrations. :type integrations: list :param integrations: The integrations to be traced. """ integrated = [] for item in integrations: module_name = 'opencensus.ext.{}.trace'.format(item) try: module = importlib.import_module(module_name) module.trace_integration(tracer=tracer) integrated.append(item) except Exception as e: log.warning('Failed to integrate module: {}'.format(module_name)) log.warning('{}'.format(e)) return integrated
fd29d423ff124d7289cca464d2dbd43fdc7dae05
8f6cc0e8bd15067f1d9161a4b178383e62377bc7
/__OLD_CODE_STORAGE/tensorflow_PLAYGROUND/lessons/from_internet/uuuuu.py
3fc0fc1f64c4d43958978fe8396f928cf7251a2f
[]
no_license
humorbeing/python_github
9c4dfc61a3cefbb266fefff335f6b28d05797e5e
e4b4b49bee7e7e3843c6874717779ce8d619bd02
refs/heads/master
2023-01-22T21:51:20.193131
2020-01-26T21:47:23
2020-01-26T21:47:23
163,707,778
0
0
null
2022-12-27T15:37:48
2019-01-01T01:58:18
Python
UTF-8
Python
false
false
2,703
py
import numpy as np import tensorflow_playground as tf from tensorflow_playground.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) image_size = 28 labels_size = 10 learning_rate = 0.05 steps_number = 1000 batch_size = 100 tf.logging.set_verbosity(tf.logging.INFO) if __name__ == "__main__": tf.app.run() def cnn_model_fn(features, labels, mode): """model function for CNN.""" # Input Layer input_layer = tf.reshape(features["x"], [-1, 28, 28, 1]) # Convolutional Layer #1 conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu ) # Pooling Layer #1 pool1 = tf.layers.max_pooling2d( inputs=conv1, pool_size=[2, 2], strides=2 ) # Convolutional Layer #2 and Pooling Layer #2 conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu ) pool2 = tf.layers.max_pooling2d( inputs=conv2, pool_size=[2, 2], strides=2 ) # Dense Layer pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) dense = tf.layers.dense( inputs=pool2_flat, units=1024, activation=tf.nn.relu ) dropout = tf.layers.dropout( inputs=dense, rate=0.4, training= mode == tf.estimator.ModeKeys.TRAIN ) # Logits Layer logits = tf.layers.dense(inputs=dropout, units=10) predictions = { # Generate predictions (for PREDICT and EVAL mode) "classes": tf.argmax(input=logits, axis=1), "probabilities": tf.nn.softmax(logits, name="softmax_tensor") } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # Calculate Loss (for both TRAIN and EVAL modes) loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) # Configure the Training Op (for TRAIN mode) if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001) train_op = optimizer.minimize( loss=loss, global_step=tf.train.get_global_step() ) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) # Add evaluation metrics (for EVAL mode) eval_metric_ops = { "accuracy": tf.metrics.accuracy( labels=labels, predictions=predctions["classes"] ) } return tf.estimator.EstimatorSpec( mode=mode, loss=loss, eval_metric_ops=eval_metric_ops )
1535301b3f78a727e980c0c4e00988e46ff1b61a
268c588de53d48f2e48c694535e27c1be104229d
/Decorator_Pattern.py
dbbacb277861f380541934a98021297ec79ff1d3
[]
no_license
wax8280/Python_Design_Patterns
def64b1662924807946a9847ac1bf0437382a716
88fb08ad3605fb06166bf45d814f5b85a37364b5
refs/heads/master
2021-01-11T01:21:14.964828
2016-10-14T15:40:42
2016-10-14T15:40:42
70,715,104
0
0
null
null
null
null
UTF-8
Python
false
false
1,105
py
# coding:utf-8 import functools def memoize(fn): known = dict() @functools.wraps(fn) def memoizer(*args): if args not in known: known[args] = fn(*args) return known[args] return memoizer @memoize def nsum(n): '''Returns the sum of the first n numbers''' assert (n >= 0), 'n must be >= 0' return 0 if n == 0 else n + nsum(n - 1) @memoize def fibonacci(n): '''Returns the nth number of the Fibonacci sequence''' assert (n >= 0), 'n must be >= 0' return n if n in (0, 1) else fibonacci(n - 1) + fibonacci(n - 2) if __name__ == '__main__': from timeit import Timer measure = [{'exec': 'fibonacci(100)', 'import': 'fibonacci', 'func': fibonacci}, {'exec': 'nsum(200)', 'import': 'nsum', 'func': nsum}] for m in measure: t = Timer('{}'.format(m['exec']), 'from __main__ import {}'.format(m['import'])) print('name: {}, doc: {}, executing: {}, time: {}'.format(m['func'].__name__, m['func'].__doc__, m['exec'], t.timeit()))
bea389a719f322ce117b6f02b2fbd03de15d243f
5dac0010edb884cd6d412954c79b75fa946e252d
/101-AWS-S3-Hacks/createobject.py
b2b8a10c68fbf4ae56917a6656cd95a009038b7b
[]
no_license
ralic/aws_hack_collection
c1e1a107aa100e73b6e5334ed9345576057bdc9d
7b22018169e01d79df7416dd149c015605dea890
refs/heads/master
2023-01-09T04:31:57.125028
2020-02-06T11:21:39
2020-02-06T11:21:39
90,350,262
3
1
null
2022-12-26T20:03:05
2017-05-05T07:39:34
Python
UTF-8
Python
false
false
396
py
#!/usr/bin/python """ - Author : Nag m - Hack : Create a new object in S3 - Info : Create a object named - myfile.txt """ import boto def createaobject(): bucket = conn.get_bucket("101-s3-aws") obj = bucket.new_key("myfile.txt") obj.set_contents_from_string("This is my first object created in S3") if __name__ == "__main__": conn = boto.connect_s3() createaobject()
e5202820096b9831f3b03b5f13d7933f9f22108b
ac611b732321d2496862b0c4d7368d37eb1ead5c
/Blog/blogDevMedia/migrations/0001_initial.py
5fefcd9aed347aa33b619b4e5c85f6a7e6ab79a2
[]
no_license
WellingtonIdeao/django-admin-miniblog
85e0c61f186b75a4b11675a6d973dde73d0c1720
a47ee8d6bbefac4280d6d0abbee1fb43ab030087
refs/heads/master
2020-09-15T16:18:30.319187
2019-11-22T23:25:20
2019-11-22T23:25:20
223,501,182
0
0
null
null
null
null
UTF-8
Python
false
false
605
py
# Generated by Django 2.2.7 on 2019-11-11 16:39 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Postagem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(max_length=100)), ('descricao', models.CharField(max_length=200)), ('conteudo', models.TextField()), ], ), ]
4d369e4a896df1bf1b0412392fc0f664e190cedd
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/adverbs/_fore.py
4ee9f0775ec26099d96243967f7acf17c2d722c6
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
396
py
#calss header class _FORE(): def __init__(self,): self.name = "FORE" self.definitions = [u'(especially on ships) towards or in the front'] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'adverbs' def run(self, obj1, obj2): self.jsondata[obj2] = {} self.jsondata[obj2]['properties'] = self.name.lower() return self.jsondata
c0bc4d868d66841eeac3f734176734a63f8f00b7
93713f46f16f1e29b725f263da164fed24ebf8a8
/Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/themes/_dark_minimal.py
65ceb00baefed17600816474b78dad06a1826a14
[ "BSD-3-Clause" ]
permissive
holzschu/Carnets
b83d15136d25db640cea023abb5c280b26a9620e
1ad7ec05fb1e3676ac879585296c513c3ee50ef9
refs/heads/master
2023-02-20T12:05:14.980685
2023-02-13T15:59:23
2023-02-13T15:59:23
167,671,526
541
36
BSD-3-Clause
2022-11-29T03:08:22
2019-01-26T09:26:46
Python
UTF-8
Python
false
false
2,451
py
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- json = { "attrs": { "Figure" : { "background_fill_color": "#20262B", "border_fill_color": "#15191C", "outline_line_color": "#E0E0E0", "outline_line_alpha": 0.25 }, "Grid": { "grid_line_color": "#E0E0E0", "grid_line_alpha": 0.25 }, "Axis": { "major_tick_line_alpha": 0, "major_tick_line_color": "#E0E0E0", "minor_tick_line_alpha": 0, "minor_tick_line_color": "#E0E0E0", "axis_line_alpha": 0, "axis_line_color": "#E0E0E0", "major_label_text_color": "#E0E0E0", "major_label_text_font": "Helvetica", "major_label_text_font_size": "1.025em", "axis_label_standoff": 10, "axis_label_text_color": "#E0E0E0", "axis_label_text_font": "Helvetica", "axis_label_text_font_size": "1.25em", "axis_label_text_font_style": "normal" }, "Legend": { "spacing": 8, "glyph_width": 15, "label_standoff": 8, "label_text_color": "#E0E0E0", "label_text_font": "Helvetica", "label_text_font_size": "1.025em", "border_line_alpha": 0, "background_fill_alpha": 0.25, "background_fill_color": "#20262B" }, "ColorBar": { "title_text_color": "#E0E0E0", "title_text_font": "Helvetica", "title_text_font_size": "1.025em", "title_text_font_style": "normal", "major_label_text_color": "#E0E0E0", "major_label_text_font": "Helvetica", "major_label_text_font_size": "1.025em", "background_fill_color": "#15191C", "major_tick_line_alpha": 0, "bar_line_alpha": 0 }, "Title": { "text_color": "#E0E0E0", "text_font": "Helvetica", "text_font_size": "1.15em" } } }
efeebd47dc1709a52f66c0796785c9d4a18d99ff
062fa6891dfe2278bcfa36a00cc8bed4356e9f5b
/examples/remote_store/remote_server.py
242a24cdda02f56be9be607eb765873d9c12fabd
[ "Apache-2.0" ]
permissive
sepidehhosseinzadeh/mlflow-cpp
f43ffb1dba0e57b9b67fad696966bae683328527
724eeaeafbee829201859033315a9d2ebf314844
refs/heads/master
2022-12-12T13:41:28.825923
2020-06-10T20:42:55
2020-06-10T20:42:55
158,026,349
2
0
Apache-2.0
2022-12-08T05:37:42
2018-11-17T21:27:07
Makefile
UTF-8
Python
false
false
1,236
py
from __future__ import print_function import os import shutil import sys import random import tempfile import mlflow from mlflow import log_metric, log_param, log_artifacts, get_artifact_uri, active_run,\ get_tracking_uri, log_artifact if __name__ == "__main__": print("Running {} with tracking URI {}".format(sys.argv[0], get_tracking_uri())) log_param("param1", 5) log_metric("foo", 5) log_metric("foo", 6) log_metric("foo", 7) log_metric("random_int", random.randint(0, 100)) run_uuid = active_run().info.run_uuid # Get run metadata & data from the tracking server service = mlflow.tracking.MlflowClient() run = service.get_run(run_uuid) print("Metadata & data for run with UUID %s: %s" % (run_uuid, run)) local_dir = tempfile.mkdtemp() message = "test artifact written during run %s within artifact URI %s\n" \ % (active_run().info.run_uuid, get_artifact_uri()) try: file_path = os.path.join(local_dir, "some_output_file.txt") with open(file_path, "w") as handle: handle.write(message) log_artifacts(local_dir, "some_subdir") log_artifact(file_path, "another_dir") finally: shutil.rmtree(local_dir)
bb8457345e260777ed69b1380a60010f582f86d4
d24cef73100a0c5d5c275fd0f92493f86d113c62
/SRC/tutorials/movenode.py
5575fd4201c1203ed4c8f638e857d7127c92c355
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
rlinder1/oof3d
813e2a8acfc89e67c3cf8fdb6af6b2b983b8b8ee
1fb6764d9d61126bd8ad4025a2ce7487225d736e
refs/heads/master
2021-01-23T00:40:34.642449
2016-09-15T20:51:19
2016-09-15T20:51:19
92,832,740
1
0
null
null
null
null
UTF-8
Python
false
false
24,396
py
# -*- python -*- # $RCSfile: movenode.py,v $ # $Revision: 1.19.18.8 $ # $Author: langer $ # $Date: 2014/09/27 22:34:44 $ # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification and maintenance. However, to # facilitate maintenance we ask that before distributing modified # versions of this software, you first contact the authors at # [email protected]. from ooflib.tutorials import tutorial TutoringItem = tutorial.TutoringItem TutorialClass = tutorial.TutorialClass TutorialClass( subject = "Moving Nodes", ordering=2.1, lessons = [ TutoringItem( subject="Introduction", comments= """This tutorial expands on the discussion of Node Motion in the "Skeleton" tutorial. OOF3D employs two methods to adapt a Skeleton to a Microstructure's material boundaries -- BOLD(refinement) and BOLD(node movement). Refinement, of course, chops target elements into smaller pieces, increasing global homogeneity and at the same time increasing element density along material boundaries. Refinement is in some sense a blind operation -- it doesn't know exactly where material boundaries are, only that an element or segment needs to be divided. On the other hand, node movement can place nodes exactly on material boundaries. This tutorial covers most of the basics regarding node movement. """ ), TutoringItem( subject="Getting Ready", comments=""" This tutorial uses four example files, BOLD(green_corner.skeleton) BOLD(composition.skeleton), BOLD(serendipity.skeleton), and BOLD(triangle.skeleton). Download them now from http://www.ctcms.nist.gov/oof/oof3d/examples, or locate them within the share/oof3d/examples directory in your OOF3D installation. """ ), TutoringItem( subject="Refine or node movement", comments= """Whenever you have heterogeneous elements, you typically have two choices -- refinement or node movement. The order of operations actually plays a critical role in the quality of the resulting skeleton. Let us load a sample skeleton to see the effect. Choose BOLD(Load/Data) from the BOLD(File) menu in the main OOF3D window. Open the file BOLD(composition.skeleton). """, signal = ("new who", "Skeleton") ), TutoringItem( subject="Snap Nodes and Refine -- part 1", comments= """Open a graphics window to view the skeleton. Only BOLD(200) out of BOLD(625) elements are homogeneous at this point. It is tempting to move nodes to create more homogeneous elements cheaply. Open the BOLD(Skeleton) page from the main OOF3D window. Set the BOLD(method) in the BOLD(Skeleton Modification) pane to BOLD(Snap Nodes) and set BOLD(targets) to be BOLD(All Nodes). For BOLD(criterion) select BOLD(Average Energy) and set its BOLD(alpha) to be BOLD(1), sensitive only to element homogeneity. Click BOLD(OK) to snap nodes.""", signal = ("who changed", "Skeleton") ), TutoringItem( subject="Snap Nodes and Refine -- part 2", comments= """Depending on your luck -- we'll get to this later -- you created about BOLD(174) more homogeneous elements. Not too bad. At this stage, continuing to move nodes will yield only a marginal improvement. We need to refine the heterogeneous elements. Set the Skeleton Refinement method to BOLD(Refine). Set BOLD(targets) set to BOLD(Heterogeneous Elements) with BOLD(threshold) = BOLD(1). Set BOLD(criterion) to BOLD(Unconditional), and leave BOLD(alpha) set to BOLD(1). Click BOLD(OK) to refine. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Snap Nodes and Refine -- part 3", comments= """Let's check the homogeneity index for this skeleton, which can be found at the left side of the BOLD(Skeleton) page. It should be around BOLD(0.9) - BOLD(0.92). Now, Click BOLD(Undo) from the page repeatedly (actually twice), until you restore the initial skeleton in the graphics window. This time, we'll refine first and move nodes later. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Refine and Snap Nodes -- part 1", comments= """BOLD(Refine) the initial skeleton with the same options as before. And then, do BOLD(Snap Nodes) with the same options. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Refine and Snap Nodes - Continued", comments= """The difference is significant. First of all, the homogeneity index for this skeleton is greater the previous one which was below BOLD(0.92). Thus, it becomes clear that node movement is most effective after a skeleton has been BOLD(appropriately) refined. Unfortunately, BOLD('appropriately') is a very subjective word and OOF3D can't notify users of the best time to start moving nodes. However, when most of the heterogeneous elements contain only two different voxel materials, a skeleton can be considered to be BOLD(appropriately) refined.""" ), TutoringItem( subject="Serendipity", comments= """OOF3D provides four node moving tools - Snap Nodes, Anneal, Smooth, and manual node motion. These tools (except for manual node motion) move nodes in a random order to avoid any potential artifacts caused by the internal node (element) ordering of the skeleton. Thus, any two node move processes with identical parameters can yield different outcomes. Let's load a test skeleton and continue on the subject. Before we load a new skeleton, let's delete the current one. This isn't absolutely necessary but it simplifies things. Open the BOLD(Microstructure) page. Click BOLD(Delete) to delete the existing Microstructure and Skeleton at the same time. As soon as you confirm the deletion, the graphics window will be emptied. (If it isn't, close it and open a new one.)""", signal = "remove who" ), TutoringItem( subject="Serendipity -- continued", comments= """Load the file BOLD(serendipity.skeleton) with the BOLD(Load/Data) command in the BOLD(File) menu. Graphics windows show objects automatically only once. If you're still using the original graphics window, it will not show the new skeleton when it loads, but if you've opened a new one, it will. Let us make the graphics window display the Skeleton and the Image stored in Microstructure. """, signal = ("new who", "Skeleton") ), TutoringItem( subject="Serendipity -- recontinued", comments= """If necessary, go to the graphics window and you'll see that the Layer List at the bottom of the window shows two display layers. (You may have to scroll or resize the list window to see both layers.) Double-click on the first one that says BOLD(SkeletonEdgeDisplay). A window named BOLD(Edit Graphics Layer) will pop up. Set BOLD(category) to BOLD(Skeleton). Since we have only one skeleton available in the system, it's automatically chosen. Click BOLD(OK) to display the skeleton. Now, double-click on the second layer, named BOLD(BitmapDisplayMethod). Set BOLD(category) to BOLD(Image). Click BOLD(OK) to display the Image. Close the editor."""), TutoringItem( subject="Serendipity -- final", comments= """Open the BOLD(Skeleton) task page in the main OOF3D window. Select BOLD(Snap Nodes). Set BOLD(targets) to BOLD(All Nodes) and BOLD(criterion) to BOLD(Average Energy) with BOLD(alpha)=1. Click BOLD(OK) to move modes. Go to the message window and check how many nodes have been moved. Also, check the result in the graphics window. Now, BOLD(Undo) the modification and click BOLD(OK) again. You may see a different result this time. Repeat the BOLD(Undo)-BOLD(OK) dance, you'll see the effect. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Anneal or Snap Nodes", comments= """The BOLD(Anneal) skeleton modifier moves nodes randomly and accepts or rejects the moves based on a given criterion. Let us try annealing the current skeleton. Before you go further, restore the skeleton to its initial status by BOLD(Undo)ing repeatedly. If the BOLD(Undo) button is grayed out, it means the skeleton is in its initial state (or that you made so many moves that the undo/redo stack overflowed, in which case you should delete and reload the Skeleton). Select BOLD(Anneal). Set BOLD(targets) to be BOLD(Heterogeneous Elements) with BOLD(threshold)=1, meaning that only the nodes of the heterogeneous elements will be moving. Choose BOLD(Average Energy) for BOLD(criterion) and set BOLD(alpha) to be BOLD(0.95). The anneal operation has a fictive temperature, and an average move size, which are called BOLD(T) and BOLD(delta), respectively. Set BOLD(T) to zero, and BOLD(delta) to 1.0. These are the defaults. Set the BOLD(iteration) parameter to BOLD(Fixed Iterations) and set the number of iterations to BOLD(50). For every iteration, each node will be moved to a randomly chosen position an average distance delta away from the initial position. With BOLD(T=0), a move will be accepted only if it lowers the average "energy" of all of the surrounding elements. (The energy function, described in the "Skeleton" tutorial, optimizes the shape and homogeneity of the elements.) Click BOLD(OK) to give it a go. Bring up the message window to check the progress. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Anneal or Snap Nodes -- continued", comments= """Amazingly, most of the nodes moved to places almost where you want them to go. Some elements, however, are still not homogeneous. The other issue is that most nodes that appear to be correctly placed are actually not exactly on the boundaries, due to the fact that their positions have been randomly generated. Let us BOLD(Undo) the change and use BOLD(Snap Nodes) this time. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Anneal or Snap Nodes -- continued", comments= """Select BOLD(Snap Nodes) and give it a go with the same options as before. Because of the random order in which nodes are moved, different results are possible. Two of the possible results resolve most of the boundaries completely -- the material boundaries lie beneath an element edge. One of these cases snaps 48 nodes, and the other snaps 47. (There are possible 47 node snaps that create skinny vertical red elements -- these aren't the snaps we're looking for.) If you didn't get one of these cases, BOLD(Undo) and try again. Once you've found one of the two special cases, two or three more BOLD(Snap Nodes) will get the job done. All the nodes moved should be exactly BOLD(on) the boundaries. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Anneal or Snap Nodes - Final", comments= """This shows that some situations are more suited for BOLD(Snap Nodes) than BOLD(Anneal). Generally, snapping takes less time than annealing but snapping is a much more limited operation than annealing. It only works for nodes of elements with certain boundary patterns, whereas annealing works for any nodes. And of course, in a real example with a larger and more complicated skeleton, it's not feasible to repeatedly undo and repeat the snapping procedure until you get the skeleton you like. In general, one of the more efficient ways of moving nodes is to BOLD(Snap) first and BOLD(Anneal) later. This will be presented in the next set of tutorial slides.""" ), TutoringItem( subject="Delete the Microstructure and Skeleton, again", comments= """Open the BOLD(Microstructure) page and BOLD(delete) the microstructure -- the Skeleton will be deleted at the same time. As before, if the graphics window does not clear itself, close it and open a new one. """, signal = "remove who" ), TutoringItem( subject="Annealing Revisited", comments= """Load a Skeleton from the file BOLD(triangle.skeleton) with the BOLD(Load/Data) command in the BOLD(File) menu. """, signal = ("new who", "Skeleton") ), TutoringItem( subject="Displaying the New Skeleton", comments= """To display the loaded skeleton, either repeat the layer editing procedure you used earlier, or just close the graphics window and open another one. (Graphics layers are created automatically only once per window.) The unfinished skeleton for a blue triangle Microstructure should be displayed in the graphics window.""", ), TutoringItem( subject="Annealing Revisited -- continued", comments= """The Skeleton has been treated with BOLD(Snap Nodes) a few times so far and it is obvious that snapping won't help the situation any more. (Go ahead and try, anyway, if you like.) The worst problem spot is at the left corner of the triangle. If you look closely, however, you'll see that the mesh alignment at the other two corners isn't ideal, either. These spots can be easily fixed by BOLD(Anneal). Open the BOLD(Skeleton) task page and select BOLD(Anneal). Keep the previous options, except set BOLD(iterations) to BOLD(20) and BOLD(delta) to BOLD(2). BOLD(delta) is the width (in voxels) of the gaussian distribution from which the random node motions are generated. Since the bad node in the Skeleton is quite far from its ideal location, we need to generate large moves. Click BOLD(OK) to give it a go. Bring up the message window to monitor the progress, while visually enjoying the transformation of the skeleton. If you were lucky, the element edges are well aligned with the material boundaries. However it is likely that you need to do some fine tuning. Set BOLD(delta) to 1 and iterate some more.""", signal = ("who changed", "Skeleton") ), TutoringItem( subject="Annealing Efficiently", comments= """You may have noticed that the BOLD(Acceptance Rate) reported in the Message window was pitifully low for the later steps of the annealing process. That's because most of the nodes were already at their ideal positions, so most of the random moves were rejected. There are various ways in OOF3D of restricting the domain of the annealing operation (and almost all other operations, as well). BOLD(Undo) all of the Skeleton modifications to get back to the original mesh. The next few tutorial slides will illustrate different ways of annealing efficiently. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Annealing Selected Nodes", comments= """In the BOLD(Skeleton Selection) toolbox in the Graphics window, click on BOLD(Node) in the top row of buttons, to put the window into Node selection mode. Leave the BOLD(Method) menu set to BOLD(Single_Node). Click on the badly misaligned node near the lower left corner of the Skeleton (it's the one at the second column from the left and third row from the bottom) to select it -- it should appear as a blue dot.""", signal = "changed node selection" ), TutoringItem( subject="Annealing Selected Nodes -- continued", comments= """Back in the BOLD(Skeleton) page, set the BOLD(targets) parameter of the BOLD(Anneal) method to BOLD(Selected_Nodes). And set BOLD(alpha) and BOLD(iteration) to be BOLD(0.7) and BOLD(40), respectively. Click BOLD(OK) to anneal just the one selected node. Notice that the process goes quite fast, but that it also doesn't produce a great result. This is because the node can't move to the vertex of the triangle without creating a badly shaped quadrilateral (one with an interior angle near 180 degrees). BOLD(Undo) your modification and try again with BOLD(alpha) in the BOLD(criterion) parameter set to BOLD(0.95), so that shape energy is considered minimally. The node should move closer to the vertex. But the creation of an ugly element was unavoidable. In general, it is difficult to get good results from annealing selected nodes, because of the difficulty of ensuring you have selected the right subset of nodes. BOLD(Undo) this modification.""", signal = ("who changed", "Skeleton") ), TutoringItem( subject="Annealing Selected Elements", comments= """Back in the BOLD(Skeleton Selection) toolbox in the Graphics window, switch into Element Selection mode with the BOLD(Element) button in the top row. Leave BOLD(Method) set to BOLD(Single_Element). Select the element surrounding the troublesome left hand vertex of the triangle. Now BOLD(Anneal) with BOLD(targets) set to BOLD(Selected Elements). Click BOLD(OK). (Repeat, if you're not satisfied. Play around with different values of the annealing parameters, and with different sets selected nodes and elements.) After it's done, click BOLD(Clear) from the BOLD(Skeleton Selection) to get a better view of the skeleton. The Skeleton should match the Image much better than it did before, because with more nodes moving, the annealing process could avoid creating badly shaped elements. As in the previous case, it can be hard to get good results with element selections. The optimal result might require modifications to non-selected elements which are interior or adjacent to your selection. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Active Volumes", comments= """Sometimes it's necessary to restrict all operations to a portion of the Microstructure. OOF3D lets you define an BOLD(Active Volume). When an Active Volume is defined, all operations apply only to voxels, nodes, and elements within the volume. This tutorial will use Active Volumes to anneal the Skeleton. BOLD(Undo) all the Skeleton modifications, and BOLD(Clear) the element/node selection. Active Volumes are defined in terms of voxels, so go to the BOLD(Voxel Selection) toolbox in the Graphics window. Set BOLD(Method) to BOLD(Burn). Click one voxel in the triangle. Make sure that you are in the triangle because in some cases the boundaries can have a different colors that the inside of the structure that you want.""", signal = "pixel selection changed" ), TutoringItem( subject="Active Volumes -- continued", comments= """ In the BOLD(Active Volume) page in the main OOF3D window, set BOLD(Method) to BOLD(Activate Selection Only) in the BOLD(Active Volume Modification) pane. Click BOLD(OK). Notice that most of the Image is dimmed, indicating that it's inactive. This will be more obvious if you BOLD(Clear) the selected voxels. Go back to the BOLD(Voxel Selection) toolbox and press BOLD(Clear). Try selecting more voxels, and notice that only voxels within the active volume are selected.""", signal = "active area modified" ), TutoringItem( subject="Active Volumes -- recontinued", comments= """Back in the BOLD(Skeleton) page in the main window, select BOLD(Anneal) again. Set BOLD(targets) to BOLD(All Nodes), and press BOLD(OK). Notice that only the nodes that start within the Active Volume move.""", signal = ("who changed", "Skeleton") ), TutoringItem( subject="Active Volumes -- closing remarks", comments= """The BOLD(Active Volume) page lets you change the Active Volume, save and restore Active Volumes, and temporarily BOLD(Override) them. The BOLD(Override) button, when pressed, makes the whole Microstructure active. This can be important, for example, when you want to select some currently inactive voxels and add them to the current Active Volume. """ ), TutoringItem( subject="Manual Node Motion", comments= """OOF3D allows you to manually move nodes, which can resolve many tricky spots with ease. Let us load a sample skeleton for this topic. First, delete the current Microstructure and Skeleton. Open the BOLD(Microstructure) page and click the BOLD(Delete) button. Load a skeleton from the file BOLD(green_corner.skeleton). Again, you need to display the loaded objects in the graphics window manually, or open a new graphics window. Caution: In 3D the nodes on the boundary surface of the skeleton have some motion constraints. For example the voxels on the back will not be able to move on the BOLD(z) axis. This is why when you pick one of that area the BOLD(z) component will be grayed out. """, signal = ("new who", "Skeleton") ), TutoringItem( subject="Manual Node Motion -- continued", comments= """What has to be done for the skeleton is obvious. Of course, BOLD(Anneal) can take care of this but if you're a control freak or short in the patience department, you can manually move the node to the spot where it has to be. In the graphics window, open the BOLD(Move Nodes) toolbox. Click on the bad node and drag it to the sweet spot. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Manual Node Motion -- continued", comments= """It's that simple to move a pain-in-the-butt node. The BOLD(keyboard) mode allows more precise node moves. BOLD(Undo) the move with the BOLD(Undo) button in the toolbox. (The BOLD(Undo) button on the BOLD(Skeleton) page in the main window does the same thing.) Set the BOLD(Move with) button at the top of the toolbox to BOLD(Keyboard). Now, assume that this problem node has to be absolutely positively at the corner of the boundary. Unless you're blessed with enormous mouse-eye coordination, it's impossible for you to spot the point in BOLD(mouse) mode. So, in BOLD(keyboard) mode, all you have to do is to find the position of the corner and type in these numbers. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Manual Node Motion -- final", comments= """To find the coordinates of the corner, we need to pay a visit to the BOLD(Voxel Info) toolbox. Once in the toolbox, click on the green voxel in the front corner and you'll see that its voxel position is BOLD((0, 32, 30)). The size of the voxel in physical units is BOLD(1.0x1.0x1.0). Thus, the position of the corner in physical units is (BOLD(0.0, 32.0, 30.0)) -- the origin (0.0, 0.0, 0.0) is the closest point to the intersecting point of the three axes BOLD((x,y,z)). Now, go back to the BOLD(Move Nodes) toolbox and click on the node in question. It'll be highlighted with a pinkish dot. Type in BOLD(32) and BOLD(30) in the text boxes next to BOLD(y) and BOLD(z), respectively. Now, click BOLD(Move) button to move the node. """, signal = ("who changed", "Skeleton") ), TutoringItem( subject="Done moving", comments= """Many aspects of node movement have been addressed in this tutorial. The suggestions and opinions provided in the tutorials are BOLD(merely) guidelines, so practice a lot and find the right strategy for you and your Microstructures. """ ) ])
32c59c5f3c4f7a20d5ebdf417eb2394978f5db44
573932f2fc40e94001a3659043b902db4d70a912
/4-Data-Visualization/dash/components/dash-core-components/tests/integration/dropdown/test_clearable_false.py
f72043bfd1dabb347829ce6ff1b5db07011999a1
[ "MIT" ]
permissive
BioInformatica-Labs/My-Data-Science-Journey
69f441f88e9e106975ec27de873d82af2dd351c7
92e04aa2e3612a198dc213f2dbd13b5df404bfbe
refs/heads/main
2023-08-28T05:22:56.970894
2021-11-08T20:05:10
2021-11-08T20:05:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,397
py
from dash import Dash, Input, Output, dcc, html from selenium.webdriver.common.keys import Keys def test_ddcf001_clearable_false_single(dash_duo): app = Dash(__name__) app.layout = html.Div( [ dcc.Dropdown( id="my-unclearable-dropdown", options=[ {"label": "New York City", "value": "NYC"}, {"label": "Montreal", "value": "MTL"}, {"label": "San Francisco", "value": "SF"}, ], value="MTL", clearable=False, ), html.Div(id="dropdown-value", style={"height": "10px", "width": "10px"}), ] ) @app.callback( Output("dropdown-value", "children"), [Input("my-unclearable-dropdown", "value")], ) def update_value(val): return val dash_duo.start_server(app) dropdown = dash_duo.find_element("#my-unclearable-dropdown input") dropdown.send_keys(Keys.BACKSPACE) dash_duo.find_element("#dropdown-value").click() assert len(dash_duo.find_element("#dropdown-value").text) > 0 assert dash_duo.get_logs() == [] def test_ddcf002_clearable_false_multi(dash_duo): app = Dash(__name__) app.layout = html.Div( [ dcc.Dropdown( id="my-unclearable-dropdown", options=[ {"label": "New York City", "value": "NYC"}, {"label": "Montreal", "value": "MTL"}, {"label": "San Francisco", "value": "SF"}, ], value=["MTL", "SF"], multi=True, clearable=False, ), html.Div(id="dropdown-value", style={"height": "10px", "width": "10px"}), ] ) @app.callback( Output("dropdown-value", "children"), [Input("my-unclearable-dropdown", "value")], ) def update_value(val): return ", ".join(val) dash_duo.start_server(app) dropdown = dash_duo.find_element("#my-unclearable-dropdown input") dropdown.send_keys(Keys.BACKSPACE) dropdown.send_keys(Keys.BACKSPACE) dash_duo.find_element("#dropdown-value").click() assert len(dash_duo.find_element("#dropdown-value").text) > 0 assert dash_duo.get_logs() == []
f74908b36da0518e5973c25583984c0da8eb4ef5
e64c14456007aa67fbde67ad15ea145492579eac
/2tom/10_tuple.py
7aa13028d3222a5f187ff61346eb0eff63bcacfc
[]
no_license
2tom/python_study
47ef0fbf8aa0a2242e0a8867bee54d63b44b9577
0488003bce763fd89fa65c3a7cca291be307dde9
refs/heads/master
2020-05-18T13:32:38.689670
2015-10-02T04:20:47
2015-10-02T04:20:47
37,230,139
2
3
null
2015-09-28T07:22:35
2015-06-11T00:30:10
Python
UTF-8
Python
false
false
123
py
# coding: UTF-8 a = (2, 5, 8) #print a * 3 #a[2] = 10 b = list(a) print b b[2] = 10 print b c = tuple(b) print c
238376f177e037da9767d1712ce0b0903e21778b
b338d3a594a4b1e4731a4d5949694101eea016fd
/MHDWaveHarmonics/GetFieldLine.py
997a0b1f6e85a2c0e4b785e42c30a7b95e13e02d
[ "MIT" ]
permissive
mattkjames7/MHDWaveHarmonics
ad65f4c5a93cfd9742c1118207cd75302606d8bd
ac8fcc5bf9190d300774c4e114a6ec4be865f014
refs/heads/master
2022-05-18T10:21:10.719998
2022-04-26T23:12:55
2022-04-26T23:12:55
159,176,825
1
0
null
null
null
null
UTF-8
Python
false
false
12,787
py
import numpy as np from FieldTracing import RK4 as rk4 import inspect from scipy.interpolate import InterpolatedUnivariateSpline from scipy.optimize import minimize from .DipoleField import TraceField import copy from . import Globals try: import KT17 as kt17 except: try: import Models.KT17 as kt17 except: print('KT17 module not found') else: Globals.kt17_loaded = True else: Globals.kt17_loaded = True try: import PyGeopack as gp except: try: import Models.PyGeopack as gp except: print('Geopack module not found') else: Globals.geopack_loaded = True else: Globals.geopack_loaded = True def _SortModelDirection(T): if T.nstep == 0: return if T.z[0] > T.z[T.nstep-1]: I = np.arange(T.nstep) O = I[::-1] T.x[I] = T.x[O] T.y[I] = T.y[O] T.z[I] = T.z[O] T.Bx[I] = T.Bx[O] T.By[I] = T.By[O] T.Bz[I] = T.Bz[O] if hasattr(T,'Rmso'): T.Rmso[I] = T.Rmso[O] T.Rmsm[I] = T.Rmsm[O] def GetModelFunction(**kwargs): Model = kwargs['Model'] if Model in ['T89','T96','T01','TS05']: if not Globals.geopack_loaded: print('Geopack module not installed!!!!') return None def ModelFunc(*args): T0 = gp.TraceField(*args,**kwargs) return T0 elif Model in ['KT14','KT17']: if not Globals.kt17_loaded: print('KT17 module not installed!!!!') return None def ModelFunc(*args): T0 = kt17.TraceField(*args,**kwargs) return T0 elif Model == 'Dipole': def ModelFunc(*args): T0 = TraceField(*args[:3],**kwargs) return T0 else: print('Model not found') return None return ModelFunc def _FlattenTrace(T): T.nstep = T.nstep[0] T.x = T.x[0] T.y = T.y[0] T.z = T.z[0] T.Bx = T.Bx[0] T.By = T.By[0] T.Bz = T.Bz[0] T.Lshell = T.Lshell[0] T.MltE = T.MltE[0] def GetFieldLine(pos,Date=None,ut=None,Model='KT17',Delta=None,Polarization='none',**kwargs): ''' Provides a field line trace with distance along field line and optionally h_alpha. Args ===== pos: ndarray with cartesian positional vector in Rp. Model: Model field name -- 'KT14'|'KT17'|'T89'|'T96'|'T01'|'TS05'|'Dipole' Delta: Separation between two traced field lines Polarization: 'none'|'toroidal'|'poloidal'|float|numpy.float32|numpy.float64 In the case of each option: 'none': No polarization, so no h_alpha calculation 'toroidal': calculates h_alpha for a toroidal polarization Equivalent to Polarization = 90.0 'poloidal': calculates h_alpha for a poloidal polarization (directed in towards the planet - this is so that the second field line doesn't end up outside the magnetopause) Equivalent to Polarization = +/-180.0 float/numpy.float32/numpy.float64: Calculates h_alpha for an arbitrary polarization, in this case the number must be a floating point angle in degrees from the poloidal axis, where the poloidal axis is taken to be pointing radially away from the centre of the dipole. The toroidal direction is taken to be pointing azimuthally (eastward) around the planet. For toroidal and poloidal polarizations: +ve poloidal - Polarization = 0.0 (away from planet) +ve toroidal - Polarization = 90.0 (eastward) -ve poloidal - Polarization = +/-180.0 (towards planet) -ve toroidal - Polarization = -90.0 (westward) Keyword Args ============ The following keyword argument form **kwargs - they are completely optional and depend on which model is being used. Model kwargs T89 iopt,Kp,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose T96 parmod,Pdyn,SymH,By,Bz,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose T01 parmod,Pdyn,SymH,By,Bz,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose TS05 parmod,Pdyn,SymH,By,Bz,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose KT17 MaxStepSize: Trace step size maximum in Rp (default = None). ModelArgs: Tuple containing arguments for the magnetic field models, when set to None, a set of default parameters are used. 'T89'|'T96'|'T01'|'TS05'|'T89c'|'T96c'|'T01c'|'TS05c': ModelArgs = (Date,ut,CoordIn,CoordOut,Alt,MaxLen,DSMax,iopt,parmod,tilt,Vx,Vy,Vz) ****NOTE**** When using models 'T89'|'T96'|'T01'|'TS05' - the iopt,parmod,tilt,Vx,Vy,Vz parameters need not be specified as they will be calculated automatically within the Geopack model from Omni data using the Date and ut parameters To use those parameters, add 'c' tot he model name string: 'T89c'|'T96c'|'T01c'|'TS05c' Then all parameters will be needed ************ Date: Date in format yyyymmdd. UT: Time in format hh.hh (hh + mm/60.0 + ss/3600.0). CoordIn: Coordinate system of input position, by default 'SM' (Solar-Magnetic), can be set to 'GSM' (Geocentric Solar Magnetospheric). CoordOut: Coordinate system of output positions and field vectors, by default 'SM', can be set to 'GSM'. Alt: Altitude to stop tracing at - default = 100km MaxLen: maximum number of trace steps DSMax: Maximum step size iopt: integer for controlling T89c model parmod: 10-element floating point array to control T96c,T01c and TS05c models, for T96: parmod[0] = Pdyn (nPa) parmod[1] = Dst (nT) parmod[2] = IMF By (nT) parmod[3] = IMF Bz (nT) for T01: parmod[0] = Pdyn (nPa) parmod[1] = Dst (nT) parmod[2] = IMF By (nT) parmod[3] = IMF Bz (nT) parmod[4] = G1 parameter (See Tsyganenko [2001]) parmod[5] = G2 parameter (See Tsyganenko [2001]) for TS05: parmod[0] = Pdyn (nPa) parmod[1] = Dst (nT) parmod[2] = IMF By (nT) parmod[3] = IMF Bz (nT) parmod[4] = W1 parameter (See Tsyganenko and Sitnov [2005]) parmod[5] = W2 parameter (See Tsyganenko and Sitnov [2005]) parmod[6] = W3 parameter (See Tsyganenko and Sitnov [2005]) parmod[7] = W4 parameter (See Tsyganenko and Sitnov [2005]) parmod[8] = W5 parameter (See Tsyganenko and Sitnov [2005]) parmod[9] = W6 parameter (See Tsyganenko and Sitnov [2005]) tilt: Geodipole tilt angle - if set to NaN then will be calculated using Date and ut Vx,Vy,Vz: IMF velocity components KT17: ModelArgs = (Rsun,DistIndex,MaxLen,InitStep,MaxStepSize,LimType) Rsun: radial distance from the Sun in AU DistIndex: Disturbance index (0.0 - 100.0) MaxLen: Maximum number of steps for trace InitStep: Starting step size. MaxStepSize: Maximum step size LimType: Integer value to define where to stop the field trace (default 0): 0: Terminate trace at planet surface and magnetopause 1: Confine to box -6 < x < 2, -4 < y < 4, -4 < z < 4 2: Confine to box and terminate at planet 3: Terminate trace at planet 4: Trace to MP, Planet and stop at 10Rm KT14: ModelArgs = (MaxLen,InitStep,MaxStep,LimType,Rsm,t1,t2) MaxLen: Maximum number of steps for trace InitStep: Starting step size. MaxStepSize: Maximum step size LimType: Integer value to define where to stop the field trace (default 0): 0: Terminate trace at planet surface and magnetopause 1: Confine to box -6 < x < 2, -4 < y < 4, -4 < z < 4 2: Confine to box and terminate at planet 3: Terminate trace at planet 4: Trace to MP, Planet and stop at 10Rm Rsm: Subsolar magnetopause radius (default=1.42). t1: Tail disk current strength (default=7.37). t2: Tail quasi-harris current sheet strength (default=2.16). Dipole: ModelArgs = [Beq] Beq: Megnatic field strength at equator in nT (Default=-31200.0). Delta: Separation between two traced field lines Polarization: 'none'|'toroidal'|'poloidal' Core: This only applies to the KT14/KT17 field, as it will include tracing to the core of the planet rather than the surface. Returns: TracedField object Array storing distance along the field line. if Polarization is 'toroidal' or 'poloidal', then h_alpha array is also returned ''' #First of all check if the model that has been requested is imported or not! if Model in ['KT14','KT17'] and not Globals.kt17_loaded: #If the kt17 model hasn't been installed in the expected location #then this will happen print('KT17 module is required for this model') return (None,None,None) if Model in ['T89','T96','T01','TS05'] and not Globals.geopack_loaded: #If the geopack model hasn't been installed in the expected location #then this will happen print('Geopack module is required for this model') return (None,None,None) #get the default model arguments keys = list(Globals.DefArgs.keys()) if not Model in keys: print("Model '",Model,"' not found, available options are:") print("'KT14','KT17','T89','T96','T01','TS05', or 'Dipole'") return (None,None,None) kArgs = Globals.DefArgs[Model] keys = list(kArgs.keys()) kwkeys = list(kwargs.keys()) #update model arguments OtherKeys = ['parmod','iopt','Vx','Vy','Vz','Kp','Pdyn','SymH','By','Bz'] for k in keys: if k in kwkeys: kArgs[k] = kwargs[k] for k in OtherKeys: if k in kwkeys: kArgs[k] = kwargs[k] kArgs['Model'] = Model #get Delta and Rp if Delta is None: Delta = 0.05 if Model in ['KT14','KT17']: Rp = 2440.0 else: Rp = 6380.0 #create args args = [pos[0],pos[1],pos[2]] #Check that we have a date and time if we need it if Model in ['T89','T96','T01','TS05']: if Date is None or ut is None: print('Please set the Date and ut keywords to use Earth models') return (None,None,None) args.append(Date) args.append(ut) #return a function which can be used to call the model ModelFunc = GetModelFunction(**kArgs) #get the first field line T0 = ModelFunc(*args) if not hasattr(T0,'x'): T0.x = T0.xsm T0.y = T0.ysm T0.z = T0.zsm1 T0.Bx = T0.Bxsm T0.By = T0.Bysm T0.Bz = T0.Bzsm if not hasattr(T0,'MltE'): T0.MltE = T0.MLTe if hasattr(T0.nstep,'shape'): _FlattenTrace(T0) _SortModelDirection(T0) #return T0 s0 = np.zeros(T0.nstep) for i in range(1,T0.nstep): s0[i] = s0[i-1] + np.sqrt((T0.x[i]-T0.x[i-1])**2+(T0.y[i]-T0.y[i-1])**2+(T0.z[i]-T0.z[i-1])**2)*Rp print(Polarization) if Polarization == 'none' or Polarization is None: return (T0,s0) elif Polarization == 'poloidal': eqpos1 = np.array([-(T0.Lshell-Delta)*np.cos(T0.MltE*15.0*np.pi/180.0),-(T0.Lshell-Delta)*np.sin(T0.MltE*15.0*np.pi/180.0),0.0]) elif Polarization == 'toroidal': dmlt = 2.0*np.arcsin(Delta*0.5/T0.Lshell)*180.0/(np.pi*15.0) eqpos1 = np.array([-T0.Lshell*np.cos((T0.MltE+dmlt)*15.0*np.pi/180.0),-T0.Lshell*np.sin((T0.MltE+dmlt)*15.0*np.pi/180.0),0.0]) elif isinstance(Polarization,float) or isinstance(Polarization,np.float32) or isinstance(Polarization,np.float64): #here, we make a small step in some arbitrary direction #get x and y at the magnetic equator mlt = T0.MltE*np.pi/12.0 L = T0.Lshell xe0 = -L*np.cos(mlt) ye0 = -L*np.sin(mlt) #convert Polarization from degrees to radians alpha = Polarization*np.pi/180.0 #calculate dt and dp dt = Delta*np.sin(alpha) dp = Delta*np.cos(alpha) print(dt,dp) #get beta beta = mlt - np.pi #now rotate dx = dp*np.cos(beta) - dt*np.sin(beta) dy = dp*np.sin(beta) + dt*np.cos(beta) #now we have the new position eqpos1 = np.array([xe0+dx,ye0+dy,0.0]) #create new args if not Date is None: args1 = (eqpos1[0],eqpos1[1],eqpos1[2],Date,ut) else: args1 = (eqpos1[0],eqpos1[1],eqpos1[2]) T1 = ModelFunc(*args1) if not hasattr(T1,'x'): T1.x = T1.xsm T1.y = T1.ysm T1.z = T1.zsm T1.Bx = T1.Bxsm T1.By = T1.Bysm T1.Bz = T1.Bzsm if not hasattr(T1,'MltE'): T1.MltE = T1.MLTe if hasattr(T1.nstep,'shape'): _FlattenTrace(T1) _SortModelDirection(T1) s1 = np.zeros(T1.nstep) for i in range(1,T1.nstep): s1[i] = s1[i-1] + np.sqrt((T1.x[i]-T1.x[i-1])**2+(T1.y[i]-T1.y[i-1])**2+(T1.z[i]-T1.z[i-1])**2)*Rp #return T0,T1,s0,s1 d = np.zeros(T0.nstep,dtype='float32') #print((s1,T1.x[0:s1.size])) _,uinds = np.unique(s1,return_index=True) fx = InterpolatedUnivariateSpline(s1[uinds],T1.x[uinds]) fy = InterpolatedUnivariateSpline(s1[uinds],T1.y[uinds]) fz = InterpolatedUnivariateSpline(s1[uinds],T1.z[uinds]) def PosFn(s): return fx(s),fy(s),fz(s) def DistFn(s,j): return np.sqrt((fx(s)-T0.x[j])**2.0 + (fy(s)-T0.y[j])**2.0 + (fz(s)-T0.z[j])**2.0) for i in range(0,T0.nstep): res = minimize(DistFn,s0[i],args=(i),method='Nelder-Mead') print(res.nit) d[i] = DistFn(res.x,i)*Rp h_alpha = d/(Delta*Rp) print(h_alpha) return (T0,s0,h_alpha)
b54a31ae9d0c919895d7e4849e0c88033c079784
3fd8a3e3f37f9db258df63d8565239b8b8be0f24
/basic_python/recursive1.py
0f193c317a780debbb813484ea13ccb457dd86e4
[]
no_license
raveena17/workout_problems
713a3e1a6ec513c1ee8b878519171150c6858aa4
004812cb7abf096d6f5d20181a29c16f8daaac55
refs/heads/master
2021-03-12T19:27:08.013266
2017-09-08T16:11:32
2017-09-08T16:11:32
102,878,449
0
0
null
null
null
null
UTF-8
Python
false
false
133
py
def fact(n): if n==1: return 1 else: return n*fact(n-1) #fact(8)-----40320 # fact(5)-----120
210cf835a8be8b9d470daf96cd61f49319e29fe2
0fd5793e78e39adbfe9dcd733ef5e42390b8cc9a
/python3/16_Web_Services/f_web_application/c_WSGI/a_simple_app.py
bbc45b452f311ac1047e899d9562b58b27dbb7e0
[]
no_license
udhayprakash/PythonMaterial
3ea282ceb4492d94d401e3bc8bad9bf6e9cfa156
e72f44e147141ebc9bf9ec126b70a5fcdbfbd076
refs/heads/develop
2023-07-08T21:07:33.154577
2023-07-03T10:53:25
2023-07-03T10:53:25
73,196,374
8
5
null
2023-05-26T09:59:17
2016-11-08T14:55:51
Jupyter Notebook
UTF-8
Python
false
false
530
py
""" Purpose: To create a dynamic website WSGI - Web Server Gateway Interface - It is a specification that describes how web servers communicate with web applications. - WSGI has been specified in PEP 3333. """ from wsgiref.simple_server import make_server def hello_world_app(environ, start_response): status = "200 OK" headers = [("Content-type", "text/plain")] start_response(status, headers) return [b"Hello, World!"] httpd = make_server("localhost", 8000, hello_world_app) httpd.serve_forever()
8c741bc818878bd6a70054719d84fc8bafd35448
f1340e9051164cace1b2c8c884dd51be18651972
/tests/unit/test__algebraic_intersection.py
b53e0df13098488a455d033979e656da103013ad
[ "Apache-2.0" ]
permissive
fudp/bezier
250aa9481c50ab1bca13789bef6f742e65404878
4f941f82637a8e70a5b159a9203132192e23406b
refs/heads/master
2020-04-30T14:28:34.566074
2018-12-06T20:19:09
2018-12-06T20:19:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
54,796
py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import unittest.mock import numpy as np try: import scipy.linalg.lapack as SCIPY_LAPACK except ImportError: # pragma: NO COVER SCIPY_LAPACK = None import six # noqa: I202 from tests import utils as base_utils from tests.unit import utils FLOAT64 = np.float64 # pylint: disable=no-member SPACING = np.spacing # pylint: disable=no-member LOCAL_EPS = 0.5 ** 25 # 2 * sqrt(machine precision) class Test__evaluate3(unittest.TestCase): @staticmethod def _call_function_under_test(nodes, x_val, y_val): from bezier import _algebraic_intersection return _algebraic_intersection._evaluate3(nodes, x_val, y_val) @staticmethod def _compute_expected(x_val, y_val): return 289.0 * ( ((17.0 * x_val - 81.0) * x_val + 135.0) * x_val - 27.0 * y_val ) def test_it(self): # f(x, y) = 289(17 x^3 - 81 x^2 + 135 x - 27 y) nodes = np.asfortranarray([[0.0, 1.0, 2.0, 3.0], [0.0, 5.0, 1.0, 5.0]]) xy_vals = utils.get_random_nodes(shape=(50, 2), seed=81390, num_bits=8) for x_val, y_val in xy_vals: result = self._call_function_under_test(nodes, x_val, y_val) expected = self._compute_expected(x_val, y_val) self.assertAlmostEqual(result, expected, delta=LOCAL_EPS) class Test_evaluate(unittest.TestCase): @staticmethod def _call_function_under_test(nodes, x_val, y_val): from bezier import _algebraic_intersection return _algebraic_intersection.evaluate(nodes, x_val, y_val) def test_point(self): nodes = np.asfortranarray([[1.0], [1.0]]) with self.assertRaises(ValueError): self._call_function_under_test(nodes, 0.0, 0.0) def test_linear(self): # f(x, y) = -4 x + y + 3 nodes = np.asfortranarray([[1.0, 2.0], [1.0, 5.0]]) result0 = self._call_function_under_test(nodes, 0.0, 0.0) self.assertEqual(result0, 3.0) result1 = self._call_function_under_test(nodes, 0.0, 1.0) self.assertEqual(result1, 4.0) result2 = self._call_function_under_test(nodes, 1.0, 0.0) self.assertEqual(result2, -1.0) result3 = self._call_function_under_test(nodes, 1.0, 1.0) self.assertEqual(result3, 0.0) # f(x, y) = (-12 x + 8 y - 5) / 32 nodes = np.asfortranarray([[0.0, 0.25], [0.625, 1.0]]) result0 = self._call_function_under_test(nodes, 0.0, 0.0) self.assertEqual(result0, -5.0 / 32) result1 = self._call_function_under_test(nodes, 0.0, 1.0) self.assertEqual(result1, 3.0 / 32) result2 = self._call_function_under_test(nodes, 1.0, 0.0) self.assertEqual(result2, -17.0 / 32) result3 = self._call_function_under_test(nodes, 1.0, 1.0) self.assertEqual(result3, -9.0 / 32) # f(x, y) = -x nodes = np.asfortranarray([[0.0, 0.0], [0.0, 1.0]]) vals = np.linspace(0.0, 1.0, 9) for x_val in vals: for y_val in vals: result = self._call_function_under_test(nodes, x_val, y_val) self.assertEqual(result, -x_val) def test_quadratic(self): # f(x, y) = x^2 + 4 x - 4 y nodes = np.asfortranarray([[0.0, 1.0, 2.0], [0.0, 1.0, 3.0]]) values = [ self._call_function_under_test(nodes, 0.0, 0.0), self._call_function_under_test(nodes, 1.0, 0.0), self._call_function_under_test(nodes, 2.0, 0.0), self._call_function_under_test(nodes, 0.0, 1.0), self._call_function_under_test(nodes, 1.0, 1.0), self._call_function_under_test(nodes, 0.0, 2.0), ] expected = [0.0, 5.0, 12.0, -4.0, 1.0, -8.0] self.assertEqual(values, expected) # f(x, y) = (x - y)^2 - y nodes = np.asfortranarray([[0.75, -0.25, -0.25], [0.25, -0.25, 0.25]]) xy_vals = utils.get_random_nodes( shape=(50, 2), seed=7930932, num_bits=8 ) values = [] expected = [] for x_val, y_val in xy_vals: values.append(self._call_function_under_test(nodes, x_val, y_val)) expected.append((x_val - y_val) * (x_val - y_val) - y_val) self.assertEqual(values, expected) def test_cubic(self): # f(x, y) = 13824 (x^3 - 24 y^2) nodes = np.asfortranarray( [[6.0, -2.0, -2.0, 6.0], [-3.0, 3.0, -3.0, 3.0]] ) xy_vals = utils.get_random_nodes( shape=(50, 2), seed=238382, num_bits=8 ) for x_val, y_val in xy_vals: result = self._call_function_under_test(nodes, x_val, y_val) expected = 13824.0 * (x_val * x_val * x_val - 24.0 * y_val * y_val) self.assertAlmostEqual(result, expected, delta=LOCAL_EPS) def test_quartic(self): from bezier import _helpers # f(x, y) = -28 x^4 + 56 x^3 - 36 x^2 + 8 x - y nodes = np.asfortranarray( [[0.0, 0.25, 0.5, 0.75, 1.0], [0.0, 2.0, -2.0, 2.0, 0.0]] ) degree = nodes.shape[1] - 1 with self.assertRaises(_helpers.UnsupportedDegree) as exc_info: self._call_function_under_test(nodes, 0.0, 0.0) self.assertEqual(exc_info.exception.degree, degree) self.assertEqual(exc_info.exception.supported, (1, 2, 3)) class Test_eval_intersection_polynomial(unittest.TestCase): @staticmethod def _call_function_under_test(nodes1, nodes2, t): from bezier import _algebraic_intersection return _algebraic_intersection.eval_intersection_polynomial( nodes1, nodes2, t ) def test_degrees_1_1(self): # f1(x, y) = (8 y - 3) / 8 nodes1 = np.asfortranarray([[0.0, 1.0], [0.375, 0.375]]) # x2(t), y2(t) = 1 / 2, 3 s / 4 nodes2 = np.asfortranarray([[0.5, 0.5], [0.0, 0.75]]) values = [ self._call_function_under_test(nodes1, nodes2, 0.0), self._call_function_under_test(nodes1, nodes2, 0.5), self._call_function_under_test(nodes1, nodes2, 1.0), ] # f1(x2(t), y2(t)) = 3 (2 t - 1) / 8 expected = [-0.375, 0.0, 0.375] self.assertEqual(values, expected) def test_degrees_1_2(self): # f1(x, y) = 2 (4 x + 3 y - 24) nodes1 = np.asfortranarray([[0.0, 6.0], [8.0, 0.0]]) # x2(t), y2(t) = 9 t, 18 t (1 - t) nodes2 = np.asfortranarray([[0.0, 4.5, 9.0], [0.0, 9.0, 0.0]]) values = [ self._call_function_under_test(nodes1, nodes2, 0.0), self._call_function_under_test(nodes1, nodes2, 0.25), self._call_function_under_test(nodes1, nodes2, 0.5), self._call_function_under_test(nodes1, nodes2, 0.75), self._call_function_under_test(nodes1, nodes2, 1.0), ] # f1(x2(t), y2(t)) = 12 (4 - 3 t) (3 t - 1) expected = [-48.0, -9.75, 15.0, 26.25, 24.0] self.assertEqual(values, expected) class Test__to_power_basis11(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection._to_power_basis11(nodes1, nodes2) def test_it(self): # f1(x, y) = -(12 x - 8 y + 5) / 32 nodes1 = np.asfortranarray([[0.0, 0.25], [0.625, 1.0]]) # x2(t), y2(t) = (2 - 3 t) / 4, (3 t + 2) / 4 nodes2 = np.asfortranarray([[0.5, -0.25], [0.5, 1.25]]) # f1(x2(t), y2(t)) = (15 t - 7) / 32 result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([-7.0, 15.0]) / 32.0 self.assertEqual(result, expected) class Test__to_power_basis12(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection._to_power_basis12(nodes1, nodes2) def test_it(self): # f1(x, y) = (2 y - 1) / 2 nodes1 = np.asfortranarray([[0.0, 1.0], [0.5, 0.5]]) # x2(t), y2(t) = t, 2 t (1 - t) nodes2 = np.asfortranarray([[0.0, 0.5, 1.0], [0.0, 1.0, 0.0]]) # f1(x2(t), y2(t)) = -(2 t - 1)^2 / 2 result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([-0.5, 2.0, -2.0]) self.assertEqual(result, expected) class Test__to_power_basis13(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection._to_power_basis13(nodes1, nodes2) def test_it(self): # f1(x, y) = -(152 x + 112 y - 967) / 64 nodes1 = np.asfortranarray([[2.5625, 0.8125], [5.15625, 7.53125]]) # x2(t), y2(t) = 3 (14 t + 1) / 8, 18 t^3 - 27 t^2 + 3 t + 7 nodes2 = np.asfortranarray( [[0.375, 2.125, 3.875, 5.625], [7.0, 8.0, 0.0, 1.0]] ) # f1(x2(t), y2(t)) = -63 (t - 1) (4 t - 1)^2 / 32 result = self._call_function_under_test(nodes1, nodes2) # The 1-3 method avoids a division by 3.0 expected = ( 3.0 * (-63.0 / 32.0) * np.asfortranarray([-1.0, 9.0, -24.0, 16.0]) ) self.assertEqual(result, expected) class Test__to_power_basis_degree4(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection._to_power_basis_degree4(nodes1, nodes2) def test_degrees_2_2(self): # f1(x, y) = (x^2 - 4 x y + 4 y^2 - y) / 16 nodes1 = np.asfortranarray( [[0.375, -0.125, -0.125], [0.0625, -0.0625, 0.0625]] ) # x2(t), y2(t) = (2 t - 3) (2 t - 1) / 4, (2 t - 1)^2 / 4 nodes2 = np.asfortranarray([[0.75, -0.25, -0.25], [0.25, -0.25, 0.25]]) # f1(x2(t), y2(t)) = (2 t - 1)^3 (2 t + 3) / 256 result = self._call_function_under_test(nodes1, nodes2) # The function avoids a division by 3.0 expected = (3.0 / 256.0) * np.asfortranarray( [-3.0, 16.0, -24.0, 0.0, 16.0] ) self.assertEqual(result, expected) def test_degrees_1_4(self): # f1(x, y) = 4 (y - 3) nodes1 = np.asfortranarray([[0.0, 4.0], [3.0, 3.0]]) # x2(t), y2(t) = 4 s, 2 s (s - 1) (5 s^2 - 5 s - 2) nodes2 = np.asfortranarray( [[0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 3.0, 1.0, 0.0]] ) # f1(x2(t), y2(t)) = 4 (10 t^4 - 20 t^3 + 6 t^2 + 4 t - 3) result = self._call_function_under_test(nodes1, nodes2) # The function avoids a division by 3.0 expected = 3.0 * np.asfortranarray([-12.0, 16.0, 24.0, -80.0, 40.0]) self.assertEqual(result, expected) class Test__to_power_basis23(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection._to_power_basis23(nodes1, nodes2) def test_it(self): # f1(x, y) = 4 (4 x^2 - 12 x - 4 y + 11) nodes1 = np.asfortranarray([[0.5, 1.5, 2.5], [1.5, -0.5, 1.5]]) # x2(t), y2(t) = 3 t, t (4 t^2 - 6 t + 3) nodes2 = np.asfortranarray( [[0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 0.0, 1.0]] ) # f1(x2(t), y2(t)) = 4 (2 s - 1)^2 (4 s - 11) result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([44, -192, 240, -64, 0.0, 0.0, 0.0]) self.assertLess(np.abs(result - expected).max(), LOCAL_EPS) class Test__to_power_basis_degree8(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection._to_power_basis_degree8(nodes1, nodes2) def test_degrees_2_4(self): # f1(x, y) = 2 (9 x - 2 y^2 - 6 y) nodes1 = np.asfortranarray([[0.0, 1.0, 4.0], [0.0, 1.5, 3.0]]) # x2(t), y2(t) = 4 t, -t (7 t^3 - 6 t - 4) nodes2 = np.asfortranarray( [[0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 3.0, 6.0, 3.0]] ) # f1(x2(t), y2(t)) = ( # 4 t (t - 1) (49 t^6 + 49 t^5 - 35 t^4 - # 91 t^3 - 76 t^2 - 28 t + 6)) result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray( [0.0, -24.0, 136.0, 192.0, 60.0, -224.0, -336.0, 0.0, 196.0] ) self.assertLess(np.abs(result - expected).max(), LOCAL_EPS) class Test__to_power_basis33(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection._to_power_basis33(nodes1, nodes2) def test_it(self): # f1(x, y) = x^3 - 9 x^2 + 27 x - 27 y nodes1 = np.asfortranarray( [[0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 1.0, 1.0]] ) # x2(t), y2(t) = (1 - t) (t^2 + t + 1), 3 (1 - t) nodes2 = np.asfortranarray( [[1.0, 1.0, 1.0, 0.0], [3.0, 2.0, 1.0, 0.0]] ) # f1(x2(t), y2(t)) = ( # -(s - 1)^2 (s + 2) (s^6 + 3 s^4 + 4 s^3 + 9 s^2 + 6 s + 31) result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray( [-62, 81, 0, -12, 0, 0, -6, 0, 0, -1], dtype=FLOAT64 ) self.assertLess(np.abs(result - expected).max(), 2.0 * LOCAL_EPS) class Test_to_power_basis(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection.to_power_basis(nodes1, nodes2) def test_degrees_1_1(self): # f1(x, y) = -x nodes1 = np.asfortranarray([[0.0, 0.0], [0.0, 1.0]]) # x2(t), y2(t) = 1, t nodes2 = np.asfortranarray([[1.0, 1.0], [0.0, 1.0]]) # f1(x2(t), y2(t)) = -1 result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([-1.0, 0.0]) self.assertEqual(result, expected) def test_degrees_1_2(self): # f1(x, y) = 2 (4 x + 3 y - 24) nodes1 = np.asfortranarray([[0.0, 6.0], [8.0, 0.0]]) # x2(t), y2(t) = 9 t, 18 t (1 - t) nodes2 = np.asfortranarray([[0.0, 4.5, 9.0], [0.0, 9.0, 0.0]]) # f1(x2(t), y2(t)) = 12 (4 - 3 t) (3 t - 1) result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([-48.0, 180.0, -108.0]) self.assertEqual(result, expected) def test_degrees_1_3(self): # f1(x, y) = -(2 x - y - 1) / 2 nodes1 = np.asfortranarray([[0.5, 1.0], [0.0, 1.0]]) # x2(t), y2(t) = -t (2 t^2 - 3 t - 3) / 4, -(3 t^3 - 3 t - 1) / 2 nodes2 = np.asfortranarray( [[0.0, 0.25, 0.75, 1.0], [0.5, 1.0, 1.5, 0.5]] ) # f1(x2(t), y2(t)) = -(t^3 + 3 t^2 - 3) / 4 result = self._call_function_under_test(nodes1, nodes2) # The 1-3 method avoids a division by 3.0 expected = 3.0 * np.asfortranarray([0.75, 0.0, -0.75, -0.25]) self.assertEqual(result, expected) def test_degrees_1_4(self): # f1(x, y) = 4 y - 3 x nodes1 = np.asfortranarray([[0.0, 4.0], [0.0, 3.0]]) # x2(t), y2(t) = 4 t, -t (7 t^3 - 6 t - 4) nodes2 = np.asfortranarray( [[0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 3.0, 6.0, 3.0]] ) # f1(x2(t), y2(t)) = 4 t (1 - t) (7 t^2 + 7 t + 1) result = self._call_function_under_test(nodes1, nodes2) # The function avoids a division by 3.0 expected = 3.0 * np.asfortranarray([0.0, 4.0, 24.0, 0.0, -28.0]) self.assertEqual(result, expected) def test_degrees_2_2(self): # f1(x, y) = (x^2 - 2 x y + 4 x + y^2 + 4 y - 5) / 4 nodes1 = np.asfortranarray([[1.0, 0.75, 0.0], [0.0, 0.75, 1.0]]) # x2(t), y2(t) = (t - 1) (5 t - 8) / 8, -(t - 1) (7 t + 8) / 8 nodes2 = np.asfortranarray([[1.0, 0.1875, 0.0], [1.0, 0.9375, 0.0]]) # f1(x2(t), y2(t)) = (9 t^4 - 18 t^3 + 5 t^2 - 28 t + 12) / 16 result = self._call_function_under_test(nodes1, nodes2) # The function avoids a division by 3.0 expected = (3.0 / 16.0) * np.asfortranarray( [12.0, -28.0, 5.0, -18.0, 9.0] ) self.assertEqual(result, expected) def test_degrees_2_3(self): # f1(x, y) = 81 (2 x^2 - 2 x - y + 1) / 128 nodes1 = np.asfortranarray([[0.25, 0.625, 1.0], [0.625, 0.25, 1.0]]) # x2(t), y2(t) = -t (2 t^2 - 3 t - 3) / 4, -(3 t^3 - 3 t - 1) / 2 nodes2 = np.asfortranarray( [[0.0, 0.25, 0.75, 1.0], [0.5, 1.0, 1.5, 0.5]] ) # f1(x2(t), y2(t)) = ( # 81 (t + 1) (4 t^5 - 16 t^4 + 13 t^3 + 25 t^2 - 28 t + 4) / 1024) result = self._call_function_under_test(nodes1, nodes2) expected = (81.0 / 1024.0) * np.asfortranarray( [4, -24, -3, 38, -3, -12, 4] ) self.assertTrue( np.allclose(result, expected, atol=0.0, rtol=LOCAL_EPS) ) def test_degrees_2_4(self): # f1(x, y) = 2*(9*x - 2*y**2 - 6*y) nodes1 = np.asfortranarray([[0.0, 1.0, 4.0], [0.0, 1.5, 3.0]]) # x2(t), y2(t) = 4*t, 2*t*(t - 1)*(5*t**2 - 5*t - 2)]]) nodes2 = np.asfortranarray( [[0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 3.0, 1.0, 0.0]] ) # f1(x2(t), y2(t)) = ( # 8 t (50 t^7 - 200 t^6 + 260 t^5 - 80 t^4 - # 47 t^3 - 6 t^2 + 17 t - 3)) result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray( [0.0, -24.0, 136.0, -48.0, -376.0, -640.0, 2080.0, -1600.0, 400.0] ) self.assertLess(np.abs(result - expected).max(), LOCAL_EPS) def test_degrees_3_3(self): # f1(x, y) = -(13824 x^3 + 3456 x^2 y - 55296 x^2 + # 288 x y^2 - 2088 x y + 39816 x + 8 y^3 + # 129 y^2 + 6846 y - 6983) / 512 nodes1 = np.asfortranarray( [[0.0, 0.375, 0.625, 1.0], [1.0, -1.0, 0.0, 1.0]] ) # x2(t), y2(t) = -t (2 t^2 - 3 t - 3) / 4, -(3 t^3 - 3 t - 1) / 2 nodes2 = np.asfortranarray( [[0.0, 0.25, 0.75, 1.0], [0.5, 1.0, 1.5, 0.5]] ) # f1(x2(t), y2(t)) = ( # 13500 t^9 - 48600 t^8 + 1620 t^7 + 170451 t^6 - 171072 t^5 - # 146394 t^4 + 331686 t^3 + 10827 t^2 - 158418 t + 14107) / 2048 result = self._call_function_under_test(nodes1, nodes2) expected = ( np.asfortranarray( [ 14107, -158418, 10827, 331686, -146394, -171072, 170451, 1620, -48600, 13500, ] ) / 2048.0 ) self.assertTrue( np.allclose(result, expected, atol=0.0, rtol=LOCAL_EPS) ) def test_unsupported(self): nodes_yes1 = np.zeros((2, 2), order="F") nodes_yes2 = np.zeros((2, 3), order="F") nodes_yes3 = np.zeros((2, 4), order="F") nodes_no = np.zeros((2, 6), order="F") # Just make sure we fall through **all** of the implicit # ``else`` branches. with self.assertRaises(NotImplementedError): self._call_function_under_test(nodes_yes1, nodes_no) with self.assertRaises(NotImplementedError): self._call_function_under_test(nodes_yes2, nodes_no) with self.assertRaises(NotImplementedError): self._call_function_under_test(nodes_yes3, nodes_no) with self.assertRaises(NotImplementedError): self._call_function_under_test(nodes_no, nodes_no) class Test_polynomial_norm(unittest.TestCase): @staticmethod def _call_function_under_test(coeffs): from bezier import _algebraic_intersection return _algebraic_intersection.polynomial_norm(coeffs) def test_it(self): coeffs = np.asfortranarray([2.0, 1.0, 3.0]) result = self._call_function_under_test(coeffs) expected = np.sqrt(409.0 / 30.0) self.assertAlmostEqual(result, expected, delta=LOCAL_EPS) class Test_roots_in_unit_interval(utils.NumPyTestCase): @staticmethod def _call_function_under_test(coeffs): from bezier import _algebraic_intersection return _algebraic_intersection.roots_in_unit_interval(coeffs) def test_it(self): # P(t) = (t^2 + 1) (2 t - 1) (3 t - 1) (3 t - 2) coeffs = np.asfortranarray([-2.0, 13.0, -29.0, 31.0, -27.0, 18.0]) all_roots = self._call_function_under_test(coeffs) all_roots = np.sort(all_roots) self.assertEqual(all_roots.shape, (3,)) for index in (0, 1, 2): expected = (index + 2.0) / 6.0 self.assertAlmostEqual(all_roots[index], expected, delta=LOCAL_EPS) class Test__strip_leading_zeros(utils.NumPyTestCase): @staticmethod def _call_function_under_test(coeffs, **kwargs): from bezier import _algebraic_intersection return _algebraic_intersection._strip_leading_zeros(coeffs, **kwargs) def test_default_threshold(self): coeffs = np.asfortranarray([0.0, 1.0, 1.5]) result = self._call_function_under_test(coeffs) self.assertIs(result, coeffs) def test_custom_threshold(self): coeffs = np.asfortranarray([2.0, 0.0, 0.0, 0.5 ** 10]) result = self._call_function_under_test(coeffs) self.assertIs(result, coeffs) result = self._call_function_under_test(coeffs, threshold=0.5 ** 9) self.assertEqual(result, coeffs[:1]) class Test__check_non_simple(utils.NumPyTestCase): @staticmethod def _call_function_under_test(coeffs): from bezier import _algebraic_intersection return _algebraic_intersection._check_non_simple(coeffs) def test_extra_zeros(self): coeffs = np.asfortranarray([2.0, -3.0, 1.0, 0.0]) # Just make sure no exception was thrown. self.assertIsNone(self._call_function_under_test(coeffs)) def test_line(self): coeffs = np.asfortranarray([4.0, 1.0]) # Just make sure no exception was thrown. self.assertIsNone(self._call_function_under_test(coeffs)) def test_double_root(self): # f(t) = (t - 2)^2 coeffs = np.asfortranarray([4.0, -4.0, 1.0]) with self.assertRaises(NotImplementedError): self._call_function_under_test(coeffs) # f(t) = (t + 2)^2 (3 t + 2) (4 t + 19) coeffs = np.asfortranarray([152.0, 412.0, 346.0, 113.0, 12.0]) with self.assertRaises(NotImplementedError): self._call_function_under_test(coeffs) def test_scale_invariant(self): # f(t) = (t - 1) (t - 2) (t - 3) (t - 4) coeffs = np.asfortranarray([24.0, -50.0, 35.0, -10.0, 1.0]) # Make sure no exception was thrown. self.assertIsNone(self._call_function_under_test(coeffs)) for exponent in (-30, -20, -10, 10, 20, 30): new_coeffs = 0.5 ** exponent * coeffs self.assertIsNone(self._call_function_under_test(new_coeffs)) class Test__resolve_and_add(utils.NumPyTestCase): @staticmethod def _call_function_under_test( nodes1, s_val, final_s, nodes2, t_val, final_t ): from bezier import _algebraic_intersection return _algebraic_intersection._resolve_and_add( nodes1, s_val, final_s, nodes2, t_val, final_t ) def _helper(self, s, t): nodes1 = unittest.mock.sentinel.nodes1 nodes2 = unittest.mock.sentinel.nodes2 final_s = [] final_t = [] patch = unittest.mock.patch( "bezier._intersection_helpers.newton_refine", return_value=(s, t) ) with patch as mocked: self._call_function_under_test( nodes1, s, final_s, nodes2, t, final_t ) mocked.assert_called_once_with(s, nodes1, t, nodes2) return final_s, final_t def test_unchanged(self): s = 0.5 t = 0.25 final_s, final_t = self._helper(s, t) self.assertEqual(final_s, [s]) self.assertEqual(final_t, [t]) def test_to_zero(self): s = -0.5 ** 60 t = 0.5 final_s, final_t = self._helper(s, t) self.assertEqual(final_s, [0.0]) self.assertEqual(final_t, [t]) def test_still_negative(self): s = 0.125 t = -0.5 ** 20 final_s, final_t = self._helper(s, t) self.assertEqual(final_s, []) self.assertEqual(final_t, []) class Test_intersect_curves(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes1, nodes2): from bezier import _algebraic_intersection return _algebraic_intersection.intersect_curves(nodes1, nodes2) def test_degrees_1_1(self): # f1(x, y) = (8 y - 3) / 8 nodes1 = np.asfortranarray([[0.0, 1.0], [0.375, 0.375]]) # x2(t), y2(t) = 1 / 2, 3 s / 4 nodes2 = np.asfortranarray([[0.5, 0.5], [0.0, 0.75]]) # f1(x2(t), y2(t)) = 3 (2 t - 1) / 8 result = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([[0.5], [0.5]]) self.assertEqual(result, expected) def _degrees_1_2_helper(self, swapped=False): # f1(x, y) = 2 (4 x + 3 y - 24) nodes1 = np.asfortranarray([[0.0, 6.0], [8.0, 0.0]]) # x2(t), y2(t) = 9 t, 18 t (1 - t) nodes2 = np.asfortranarray([[0.0, 4.5, 9.0], [0.0, 9.0, 0.0]]) # f1(x2(t), y2(t)) = 12 (4 - 3 t) (3 t - 1) if swapped: row1, row2 = 1, 0 result = self._call_function_under_test(nodes2, nodes1) else: row1, row2 = 0, 1 result = self._call_function_under_test(nodes1, nodes2) self.assertEqual(result.shape, (2, 1)) self.assertAlmostEqual(result[row1, 0], 0.5, delta=LOCAL_EPS) self.assertAlmostEqual(result[row2, 0], 1.0 / 3.0, delta=LOCAL_EPS) def test_degrees_1_2(self): self._degrees_1_2_helper() def test_degrees_2_1(self): self._degrees_1_2_helper(swapped=True) def test_t_val_without_s_val(self): # f1(x, y) = 81 (2 x^2 - 2 x - y + 1) / 128 nodes1 = np.asfortranarray([[0.25, 0.625, 1.0], [0.625, 0.25, 1.0]]) # x2(t), y2(t) = -t (2 t^2 - 3 t - 3) / 4, -(3 t^3 - 3 t - 1) / 2 nodes2 = np.asfortranarray( [[0.0, 0.25, 0.75, 1.0], [0.5, 1.0, 1.5, 0.5]] ) # f1(x2(t), y2(t)) = ( # 81 (t + 1) (4 t^5 - 16 t^4 + 13 t^3 + 25 t^2 - 28 t + 4) / 1024) # NOTE: This polynomial has two roots inside the unit interval # t1 = 0.17072782629577715 and t2 = 0.8734528541508780397 but # they correspond to s-values s1 = -0.1367750984247189222649977 # and s2 = 0.8587897065534014787757 so only s2, t2 is returned. result = self._call_function_under_test(nodes1, nodes2) self.assertEqual(result.shape, (2, 1)) # 486 s^5 - 3726 s^4 + 13905 s^3 - 18405 s^2 + 6213 s + 1231 self.assertAlmostEqual( result[0, 0], float.fromhex("0x1.b7b348cf939b9p-1"), delta=LOCAL_EPS, ) # 4 t^5 - 16 t^4 + 13 t^3 + 25 t^2 - 28 t + 4 self.assertAlmostEqual( result[1, 0], float.fromhex("0x1.bf3536665a0cdp-1"), delta=LOCAL_EPS, ) def test_coincident(self): # f1(x, y) = -4 (4 x^2 + 4 x y - 16 x + y^2 + 8 y) nodes1 = np.asfortranarray([[0.0, 1.0, 4.0], [0.0, 2.0, 0.0]]) # x2(t), y2(t) = 3 (t + 1) (3 t + 7) / 8, -3 (t + 1) (3 t - 1) / 4 nodes2 = np.asfortranarray([[2.625, 4.5, 7.5], [0.75, 0.0, -3.0]]) # f1(x2(t), y2(t)) = 0 with self.assertRaises(NotImplementedError): self._call_function_under_test(nodes1, nodes2) class Test_normalize_polynomial(utils.NumPyTestCase): @staticmethod def _call_function_under_test(coeffs, **kwargs): from bezier import _algebraic_intersection return _algebraic_intersection.normalize_polynomial(coeffs, **kwargs) def test_nonzero(self): coeffs = np.asfortranarray([2.0]) result = self._call_function_under_test(coeffs) self.assertIs(result, coeffs) # Check changed in place. expected = np.asfortranarray([1.0]) self.assertEqual(result, expected) coeffs = np.asfortranarray([-2.0, 6.0]) result = self._call_function_under_test(coeffs) self.assertIs(result, coeffs) # Check changed in place. expected = np.asfortranarray([-1.0, 3.0]) self.assertEqual(result, expected) def test_actual_zero(self): for num_vals in (1, 2, 3, 4, 5): coeffs = np.zeros((num_vals,), order="F") result = self._call_function_under_test(coeffs) self.assertIsNot(result, coeffs) self.assertEqual(result, coeffs) def test_almost_zero(self): shape = (4,) coeffs = 0.5 ** 42 * np.random.random(shape) result = self._call_function_under_test(coeffs) self.assertIsNot(result, coeffs) self.assertEqual(result, np.zeros(shape, order="F")) coeffs = 0.5 ** 10 * np.random.random(shape) result = self._call_function_under_test(coeffs, threshold=0.5 ** 8) self.assertIsNot(result, coeffs) self.assertEqual(result, np.zeros(shape, order="F")) class Test__get_sigma_coeffs(utils.NumPyTestCase): @staticmethod def _call_function_under_test(coeffs): from bezier import _algebraic_intersection return _algebraic_intersection._get_sigma_coeffs(coeffs) def test_all_zero(self): for num_zeros in (1, 2, 3, 4): coeffs = np.zeros((num_zeros,), order="F") result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result self.assertIsNone(sigma_coeffs) self.assertEqual(degree, 0) self.assertEqual(effective_degree, 0) def test_linear(self): # s coeffs = np.asfortranarray([0.0, 1.0]) result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result self.assertEqual(sigma_coeffs, np.asfortranarray([0.0])) self.assertEqual(degree, 1) self.assertEqual(effective_degree, 1) def test_linear_drop_degree(self): # 4 (1 - s) coeffs = np.asfortranarray([4.0, 0.0]) result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result self.assertIsNone(sigma_coeffs) self.assertEqual(degree, 1) self.assertEqual(effective_degree, 0) def test_quadratic(self): # 2 s (s + 1) coeffs = np.asfortranarray([0.0, 1.0, 4.0]) result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result expected = np.asfortranarray([0.0, 0.5]) self.assertEqual(sigma_coeffs, expected) self.assertEqual(degree, 2) self.assertEqual(effective_degree, 2) def test_quadratic_drop_degree(self): # 2 (s - 2) (s - 1) coeffs = np.asfortranarray([4.0, 1.0, 0.0]) result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result self.assertEqual(sigma_coeffs, np.asfortranarray([2.0])) self.assertEqual(degree, 2) self.assertEqual(effective_degree, 1) def test_cubic(self): # -(s - 17) (s - 5) (s - 2) coeffs = np.asfortranarray([170.0, 127.0, 92.0, 64.0]) result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result expected = np.asfortranarray([2.65625, 5.953125, 4.3125]) self.assertEqual(sigma_coeffs, expected) self.assertEqual(degree, 3) self.assertEqual(effective_degree, 3) def test_cubic_drop_degree(self): # 3 (1 - s)^2 (3 s + 1) coeffs = np.asfortranarray([3.0, 4.0, 0.0, 0.0]) result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result self.assertEqual(sigma_coeffs, np.asfortranarray([0.25])) self.assertEqual(degree, 3) self.assertEqual(effective_degree, 1) def test_quartic(self): # 4 s^3 (5 - s) coeffs = np.asfortranarray([0.0, 0.0, 0.0, 5.0, 16.0]) result = self._call_function_under_test(coeffs) sigma_coeffs, degree, effective_degree = result expected = np.asfortranarray([0.0, 0.0, 0.0, 1.25]) self.assertEqual(sigma_coeffs, expected) self.assertEqual(degree, 4) self.assertEqual(effective_degree, 4) class Test_bernstein_companion(utils.NumPyTestCase): @staticmethod def _call_function_under_test(coeffs): from bezier import _algebraic_intersection return _algebraic_intersection.bernstein_companion(coeffs) def test_all_zero(self): for num_zeros in (1, 2, 3, 4): coeffs = np.zeros((num_zeros,), order="F") result = self._call_function_under_test(coeffs) companion, degree, effective_degree = result self.assertEqual(companion.shape, (0, 0)) self.assertEqual(degree, 0) self.assertEqual(effective_degree, 0) def test_quadratic(self): # 2 s (s + 1) coeffs = np.asfortranarray([0.0, 1.0, 4.0]) companion, degree, effective_degree = self._call_function_under_test( coeffs ) expected = np.asfortranarray([[-0.5, 0.0], [1.0, 0.0]]) self.assertEqual(companion, expected) self.assertEqual(degree, 2) self.assertEqual(effective_degree, 2) class Test_bezier_roots(utils.NumPyTestCase): @staticmethod def _call_function_under_test(coeffs): from bezier import _algebraic_intersection return _algebraic_intersection.bezier_roots(coeffs) def test_all_zero(self): for num_zeros in (1, 2, 3, 4): coeffs = np.zeros((num_zeros,), order="F") roots = self._call_function_under_test(coeffs) self.assertEqual(roots.shape, (0,)) def test_linear(self): # s coeffs = np.asfortranarray([0.0, 1.0]) roots = self._call_function_under_test(coeffs) self.assertEqual(roots, np.asfortranarray([0.0])) def test_linear_drop_degree(self): # 4 (1 - s) coeffs = np.asfortranarray([4.0, 0.0]) roots = self._call_function_under_test(coeffs) self.assertEqual(roots, np.asfortranarray([1.0])) def test_linear_as_elevated(self): # 2 coeffs = np.asfortranarray([2.0, 2.0]) roots = self._call_function_under_test(coeffs) self.assertEqual(roots.shape, (0,)) def test_quadratic(self): # 2 s (s + 1) coeffs = np.asfortranarray([0.0, 1.0, 4.0]) roots = self._call_function_under_test(coeffs) roots = np.sort(roots) expected = np.asfortranarray([-1.0, 0.0]) self.assertEqual(roots, expected) def test_quadratic_complex(self): # s^2 + 1 coeffs = np.asfortranarray([1.0, 1.0, 2.0]) roots = self._call_function_under_test(coeffs) roots = np.sort(roots) expected = np.asfortranarray([-1.0j, 1.0j]) ulp_errs = np.abs((roots - expected) / SPACING(expected.imag)) self.assertEqual(ulp_errs.shape, (2,)) self.assertLess(ulp_errs[0], 2) self.assertEqual(ulp_errs[0], ulp_errs[1]) def test_quadratic_drop_degree(self): # 2 (s - 2) (s - 1) coeffs = np.asfortranarray([4.0, 1.0, 0.0]) roots = self._call_function_under_test(coeffs) self.assertEqual(roots, np.asfortranarray([2.0, 1.0])) def test_quadratic_as_elevated(self): # 2 (s + 1) coeffs = np.asfortranarray([2.0, 3.0, 4.0]) roots = self._call_function_under_test(coeffs) self.assertEqual(roots, np.asfortranarray([-1.0])) def test_cubic(self): # -(s - 17) (s - 5) (s - 2) coeffs = np.asfortranarray([170.0, 127.0, 92.0, 64.0]) roots = self._call_function_under_test(coeffs) roots = np.sort(roots) expected = np.asfortranarray([2.0, 5.0, 17.0]) ulp_errs = np.abs((roots - expected) / SPACING(expected)) self.assertEqual(ulp_errs.shape, (3,)) self.assertLess(ulp_errs[0], 16) self.assertLess(ulp_errs[1], 512) self.assertLess(ulp_errs[2], 1024) def test_cubic_drop_degree(self): # 6 (1 - s)^2 (s + 1) coeffs = np.asfortranarray([6.0, 4.0, 0.0, 0.0]) roots = self._call_function_under_test(coeffs) self.assertEqual(roots, np.asfortranarray([-1.0, 1.0, 1.0])) def test_cubic_as_elevated(self): # 3 (s - 5) (4 s - 3) coeffs = np.asfortranarray([45.0, 22.0, 3.0, -12.0]) roots = self._call_function_under_test(coeffs) roots = np.sort(roots) expected = np.asfortranarray([0.75, 5.0]) ulp_errs = np.abs((roots - expected) / SPACING(expected)) self.assertEqual(ulp_errs.shape, (2,)) self.assertEqual(ulp_errs[0], 0.0) self.assertLess(ulp_errs[1], 64) def test_quartic(self): # 4 s^3 (5 - s) coeffs = np.asfortranarray([0.0, 0.0, 0.0, 5.0, 16.0]) roots = self._call_function_under_test(coeffs) roots = np.sort(roots) expected = np.asfortranarray([0.0, 0.0, 0.0, 5.0]) self.assertEqual(roots, expected) def test_quartic_as_twice_elevated(self): # 6 (s - 3) (s + 7) coeffs = np.asfortranarray([-126.0, -120.0, -113.0, -105.0, -96.0]) roots = self._call_function_under_test(coeffs) roots = np.sort(roots) expected = np.asfortranarray([-7.0, 3.0]) ulp_errs = np.abs((roots - expected) / SPACING(expected)) self.assertEqual(ulp_errs.shape, (2,)) self.assertLess(ulp_errs[0], 16384) self.assertLess(ulp_errs[1], 256) class Test_lu_companion(utils.NumPyTestCase): @staticmethod def _call_function_under_test(top_row, value): from bezier import _algebraic_intersection return _algebraic_intersection.lu_companion(top_row, value) def test_linear(self): # t + 3 top_row = np.asfortranarray([-3.0]) lu_mat, one_norm = self._call_function_under_test(top_row, -2.0) expected = np.asfortranarray([[-1.0]]) self.assertEqual(expected, lu_mat) self.assertEqual(one_norm, 1.0) def _check_lu(self, lu_mat, expected_a): from bezier import _helpers rows, cols = lu_mat.shape self.assertEqual(rows, cols) l_mat = np.asfortranarray( np.tril(lu_mat, -1) + np.eye(rows, order="F") ) u_mat = np.triu(lu_mat) a_mat = _helpers.matrix_product(l_mat, u_mat) self.assertEqual(a_mat, expected_a) def test_quadratic(self): # t^2 + 5 t - 4 top_row = np.asfortranarray([-5.0, 4.0]) value = 2.0 lu_mat, one_norm = self._call_function_under_test(top_row, value) expected = np.asfortranarray([[1.0, -value], [-7.0, -10.0]]) self.assertEqual(expected, lu_mat) self.assertEqual(one_norm, 8.0) expected_a = np.asfortranarray([[1.0, -value], [-7.0, 4.0]]) self._check_lu(lu_mat, expected_a) def test_cubic(self): # t^3 + 3 t^2 - t + 2 top_row = np.asfortranarray([-3.0, 1.0, -2.0]) value = 3.0 lu_mat, one_norm = self._call_function_under_test(top_row, value) expected = np.asfortranarray( [[1.0, -value, 0.0], [0.0, 1.0, -value], [-6.0, -17.0, -53.0]] ) self.assertEqual(expected, lu_mat) self.assertEqual(one_norm, 7.0) expected_a = np.asfortranarray( [[1.0, -value, 0.0], [0.0, 1.0, -value], [-6.0, 1.0, -2.0]] ) self._check_lu(lu_mat, expected_a) def test_quartic(self): # t^4 + t^3 + t^2 - 5 t - 2 top_row = np.asfortranarray([-1.0, -1.0, 5.0, 2.0]) value = 4.0 lu_mat, one_norm = self._call_function_under_test(top_row, value) expected = np.asfortranarray( [ [1.0, -value, 0.0, 0.0], [0.0, 1.0, -value, 0.0], [0.0, 0.0, 1.0, -value], [-5.0, -21.0, -79.0, -314.0], ] ) self.assertEqual(expected, lu_mat) self.assertEqual(one_norm, 10.0) expected_a = np.asfortranarray( [ [1.0, -value, 0.0, 0.0], [0.0, 1.0, -value, 0.0], [0.0, 0.0, 1.0, -value], [-5.0, -1.0, 5.0, 2.0], ] ) self._check_lu(lu_mat, expected_a) class Test__reciprocal_condition_number(utils.NumPyTestCase): @staticmethod def _call_function_under_test(lu_mat, one_norm): from bezier import _algebraic_intersection return _algebraic_intersection._reciprocal_condition_number( lu_mat, one_norm ) @unittest.mock.patch( "bezier._algebraic_intersection._scipy_lapack", new=None ) def test_without_scipy(self): lu_mat = np.zeros((2, 2), order="F") one_norm = 0.0 with self.assertRaises(OSError): self._call_function_under_test(lu_mat, one_norm) @unittest.mock.patch("bezier._algebraic_intersection._scipy_lapack") def test_dgecon_failure(self, _scipy_lapack): rcond = 0.5 info = -1 _scipy_lapack.dgecon.return_value = rcond, info one_norm = 1.0 with self.assertRaises(RuntimeError): self._call_function_under_test( unittest.mock.sentinel.lu_mat, one_norm ) _scipy_lapack.dgecon.assert_called_once_with( unittest.mock.sentinel.lu_mat, one_norm ) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_singular(self): # A = [[ 2. 3. ] # [ 1. 1.5]] one_norm = 4.5 lu_mat = np.asfortranarray([[2.0, 3.0], [0.5, 0.0]]) rcond = self._call_function_under_test(lu_mat, one_norm) self.assertEqual(rcond, 0.0) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_invertible(self): # A = [[ 4., 10., 0.], # [ 0., 16., 32.], # [ 2., -3., 0.]] one_norm = 32.0 lu_mat = np.asfortranarray( [[4.0, 10.0, 0.0], [0.0, 16.0, 32.0], [0.5, -0.5, 16.0]] ) rcond = self._call_function_under_test(lu_mat, one_norm) self.assertEqual(rcond, 0.0625) class Test_bezier_value_check(utils.NumPyTestCase): CUBIC_COEFFS = np.asfortranarray([170.0, 127.0, 92.0, 64.0]) @staticmethod def _call_function_under_test(coeffs, s_val, **kwargs): from bezier import _algebraic_intersection return _algebraic_intersection.bezier_value_check( coeffs, s_val, **kwargs ) def test_check_one_failure(self): # 3 (s^2 + 3) (2 - s) coeffs = np.asfortranarray([18.0, 15.0, 14.0, 12.0]) # 3 (1^2 + 3) (2 - 1) = 12 rhs_val = 10.0 self.assertFalse( self._call_function_under_test(coeffs, 1.0, rhs_val=rhs_val) ) def test_check_one_success(self): # 2 (1 - s) (s + 4) coeffs = np.asfortranarray([8.0, 5.0, 0.0]) self.assertTrue(self._call_function_under_test(coeffs, 1.0)) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_constant(self): input_s = (-9.0, -2.0, 0.0, 0.5, 1.0, 1.5, 4.0) values = (1.0, 2.0, 4.5, 0.0) for index, value in enumerate(values): count = index + 1 coeffs = value * np.ones((count,), order="F") for s_val in input_s: is_root = self._call_function_under_test( coeffs, s_val, rhs_val=value ) self.assertTrue(is_root) is_root = self._call_function_under_test( coeffs, s_val, rhs_val=value + 1.0 ) self.assertFalse(is_root) def test_all_zero(self): for num_zeros in (1, 2, 3, 4): coeffs = np.zeros((num_zeros,), order="F") is_root = self._call_function_under_test(coeffs, 0.0) self.assertTrue(is_root) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_linear(self): # 8 s + 1 coeffs = np.asfortranarray([1.0, 9.0]) for s_val in (-2.0, -0.125, 0.0, 0.75, 1.0, 9.5): rhs_val = 8.0 * s_val + 1.0 is_root = self._call_function_under_test( coeffs, s_val, rhs_val=rhs_val ) self.assertTrue(is_root) is_root = self._call_function_under_test( coeffs, s_val, rhs_val=rhs_val + 2.0 ) self.assertFalse(is_root) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_quadratic(self): # 2 s (s + 1) coeffs = np.asfortranarray([0.0, 1.0, 4.0]) s_vals = (-2.0, -1.0, -0.5, 0.0, 0.25, 1.0) check_values = [ self._call_function_under_test(coeffs, s_val) for s_val in s_vals ] self.assertEqual( check_values, [False, True, False, True, False, False] ) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_quadratic_complex(self): # s^2 + 1 coeffs = np.asfortranarray([1.0, 1.0, 2.0]) rhs_val = 10.0 s_vals = (-4.5, -3.0, -1.0, 0.0, 1.0, 3.0, 5.5) check_values = [ self._call_function_under_test(coeffs, s_val, rhs_val=rhs_val) for s_val in s_vals ] self.assertEqual( check_values, [False, True, False, False, False, True, False] ) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_quadratic_drop_degree(self): # 2 (s - 2) (s - 1) coeffs = np.asfortranarray([4.0, 1.0, 0.0]) s_vals = (-2.25, -1.0, 0.0, 1.0, 1.25, 2.0, 4.5) check_values = [ self._call_function_under_test(coeffs, s_val) for s_val in s_vals ] self.assertEqual( check_values, [False, False, False, True, False, True, False] ) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_quadratic_as_elevated(self): # 2 (s + 1) coeffs = np.asfortranarray([2.0, 3.0, 4.0]) s_vals = (-2.0, -1.0, -0.5, 0.0, 0.25, 1.0) check_values = [ self._call_function_under_test(coeffs, s_val) for s_val in s_vals ] self.assertEqual( check_values, [False, True, False, False, False, False] ) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_cubic(self): # -(s - 17) (s - 5) (s - 2) s_vals = (0.0, 1.0, 2.0, 3.0, 5.0, 6.0, 16.0, 17.0, 18.0) check_values = [ self._call_function_under_test(self.CUBIC_COEFFS, s_val) for s_val in s_vals ] self.assertEqual( check_values, [False, False, True, False, True, False, False, True, False], ) def _cubic_wiggle(self, root, max_ulps): # -(s - 17) (s - 5) (s - 2) coeffs = self.CUBIC_COEFFS eps = SPACING(root) for delta in six.moves.xrange(-32, 32 + 1): s_val = root + delta * eps self.assertTrue(self._call_function_under_test(coeffs, s_val)) s_val1 = root + max_ulps * eps s_val2 = root - max_ulps * eps s_val3 = root + (max_ulps + 1) * eps s_val4 = root - (max_ulps + 1) * eps self.assertTrue(self._call_function_under_test(coeffs, s_val1)) self.assertTrue(self._call_function_under_test(coeffs, s_val2)) check3 = self._call_function_under_test(coeffs, s_val3) check4 = self._call_function_under_test(coeffs, s_val4) self.assertFalse(check3 and check4) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_cubic_wiggle(self): self._cubic_wiggle(2.0, 308) # This wiggle room is especially egregious. if ( base_utils.IS_LINUX and not base_utils.IS_64_BIT ): # pragma: NO COVER self._cubic_wiggle(5.0, 8125) self._cubic_wiggle(17.0, 22504) else: self._cubic_wiggle(5.0, 8129) self._cubic_wiggle(17.0, 22503) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_cubic_drop_degree(self): # 3 (1 - s)^2 (3 s + 1) coeffs = np.asfortranarray([3.0, 4.0, 0.0, 0.0]) s_vals = (-2.5, -1.0, -1.0 / 3.0, 0.0, 0.5, 1.0, 1.25) check_values = [ self._call_function_under_test(coeffs, s_val) for s_val in s_vals ] self.assertEqual( check_values, [False, False, True, False, False, True, False] ) @unittest.skipIf(SCIPY_LAPACK is None, "SciPy not installed") def test_quartic(self): # 4 s^3 (5 - s) coeffs = np.asfortranarray([0.0, 0.0, 0.0, 5.0, 16.0]) s_vals = (-1.0, 0.0, 1.0, 3.5, 5.0, 7.25) check_values = [ self._call_function_under_test(coeffs, s_val) for s_val in s_vals ] self.assertEqual( check_values, [False, True, False, False, True, False] ) class Test_poly_to_power_basis(utils.NumPyTestCase): @staticmethod def _call_function_under_test(bezier_coeffs): from bezier import _algebraic_intersection return _algebraic_intersection.poly_to_power_basis(bezier_coeffs) def test_point(self): bezier_coeffs = np.asfortranarray([1.0]) expected = bezier_coeffs self.assertEqual( self._call_function_under_test(bezier_coeffs), expected ) def test_line(self): bezier_coeffs = np.asfortranarray([1.0, 2.0]) expected = np.asfortranarray([1.0, 1.0]) self.assertEqual( self._call_function_under_test(bezier_coeffs), expected ) def test_quadratic(self): bezier_coeffs = np.asfortranarray([-1.0, 0.0, 3.0]) expected = np.asfortranarray([-1.0, 2.0, 2.0]) self.assertEqual( self._call_function_under_test(bezier_coeffs), expected ) def test_cubic(self): bezier_coeffs = np.asfortranarray([1.0, 2.0, 1.0, 2.0]) expected = np.asfortranarray([1.0, 3.0, -6.0, 4.0]) self.assertEqual( self._call_function_under_test(bezier_coeffs), expected ) def test_unsupported(self): from bezier import _helpers bezier_coeffs = np.asfortranarray([1.0, 0.0, 0.0, 2.0, 1.0]) degree = bezier_coeffs.shape[0] - 1 with self.assertRaises(_helpers.UnsupportedDegree) as exc_info: self._call_function_under_test(bezier_coeffs) self.assertEqual(exc_info.exception.degree, degree) self.assertEqual(exc_info.exception.supported, (0, 1, 2, 3)) class Test_locate_point(unittest.TestCase): @staticmethod def _call_function_under_test(nodes, x_val, y_val): from bezier import _algebraic_intersection return _algebraic_intersection.locate_point(nodes, x_val, y_val) def test_reduced(self): nodes = np.asfortranarray([[0.0, 1.0, 3.0], [3.0, 2.0, 0.0]]) result = self._call_function_under_test(nodes, 1.25, 1.75) self.assertEqual(result, 0.5) def test_elevated_swap(self): nodes = np.asfortranarray([[0.0, 1.0, 1.0, 2.0], [1.0, 2.0, 3.0, 4.0]]) result = self._call_function_under_test(nodes, 1.40625, 3.25) self.assertEqual(result, 0.75) def test_with_point(self): nodes = np.asfortranarray([[0.0, 0.0], [1.0, 5.0]]) result = self._call_function_under_test(nodes, 0.0, 1.5) self.assertEqual(result, 0.125) def test_no_solution_first(self): nodes = np.asfortranarray([[0.0, 1.0, 3.0], [0.0, 1.0, 0.0]]) result = self._call_function_under_test(nodes, 4.0, 0.25) self.assertIsNone(result) def test_no_solution_second(self): nodes = np.asfortranarray([[0.0, 1.0, 3.0], [0.0, 1.0, 0.0]]) result = self._call_function_under_test(nodes, 0.5, 1.0) self.assertIsNone(result) class Test_all_intersections(utils.NumPyTestCase): @staticmethod def _call_function_under_test(nodes_first, nodes_second): from bezier import _algebraic_intersection return _algebraic_intersection.all_intersections( nodes_first, nodes_second ) def test_no_intersections(self): nodes1 = np.asfortranarray([[0.0, 1.0], [0.0, 1.0]]) nodes2 = np.asfortranarray([[3.0, 4.0], [3.0, 3.0]]) intersections, coincident = self._call_function_under_test( nodes1, nodes2 ) self.assertEqual(intersections.shape, (2, 0)) self.assertFalse(coincident) def test_success(self): # NOTE: ``nodes1`` is a specialization of [0, 0], [1/2, 1], [1, 1] # onto the interval [1/4, 1] and ``nodes`` is a specialization # of [0, 1], [1/2, 1], [1, 0] onto the interval [0, 3/4]. # We expect them to intersect at s = 1/3, t = 2/3, which is # the point [1/2, 3/4]. nodes1 = np.asfortranarray([[0.25, 0.625, 1.0], [0.4375, 1.0, 1.0]]) nodes2 = np.asfortranarray([[0.0, 0.375, 0.75], [1.0, 1.0, 0.4375]]) s_val = 1.0 / 3.0 t_val = 2.0 / 3.0 intersections, coincident = self._call_function_under_test( nodes1, nodes2 ) expected = np.asfortranarray([[s_val], [t_val]]) self.assertEqual(intersections, expected) self.assertFalse(coincident)
1b6ed3df6f5825b6934d6c29dfdaf515c683f87e
c31c8095ce4d4e9686e3e7ad6b004342e49671fa
/forum/migrations/0003_perso_image.py
86a65ba4537fa1611bb7668b648b1dbee17b6a3e
[]
no_license
Lionalisk/arrakambre
7bcc96dea2ca2a471572bfb1646256f1382ce25b
2caece9be5eebf21ddfa87a6c821c32b5d5019a2
refs/heads/master
2020-12-07T19:31:24.471090
2020-01-09T10:14:29
2020-01-09T10:14:29
232,782,172
0
0
null
null
null
null
UTF-8
Python
false
false
428
py
# Generated by Django 2.1.1 on 2018-09-16 11:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('forum', '0002_remove_post_titre'), ] operations = [ migrations.AddField( model_name='perso', name='image', field=models.CharField(default='a', max_length=20), preserve_default=False, ), ]
d711316308d6bd168c770b41a387e488cf228ba6
9d0d4db62ebc84460c7d6f53ac28cbe315407592
/py_files/lab10_mpc_reachability.py
df1dc97057fdf7da15f99a4e5d6c0ba9bceee7b7
[]
no_license
ZionDeng/Advanced-Control-Design
c471c44b3044b94e197147ec566811be8d1a5ffd
1e82cdd1b98e95a0d210808e89eff4536efc9e73
refs/heads/master
2023-01-29T07:50:21.805723
2020-12-09T15:48:56
2020-12-09T15:48:56
312,738,867
1
0
null
null
null
null
UTF-8
Python
false
false
10,051
py
# %% # Lab 10: Reachability Analysis for Constrained Inverted Pendulum Model (Solution) # x1 is the angle of the pendulum, # x2 is the angular velocity of the pendulum, and # u is the speed of the cart. # %% import numpy as np import scipy.signal import scipy.linalg from scipy.integrate import solve_ivp import matplotlib.pyplot as plt import polytope as pt Ts = 0.1 # Ts is the discrete sample-time. Ac = np.array([[0, 1], [2.5, -0.05]]) Bc = np.array([[0], [2.5]]) Cc = np.zeros((1,2)) Dc = np.zeros((1,1)) system = (Ac, Bc, Cc, Dc) A, B, C, D, dt = scipy.signal.cont2discrete(system, Ts) nx = np.size(A,0) # number of states nu = np.size(B,1) # number of inputs Q = np.eye(2) R = np.array([1]) uU = np.pi/10 uX1 = np.pi/4 uX2 = np.pi/2 def dlqr(A, B, Q, R): # solve Discrete Algebraic Riccatti equation P = scipy.linalg.solve_discrete_are(A, B, Q, R) # compute the LQR gain K = scipy.linalg.inv(B.T @ P @ B + R) @ (B.T @ P @ A) # stability check eigVals, eigVecs = scipy.linalg.eig(A - B @ K) return K, P Finf, Pinf = dlqr(A, B, Q, R) Acl = A - B @ Finf # %% # Polytope tools x1U = np.pi/4 x2U = np.pi/2 uU = np.pi/10 # constraint sets represented as polyhedra # state constraint X = pt.Polytope(np.array([[1.0, 0], [0, 1.0], [-1, 0], [0, -1]]), np.array([[x1U], [x2U], [x1U], [x2U]])) U = pt.Polytope(np.array([1, -1]).reshape(2,1), np.array([uU, uU]).reshape(2,1)) # Helper Function: def minkowski_sum(X, Y): # Minkowski sum between two polytopes based on # vertex enumeration. So, it's not fast for the # high dimensional polytopes with lots of vertices. V_sum = [] if isinstance(X, pt.Polytope): V1 = pt.extreme(X) else: # assuming vertices are in (N x d) shape. N # of vertices, d dimension V1 = X if isinstance(Y, pt.Polytope): V2 = pt.extreme(Y) else: V2 = Y for i in range(V1.shape[0]): for j in range(V2.shape[0]): V_sum.append(V1[i,:] + V2[j,:]) return pt.qhull(np.asarray(V_sum)) # %% positive invariant set def precursor(Xset, A, Uset=pt.Polytope(), B=np.array([])): if not B.any(): return pt.Polytope(Xset.A @ A, Xset.b) else: tmp = minkowski_sum( Xset, pt.extreme(Uset) @ -B.T ) return pt.Polytope(tmp.A @ A, tmp.b) def Oinf(A, Xset): Omega = Xset k = 0 Omegap = precursor(Omega, A).intersect(Omega) while not Omegap == Omega: k += 1 Omega = Omegap Omegap = pt.reduce(precursor(Omega, A).intersect(Omega)) return Omegap # remeber to convet input constraits in state constraints S = X.intersect(pt.Polytope(U.A @ -Finf, U.b)) # maximal positive invariant set O_inf = Oinf(Acl, S) # %% maximal control invariant set def Cinf(A, B, Xset, Uset): Omega = Xset k = 0 Omegap = precursor(Omega, A, Uset, B).intersect(Omega) while not Omegap == Omega: k += 1 Omega = Omegap Omegap = precursor(Omega, A, Uset, B).intersect(Omega) return Omegap C_inf = Cinf(A, B, X, U) # %% initial feasible set N = 3 C = {} PreS = precursor(O_inf, A, U, B) for j in range(N): C[j]= PreS.intersect(X) PreS = precursor(C[j], A, U, B) X0 = C[N-1] # The initial feasible set X0 is equivalent to the N-step controllable set. # %% plot # Plotting and Comparison plt.clf() plt.cla() plt.close('all') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) X.plot(ax, color='m', alpha=0.1, linestyle='solid', linewidth=1, edgecolor=None) # state constraint set C_inf.plot(ax, color='m', alpha=0.6, linestyle='solid', linewidth=1) # maximal control invariant set X0.plot(ax, color='y', alpha=0.7, linestyle='solid', linewidth=1) # initial feasible set O_inf.plot(ax, color='g', alpha=0.7, linestyle='solid', linewidth=1) # maximal positive invariant set ax.legend(['X', 'Cinf', 'X0', 'Oinf']) ax.autoscale_view() # ax.axis('equal') plt.show() # %% # simulation with MPC import pyomo.environ as pyo Xf = O_inf Af = Xf.A bf = Xf.b Q = np.eye(2) R = np.array([1]).reshape(1,1) P = Pinf # play here with different P N = 3 x1U = np.pi/4 x2U = np.pi/2 uU = np.pi/10 x0 = np.array([-0.5, 1]) def solve_cftoc(A, B, P, Q, R, N, x0, x1U, x2U, uL, uU, bf, Af): model = pyo.ConcreteModel() model.N = N model.nx = np.size(A, 0) model.nu = np.size(B, 1) model.nf = np.size(Af, 0) # length of finite optimization problem: model.tIDX = pyo.Set( initialize= range(model.N+1), ordered=True ) model.xIDX = pyo.Set( initialize= range(model.nx), ordered=True ) model.uIDX = pyo.Set( initialize= range(model.nu), ordered=True ) model.nfIDX = pyo.Set( initialize= range(model.nf), ordered=True ) # these are 2d arrays: model.A = A model.B = B model.Q = Q model.P = P model.R = R model.Af = Af model.bf = bf # Create state and input variables trajectory: model.x = pyo.Var(model.xIDX, model.tIDX) model.u = pyo.Var(model.uIDX, model.tIDX, bounds=(uL,uU)) #Objective: def objective_rule(model): costX = 0.0 costU = 0.0 costTerminal = 0.0 for t in model.tIDX: for i in model.xIDX: for j in model.xIDX: if t < model.N: costX += model.x[i, t] * model.Q[i, j] * model.x[j, t] for t in model.tIDX: for i in model.uIDX: for j in model.uIDX: if t < model.N: costU += model.u[i, t] * model.R[i, j] * model.u[j, t] for i in model.xIDX: for j in model.xIDX: costTerminal += model.x[i, model.N] * model.P[i, j] * model.x[j, model.N] return costX + costU + costTerminal model.cost = pyo.Objective(rule = objective_rule, sense = pyo.minimize) # Constraints: def equality_const_rule(model, i, t): return model.x[i, t+1] - (sum(model.A[i, j] * model.x[j, t] for j in model.xIDX) + sum(model.B[i, j] * model.u[j, t] for j in model.uIDX) ) == 0.0 if t < model.N else pyo.Constraint.Skip model.equality_constraints = pyo.Constraint(model.xIDX, model.tIDX, rule=equality_const_rule) model.init_const1 = pyo.Constraint(expr = model.x[0, 0] == x0[0]) model.init_const2 = pyo.Constraint(expr = model.x[1, 0] == x0[1]) model.state_limit1 = pyo.Constraint(model.tIDX, rule=lambda model, t: model.x[0, t] <= x1U if t < N else pyo.Constraint.Skip) model.state_limit2 = pyo.Constraint(model.tIDX, rule=lambda model, t: -x1U <= model.x[0, t] if t < N else pyo.Constraint.Skip) model.state_limit3 = pyo.Constraint(model.tIDX, rule=lambda model, t: model.x[1, t] <= x2U if t < N else pyo.Constraint.Skip) model.state_limit4 = pyo.Constraint(model.tIDX, rule=lambda model, t: -x2U <= model.x[1, t] if t < N else pyo.Constraint.Skip) def final_const_rule(model, i): return sum(model.Af[i, j] * model.x[j, model.N] for j in model.xIDX) <= model.bf[i] model.final_const = pyo.Constraint(model.nfIDX, rule=final_const_rule) solver = pyo.SolverFactory('ipopt') results = solver.solve(model) if str(results.solver.termination_condition) == "optimal": feas = True else: feas = False xOpt = np.asarray([[model.x[i,t]() for i in model.xIDX] for t in model.tIDX]).T uOpt = np.asarray([model.u[:,t]() for t in model.tIDX]).T JOpt = model.cost() return [model, feas, xOpt, uOpt, JOpt] [model, feas, xOpt, uOpt, JOpt] = solve_cftoc(A, B, P, Q, R, N, x0, x1U, x2U, -uU, uU, bf, Af) # Setup the simulation with MPC controller nx = np.size(A, 0) nu = np.size(B, 1) M = 25 # Simulation steps xOpt = np.zeros((nx, M+1)) uOpt = np.zeros((nu, M)) xOpt[:, 0] = x0.reshape(nx, ) xPred = np.zeros((nx, N+1, M)) predErr = np.zeros((nx, M-N+1)) feas = np.zeros((M, ), dtype=bool) xN = np.zeros((nx,1)) fig = plt.figure(figsize=(9, 6)) for t in range(M): [model, feas[t], x, u, J] = solve_cftoc(A, B, P, Q, R, N, xOpt[:, t], x1U, x2U, -uU, uU, bf, Af) if not feas[t]: xOpt = [] uOpt = [] predErr = [] break # Save open loop predictions xPred[:, :, t] = x # Save closed loop trajectory # Note that the second column of x represents the optimal closed loop state xOpt[:, t+1] = x[:, 1] uOpt[:, t] = u[:, 0].reshape(nu, ) # Plot Open Loop line1 = plt.plot(x[0,:], x[1,:], 'r--') # Plot Closed Loop line2 = plt.plot(xOpt[0, :], xOpt[1, :], 'bo-') plt.legend([line1[0], line2[0]], ['Open-loop', 'Closed-loop']); plt.xlabel('x1') plt.ylabel('x2') plt.axis('equal') plt.show() # Plotting the polytopic sets and the closed loop trajectory plt.clf() plt.cla() plt.close('all') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) X.plot(ax, color='m', alpha=0.1, linestyle='solid', linewidth=1, edgecolor=None) # state constraint set C_inf.plot(ax, color='m', alpha=0.6, linestyle='solid', linewidth=1) # maximal control invariant set X0.plot(ax, color='y', alpha=0.7, linestyle='solid', linewidth=1) # initial feasible set O_inf.plot(ax, color='g', alpha=0.7, linestyle='solid', linewidth=1) # maximal positive invariant set ax.legend(['X', 'Cinf', 'X0', 'Oinf']) ax.plot(xOpt[0, :], xOpt[1, :], 'bo-', markerfacecolor='none', markeredgewidth=0.5, linewidth= 0.5, label='traj') # closed loop trajectory ax.plot(xOpt[0, 0], xOpt[1, 0], 'ro', label='init') # the initial condition x0 ax.autoscale_view() # ax.axis('equal') plt.show()
0e2dab9ebd7d156f7732efa45fc8ee01afb11ef1
e5c3b3a044e826425dd0f783d5e38e5bfeb82626
/diplomacy_research/proto/diplomacy_tensorflow/core/protobuf/checkpointable_object_graph_pb2.py
3255cddedf2006b2317064a1650484e4912bd022
[ "MIT" ]
permissive
JACKHAHA363/research
04f67f98dcd238092941725d531517ae2a4ab47f
e752f02f34936bbae904815708904cabda554b57
refs/heads/master
2020-09-14T23:42:32.337085
2019-11-22T03:36:35
2019-11-22T03:36:35
223,296,172
0
0
null
2019-11-22T01:15:52
2019-11-22T01:15:51
null
UTF-8
Python
false
true
13,585
py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: diplomacy_tensorflow/core/protobuf/checkpointable_object_graph.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='diplomacy_tensorflow/core/protobuf/checkpointable_object_graph.proto', package='diplomacy.tensorflow', syntax='proto3', serialized_options=_b('\370\001\001'), serialized_pb=_b('\nDdiplomacy_tensorflow/core/protobuf/checkpointable_object_graph.proto\x12\x14\x64iplomacy.tensorflow\"\xc3\x05\n\x19\x43heckpointableObjectGraph\x12S\n\x05nodes\x18\x01 \x03(\x0b\x32\x44.diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject\x1a\xd0\x04\n\x14\x43heckpointableObject\x12\x66\n\x08\x63hildren\x18\x01 \x03(\x0b\x32T.diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.ObjectReference\x12i\n\nattributes\x18\x02 \x03(\x0b\x32U.diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SerializedTensor\x12r\n\x0eslot_variables\x18\x03 \x03(\x0b\x32Z.diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference\x1a\x36\n\x0fObjectReference\x12\x0f\n\x07node_id\x18\x01 \x01(\x05\x12\x12\n\nlocal_name\x18\x02 \x01(\t\x1aK\n\x10SerializedTensor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tfull_name\x18\x02 \x01(\t\x12\x16\n\x0e\x63heckpoint_key\x18\x03 \x01(\t\x1al\n\x15SlotVariableReference\x12!\n\x19original_variable_node_id\x18\x01 \x01(\x05\x12\x11\n\tslot_name\x18\x02 \x01(\t\x12\x1d\n\x15slot_variable_node_id\x18\x03 \x01(\x05\x42\x03\xf8\x01\x01\x62\x06proto3') ) _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_OBJECTREFERENCE = _descriptor.Descriptor( name='ObjectReference', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.ObjectReference', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='node_id', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.ObjectReference.node_id', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='local_name', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.ObjectReference.local_name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=561, serialized_end=615, ) _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SERIALIZEDTENSOR = _descriptor.Descriptor( name='SerializedTensor', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SerializedTensor', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SerializedTensor.name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='full_name', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SerializedTensor.full_name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='checkpoint_key', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SerializedTensor.checkpoint_key', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=617, serialized_end=692, ) _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SLOTVARIABLEREFERENCE = _descriptor.Descriptor( name='SlotVariableReference', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='original_variable_node_id', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference.original_variable_node_id', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='slot_name', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference.slot_name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='slot_variable_node_id', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference.slot_variable_node_id', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=694, serialized_end=802, ) _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT = _descriptor.Descriptor( name='CheckpointableObject', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='children', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.children', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='attributes', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.attributes', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='slot_variables', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.slot_variables', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_OBJECTREFERENCE, _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SERIALIZEDTENSOR, _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SLOTVARIABLEREFERENCE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=210, serialized_end=802, ) _CHECKPOINTABLEOBJECTGRAPH = _descriptor.Descriptor( name='CheckpointableObjectGraph', full_name='diplomacy.tensorflow.CheckpointableObjectGraph', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='nodes', full_name='diplomacy.tensorflow.CheckpointableObjectGraph.nodes', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=95, serialized_end=802, ) _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_OBJECTREFERENCE.containing_type = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SERIALIZEDTENSOR.containing_type = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SLOTVARIABLEREFERENCE.containing_type = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT.fields_by_name['children'].message_type = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_OBJECTREFERENCE _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT.fields_by_name['attributes'].message_type = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SERIALIZEDTENSOR _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT.fields_by_name['slot_variables'].message_type = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SLOTVARIABLEREFERENCE _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT.containing_type = _CHECKPOINTABLEOBJECTGRAPH _CHECKPOINTABLEOBJECTGRAPH.fields_by_name['nodes'].message_type = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT DESCRIPTOR.message_types_by_name['CheckpointableObjectGraph'] = _CHECKPOINTABLEOBJECTGRAPH _sym_db.RegisterFileDescriptor(DESCRIPTOR) CheckpointableObjectGraph = _reflection.GeneratedProtocolMessageType('CheckpointableObjectGraph', (_message.Message,), dict( CheckpointableObject = _reflection.GeneratedProtocolMessageType('CheckpointableObject', (_message.Message,), dict( ObjectReference = _reflection.GeneratedProtocolMessageType('ObjectReference', (_message.Message,), dict( DESCRIPTOR = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_OBJECTREFERENCE, __module__ = 'diplomacy_tensorflow.core.protobuf.checkpointable_object_graph_pb2' # @@protoc_insertion_point(class_scope:diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.ObjectReference) )) , SerializedTensor = _reflection.GeneratedProtocolMessageType('SerializedTensor', (_message.Message,), dict( DESCRIPTOR = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SERIALIZEDTENSOR, __module__ = 'diplomacy_tensorflow.core.protobuf.checkpointable_object_graph_pb2' # @@protoc_insertion_point(class_scope:diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SerializedTensor) )) , SlotVariableReference = _reflection.GeneratedProtocolMessageType('SlotVariableReference', (_message.Message,), dict( DESCRIPTOR = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT_SLOTVARIABLEREFERENCE, __module__ = 'diplomacy_tensorflow.core.protobuf.checkpointable_object_graph_pb2' # @@protoc_insertion_point(class_scope:diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference) )) , DESCRIPTOR = _CHECKPOINTABLEOBJECTGRAPH_CHECKPOINTABLEOBJECT, __module__ = 'diplomacy_tensorflow.core.protobuf.checkpointable_object_graph_pb2' # @@protoc_insertion_point(class_scope:diplomacy.tensorflow.CheckpointableObjectGraph.CheckpointableObject) )) , DESCRIPTOR = _CHECKPOINTABLEOBJECTGRAPH, __module__ = 'diplomacy_tensorflow.core.protobuf.checkpointable_object_graph_pb2' # @@protoc_insertion_point(class_scope:diplomacy.tensorflow.CheckpointableObjectGraph) )) _sym_db.RegisterMessage(CheckpointableObjectGraph) _sym_db.RegisterMessage(CheckpointableObjectGraph.CheckpointableObject) _sym_db.RegisterMessage(CheckpointableObjectGraph.CheckpointableObject.ObjectReference) _sym_db.RegisterMessage(CheckpointableObjectGraph.CheckpointableObject.SerializedTensor) _sym_db.RegisterMessage(CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
7e8eb6d990fb73c2f7395b292c849786ef41d25c
b333dc607a2f1556f6a8adb6d16dc88fa8a30c8b
/portal/libs/whoosh/highlight.py
9b8c86059796099a3943031eb67825158392109a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hernan0216/utopia-cms
6558f8f600620c042dd79c7d2edf18fb77caebb8
48b48ef9acf8e3d0eb7d52601a122a01da82075c
refs/heads/main
2023-02-06T10:31:35.525180
2020-12-15T17:43:28
2020-12-15T17:43:28
321,775,279
1
0
BSD-3-Clause
2020-12-15T19:59:17
2020-12-15T19:59:16
null
UTF-8
Python
false
false
13,779
py
#=============================================================================== # Copyright 2008 Matt Chaput # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #=============================================================================== from __future__ import division from heapq import nlargest """ The highlight module contains classes and functions for displaying short excerpts from hit documents in the search results you present to the user, with query terms highlighted. """ # Fragment object class Fragment(object): """Represents a fragment (extract) from a hit document. This object is mainly used to keep track of the start and end points of the fragment; it does not contain the text of the fragment or do much else. """ def __init__(self, tokens, charsbefore = 0, charsafter = 0, textlen = 999999): """ :param tokens: list of the Token objects representing the matched terms. :param charsbefore: approx. how many characters before the start of the first matched term to include in the fragment. :param charsafter: approx. how many characters after the end of the last matched term to include in the fragment. :param textlen: length in characters of the document text. """ #: index of the first character of the fragment in the original document self.startchar = max(0, tokens[0].startchar - charsbefore) #: index after the last character of the fragment in the original document self.endchar = min(textlen, tokens[-1].endchar + charsafter) self.matches = [t for t in tokens if t.matched] self.matched_terms = frozenset(t.text for t in self.matches) def __len__(self): return self.endchar - self.startchar def overlaps(self, fragment): sc = self.startchar ec = self.endchar fsc = fragment.startchar fec = fragment.endchar return (fsc > sc and fsc < ec) or (fec > sc and fec < ec) def overlapped_length(self, fragment): sc = self.startchar ec = self.endchar fsc = fragment.startchar fec = fragment.endchar return max(ec, fec) - min(sc, fsc) def has_matches(self): return any(t.matched for t in self.tokens) # Filters def copyandmatchfilter(termset, tokens): for t in tokens: t = t.copy() t.matched = t.text in termset yield t # Fragmenters def NullFragmenter(text, termset, tokens): """Doesn't fragment the token stream. This object just returns the entire stream as one "fragment". This is useful if you want to highlight the entire text. """ return [Fragment(list(tokens))] class SimpleFragmenter(object): """Simply splits the text into roughly equal sized chunks. """ def __init__(self, size = 70): """ :param size: size (in characters) to chunk to. The chunking is based on tokens, so the fragments will usually be smaller. """ self.size = 70 def __call__(self, text, tokens): size = self.size first = None frag = [] for t in tokens: if first is None: first = t.startchar if t.endchar - first > size: first = None if frag: yield Fragment(frag) frag = [] frag.append(t) if frag: yield Fragment(frag) class SentenceFragmenter(object): """Breaks the text up on sentence end punctuation characters (".", "!", or "?"). This object works by looking in the original text for a sentence end as the next character after each token's 'endchar'. """ def __init__(self, maxchars = 200, sentencechars = ".!?"): """ :param maxchars: The maximum number of characters allowed in a fragment. """ self.maxchars = maxchars self.sentencechars = frozenset(sentencechars) def __call__(self, text, tokens): maxchars = self.maxchars sentencechars = self.sentencechars textlen = len(text) first = None frag = [] for t in tokens: if first is None: first = t.startchar endchar = t.endchar if endchar - first > maxchars: first = None if frag: yield Fragment(frag) frag = [] frag.append(t) if frag and endchar < textlen and text[endchar] in sentencechars: # Don't break for two periods in a row (e.g. ignore "...") if endchar+1 < textlen and text[endchar + 1] in sentencechars: continue yield Fragment(frag, charsafter = 1) frag = [] first = None if frag: yield Fragment(frag) class ContextFragmenter(object): """Looks for matched terms and aggregates them with their surrounding context. This fragmenter only yields fragments that contain matched terms. """ def __init__(self, termset, maxchars = 200, charsbefore = 20, charsafter = 20): """ :param termset: A collection (probably a set or frozenset) containing the terms you want to match to token.text attributes. :param maxchars: The maximum number of characters allowed in a fragment. :param charsbefore: The number of extra characters of context to add before the first matched term. :param charsafter: The number of extra characters of context to add after the last matched term. """ self.maxchars = maxchars self.charsbefore = charsbefore self.charsafter = charsafter def __call__(self, text, tokens): maxchars = self.maxchars charsbefore = self.charsbefore charsafter = self.charsafter current = [] currentlen = 0 countdown = -1 for t in tokens: if t.matched: countdown = charsafter current.append(t) length = t.endchar - t.startchar currentlen += length if countdown >= 0: countdown -= length if countdown < 0 or currentlen >= maxchars: yield Fragment(current) current = [] currentlen = 0 else: while current and currentlen > charsbefore: t = current.pop(0) currentlen -= t.endchar - t.startchar if countdown >= 0: yield Fragment(current) #class VectorFragmenter(object): # def __init__(self, termmap, maxchars = 200, charsbefore = 20, charsafter = 20): # """ # :param termmap: A dictionary mapping the terms you're looking for to # lists of either (posn, startchar, endchar) or # (posn, startchar, endchar, boost) tuples. # :param maxchars: The maximum number of characters allowed in a fragment. # :param charsbefore: The number of extra characters of context to add before # the first matched term. # :param charsafter: The number of extra characters of context to add after # the last matched term. # """ # # self.termmap = termmap # self.maxchars = maxchars # self.charsbefore = charsbefore # self.charsafter = charsafter # # def __call__(self, text, tokens): # maxchars = self.maxchars # charsbefore = self.charsbefore # charsafter = self.charsafter # textlen = len(text) # # vfrags = [] # for term, data in self.termmap.iteritems(): # if len(data) == 3: # t = Token(startchar = data[1], endchar = data[2]) # elif len(data) == 4: # t = Token(startchar = data[1], endchar = data[2], boost = data[3]) # else: # raise ValueError(repr(data)) # # newfrag = VFragment([t], charsbefore, charsafter, textlen) # added = False # # for vf in vfrags: # if vf.overlaps(newfrag) and vf.overlapped_length(newfrag) < maxchars: # vf.merge(newfrag) # added = True # break # Fragment scorers def BasicFragmentScorer(f): # Add up the boosts for the matched terms in this passage score = sum(t.boost for t in f.matches) # Favor diversity: multiply score by the number of separate # terms matched score *= len(f.matched_terms) * 100 return score # Fragment sorters def SCORE(fragment): "Sorts higher scored passages first." return None def FIRST(fragment): "Sorts passages from earlier in the document first." return fragment.startchar def LONGER(fragment): "Sorts longer passages first." return 0 - len(fragment) def SHORTER(fragment): "Sort shorter passages first." return len(fragment) # Formatters class UppercaseFormatter(object): def __init__(self, between = "..."): self.between = between def _format_fragment(self, text, fragment): output = [] index = fragment.startchar for t in fragment.matches: if t.startchar > index: output.append(text[index:t.startchar]) ttxt = text[t.startchar:t.endchar] if t.matched: ttxt = ttxt.upper() output.append(ttxt) index = t.endchar output.append(text[index:fragment.endchar]) return "".join(output) def __call__(self, text, fragments): return self.between.join((self._format_fragment(text, fragment) for fragment in fragments)) class GenshiFormatter(object): def __init__(self, qname, between = "..."): self.qname = qname self.between = between from genshi.core import START, END, TEXT, Attrs, Stream #@UnresolvedImport self.START, self.END, self.TEXT, self.Attrs, self.Stream = (START, END, TEXT, Attrs, Stream) def _add_text(self, text, output): if output and output[-1][0] == self.TEXT: output[-1] = (self.TEXT, output[-1][1] + text, output[-1][2]) else: output.append((self.TEXT, text, (None, -1, -1))) def _format_fragment(self, text, fragment): START, TEXT, END, Attrs = self.START, self.TEXT, self.END, self.Attrs qname = self.qname output = [] index = fragment.startchar lastmatched = False for t in fragment.matches: if t.startchar > index: if lastmatched: output.append((END, qname, (None, -1, -1))) lastmatched = False self._add_text(text[index:t.startchar], output) ttxt = text[t.startchar:t.endchar] if not lastmatched: output.append((START, (qname, Attrs()), (None, -1, -1))) lastmatched = True output.append((TEXT, ttxt, (None, -1, -1))) index = t.endchar if lastmatched: output.append((END, qname, (None, -1, -1))) return output def __call__(self, text, fragments): output = [] first = True for fragment in fragments: if not first: self._add_text(self.between, output) first = False output += self._format_fragment(text, fragment) return self.Stream(output) # Highlighting def top_fragments(text, terms, analyzer, fragmenter, top = 3, scorer = BasicFragmentScorer, minscore = 1): termset = frozenset(terms) tokens = copyandmatchfilter(termset, analyzer(text, chars = True, keeporiginal = True)) scored_frags = nlargest(top, ((scorer(f), f) for f in fragmenter(text, tokens))) return [sf for score, sf in scored_frags if score > minscore] def highlight(text, terms, analyzer, fragmenter, formatter, top=3, scorer = BasicFragmentScorer, minscore = 1, order = FIRST): fragments = top_fragments(text, terms, analyzer, fragmenter, top = top, minscore = minscore) fragments.sort(key = order) return formatter(text, fragments) if __name__ == '__main__': import re, time from whoosh import analysis #from genshi import QName sa = analysis.StemmingAnalyzer() txt = open("/Volumes/Storage/Development/help/documents/nodes/sop/copy.txt").read().decode("utf8") txt = re.sub("[\t\r\n ]+", " ", txt) t = time.time() fs = highlight(txt, ["templat", "geometri"], sa, SentenceFragmenter(), UppercaseFormatter()) print time.time() - t print fs
7a90ed38676596e38929c75c713b6dd7cccfb522
9ce90f599ec7be83fbba56842381c1891f0801b2
/examples/earm/earm_1_3_standalone.py
5d68198b42749b5a89c08f8d47140c812c0027d0
[ "BSD-2-Clause" ]
permissive
jmuhlich/bayessb
d55328cc022353118a5bb4f9184bf67bb5f39d85
c9aea038d2984afd77185d18675e3c7caae85e93
refs/heads/master
2021-01-19T20:21:58.471316
2013-04-16T13:46:49
2013-04-16T13:46:49
4,274,758
3
1
null
2013-01-29T15:37:24
2012-05-09T18:00:14
Python
UTF-8
Python
false
false
31,608
py
""" EARM 1.3 (extrinsic apoptosis reaction model) Gaudet S, Spencer SL, Chen WW, Sorger PK (2012) Exploring the Contextual Sensitivity of Factors that Determine Cell-to-Cell Variability in Receptor-Mediated Apoptosis. PLoS Comput Biol 8(4): e1002482. doi:10.1371/journal.pcbi.1002482 http://www.ploscompbiol.org/article/info:doi/10.1371/journal.pcbi.1002482 """ # exported from PySB model 'earm_1_3' import numpy import scipy.weave, scipy.integrate import collections import itertools import distutils.errors _use_inline = False # try to inline a C statement to see if inline is functional try: scipy.weave.inline('int i;', force=1) _use_inline = True except distutils.errors.CompileError: pass Parameter = collections.namedtuple('Parameter', 'name value') Observable = collections.namedtuple('Observable', 'name species coefficients') Initial = collections.namedtuple('Initial', 'param_index species_index') class Model(object): def __init__(self): self.y = None self.yobs = None self.integrator = scipy.integrate.ode(self.ode_rhs, ) self.integrator.set_integrator('vode', method='bdf', with_jacobian=True, rtol=1e-3, atol=1e-6) self.y0 = numpy.empty(60) self.ydot = numpy.empty(60) self.sim_param_values = numpy.empty(206) self.parameters = [None] * 206 self.observables = [None] * 6 self.initial_conditions = [None] * 19 self.parameters[0] = Parameter('L_0', 3000) self.parameters[1] = Parameter('pR_0', 1000) self.parameters[2] = Parameter('flip_0', 2000) self.parameters[3] = Parameter('pC8_0', 10000) self.parameters[4] = Parameter('BAR_0', 1000) self.parameters[5] = Parameter('pC3_0', 10000) self.parameters[6] = Parameter('pC6_0', 10000) self.parameters[7] = Parameter('XIAP_0', 100000) self.parameters[8] = Parameter('PARP_0', 1e+06) self.parameters[9] = Parameter('Bid_0', 60000) self.parameters[10] = Parameter('Mcl1_0', 20000) self.parameters[11] = Parameter('Bax_0', 80000) self.parameters[12] = Parameter('Bcl2_0', 30000) self.parameters[13] = Parameter('Mito_0', 500000) self.parameters[14] = Parameter('mCytoC_0', 500000) self.parameters[15] = Parameter('mSmac_0', 100000) self.parameters[16] = Parameter('pC9_0', 100000) self.parameters[17] = Parameter('Apaf_0', 100000) self.parameters[18] = Parameter('kf1', 4e-07) self.parameters[19] = Parameter('kr1', 1e-06) self.parameters[20] = Parameter('kc1', 0.01) self.parameters[21] = Parameter('kf2', 1e-06) self.parameters[22] = Parameter('kr2', 0.001) self.parameters[23] = Parameter('kf3', 1e-07) self.parameters[24] = Parameter('kr3', 0.001) self.parameters[25] = Parameter('kc3', 1) self.parameters[26] = Parameter('kf4', 1e-06) self.parameters[27] = Parameter('kr4', 0.001) self.parameters[28] = Parameter('kf5', 1e-07) self.parameters[29] = Parameter('kr5', 0.001) self.parameters[30] = Parameter('kc5', 1) self.parameters[31] = Parameter('kf6', 1e-07) self.parameters[32] = Parameter('kr6', 0.001) self.parameters[33] = Parameter('kc6', 1) self.parameters[34] = Parameter('kf7', 1e-07) self.parameters[35] = Parameter('kr7', 0.001) self.parameters[36] = Parameter('kc7', 1) self.parameters[37] = Parameter('kf8', 2e-06) self.parameters[38] = Parameter('kr8', 0.001) self.parameters[39] = Parameter('kc8', 0.1) self.parameters[40] = Parameter('kf9', 1e-06) self.parameters[41] = Parameter('kr9', 0.001) self.parameters[42] = Parameter('kc9', 20) self.parameters[43] = Parameter('kf10', 1e-07) self.parameters[44] = Parameter('kr10', 0.001) self.parameters[45] = Parameter('kc10', 1) self.parameters[46] = Parameter('kf11', 1e-06) self.parameters[47] = Parameter('kr11', 0.001) self.parameters[48] = Parameter('kf12', 1e-07) self.parameters[49] = Parameter('kr12', 0.001) self.parameters[50] = Parameter('kc12', 1) self.parameters[51] = Parameter('kf13', 0.01) self.parameters[52] = Parameter('kr13', 1) self.parameters[53] = Parameter('kf14', 0.0001) self.parameters[54] = Parameter('kr14', 0.001) self.parameters[55] = Parameter('kf15', 0.0002) self.parameters[56] = Parameter('kr15', 0.001) self.parameters[57] = Parameter('kf16', 0.0001) self.parameters[58] = Parameter('kr16', 0.001) self.parameters[59] = Parameter('kf17', 0.0002) self.parameters[60] = Parameter('kr17', 0.001) self.parameters[61] = Parameter('kf18', 0.0001) self.parameters[62] = Parameter('kr18', 0.001) self.parameters[63] = Parameter('kf19', 0.0001) self.parameters[64] = Parameter('kr19', 0.001) self.parameters[65] = Parameter('kc19', 1) self.parameters[66] = Parameter('kf20', 0.0002) self.parameters[67] = Parameter('kr20', 0.001) self.parameters[68] = Parameter('kc20', 10) self.parameters[69] = Parameter('kf21', 0.0002) self.parameters[70] = Parameter('kr21', 0.001) self.parameters[71] = Parameter('kc21', 10) self.parameters[72] = Parameter('kf22', 1) self.parameters[73] = Parameter('kr22', 0.01) self.parameters[74] = Parameter('kf23', 5e-07) self.parameters[75] = Parameter('kr23', 0.001) self.parameters[76] = Parameter('kc23', 1) self.parameters[77] = Parameter('kf24', 5e-08) self.parameters[78] = Parameter('kr24', 0.001) self.parameters[79] = Parameter('kf25', 5e-09) self.parameters[80] = Parameter('kr25', 0.001) self.parameters[81] = Parameter('kc25', 1) self.parameters[82] = Parameter('kf26', 1) self.parameters[83] = Parameter('kr26', 0.01) self.parameters[84] = Parameter('kf27', 2e-06) self.parameters[85] = Parameter('kr27', 0.001) self.parameters[86] = Parameter('kf28', 7e-06) self.parameters[87] = Parameter('kr28', 0.001) self.parameters[88] = Parameter('kf31', 0.001) self.parameters[89] = Parameter('kdeg_Mcl1', 0.0001) self.parameters[90] = Parameter('kdeg_AMito', 0.0001) self.parameters[91] = Parameter('kdeg_C3_U', 0) self.parameters[92] = Parameter('ks_L', 0) self.parameters[93] = Parameter('kdeg_L', 2.9e-06) self.parameters[94] = Parameter('kdeg_pR', 2.9e-06) self.parameters[95] = Parameter('ks_pR', 0.000435) self.parameters[96] = Parameter('kdeg_flip', 2.9e-06) self.parameters[97] = Parameter('ks_flip', 0.00087) self.parameters[98] = Parameter('kdeg_pC8', 2.9e-06) self.parameters[99] = Parameter('ks_pC8', 0.00435) self.parameters[100] = Parameter('kdeg_BAR', 2.9e-06) self.parameters[101] = Parameter('ks_BAR', 0.000435) self.parameters[102] = Parameter('kdeg_pC3', 2.9e-06) self.parameters[103] = Parameter('ks_pC3', 0.00435) self.parameters[104] = Parameter('kdeg_pC6', 2.9e-06) self.parameters[105] = Parameter('ks_pC6', 0.00435) self.parameters[106] = Parameter('kdeg_XIAP', 2.9e-06) self.parameters[107] = Parameter('ks_XIAP', 0.0435) self.parameters[108] = Parameter('kdeg_PARP', 2.9e-06) self.parameters[109] = Parameter('ks_PARP', 0.435) self.parameters[110] = Parameter('kdeg_Bid', 2.9e-06) self.parameters[111] = Parameter('ks_Bid', 0.0261) self.parameters[112] = Parameter('ks_Mcl1', 0.3) self.parameters[113] = Parameter('kdeg_Bax', 2.9e-06) self.parameters[114] = Parameter('ks_Bax', 0.0348) self.parameters[115] = Parameter('kdeg_Bcl2', 2.9e-06) self.parameters[116] = Parameter('ks_Bcl2', 0.01305) self.parameters[117] = Parameter('kdeg_Mito', 2.9e-06) self.parameters[118] = Parameter('ks_Mito', 0.2175) self.parameters[119] = Parameter('kdeg_mCytoC', 2.9e-06) self.parameters[120] = Parameter('ks_mCytoC', 0.2175) self.parameters[121] = Parameter('kdeg_mSmac', 2.9e-06) self.parameters[122] = Parameter('ks_mSmac', 0.0435) self.parameters[123] = Parameter('kdeg_Apaf', 2.9e-06) self.parameters[124] = Parameter('ks_Apaf', 0.0435) self.parameters[125] = Parameter('kdeg_pC9', 2.9e-06) self.parameters[126] = Parameter('ks_pC9', 0.0435) self.parameters[127] = Parameter('kdeg_L_pR', 2.9e-06) self.parameters[128] = Parameter('ks_L_pR', 0) self.parameters[129] = Parameter('kdeg_DISC', 2.9e-06) self.parameters[130] = Parameter('ks_DISC', 0) self.parameters[131] = Parameter('kdeg_DISC_flip', 2.9e-06) self.parameters[132] = Parameter('ks_DISC_flip', 0) self.parameters[133] = Parameter('kdeg_DISC_pC8', 2.9e-06) self.parameters[134] = Parameter('ks_DISC_pC8', 0) self.parameters[135] = Parameter('kdeg_C8', 2.9e-06) self.parameters[136] = Parameter('ks_C8', 0) self.parameters[137] = Parameter('kdeg_BAR_C8', 2.9e-06) self.parameters[138] = Parameter('ks_BAR_C8', 0) self.parameters[139] = Parameter('kdeg_C8_pC3', 2.9e-06) self.parameters[140] = Parameter('ks_C8_pC3', 0) self.parameters[141] = Parameter('kdeg_Bid_C8', 2.9e-06) self.parameters[142] = Parameter('ks_Bid_C8', 0) self.parameters[143] = Parameter('kdeg_C3', 2.9e-06) self.parameters[144] = Parameter('ks_C3', 0) self.parameters[145] = Parameter('kdeg_tBid', 2.9e-06) self.parameters[146] = Parameter('ks_tBid', 0) self.parameters[147] = Parameter('kdeg_C3_pC6', 2.9e-06) self.parameters[148] = Parameter('ks_C3_pC6', 0) self.parameters[149] = Parameter('kdeg_C3_XIAP', 2.9e-06) self.parameters[150] = Parameter('ks_C3_XIAP', 0) self.parameters[151] = Parameter('kdeg_C3_PARP', 2.9e-06) self.parameters[152] = Parameter('ks_C3_PARP', 0) self.parameters[153] = Parameter('kdeg_Mcl1_tBid', 2.9e-06) self.parameters[154] = Parameter('ks_Mcl1_tBid', 0) self.parameters[155] = Parameter('kdeg_Bax_tBid', 2.9e-06) self.parameters[156] = Parameter('ks_Bax_tBid', 0) self.parameters[157] = Parameter('kdeg_C6', 2.9e-06) self.parameters[158] = Parameter('ks_C6', 0) self.parameters[159] = Parameter('ks_C3_U', 0) self.parameters[160] = Parameter('kdeg_CPARP', 2.9e-06) self.parameters[161] = Parameter('ks_CPARP', 0) self.parameters[162] = Parameter('kdeg_aBax', 2.9e-06) self.parameters[163] = Parameter('ks_aBax', 0) self.parameters[164] = Parameter('kdeg_C6_pC8', 2.9e-06) self.parameters[165] = Parameter('ks_C6_pC8', 0) self.parameters[166] = Parameter('kdeg_MBax', 2.9e-06) self.parameters[167] = Parameter('ks_MBax', 0) self.parameters[168] = Parameter('kdeg_Bcl2_MBax', 2.9e-06) self.parameters[169] = Parameter('ks_Bcl2_MBax', 0) self.parameters[170] = Parameter('kdeg_Bax2', 2.9e-06) self.parameters[171] = Parameter('ks_Bax2', 0) self.parameters[172] = Parameter('kdeg_Bax2_Bcl2', 2.9e-06) self.parameters[173] = Parameter('ks_Bax2_Bcl2', 0) self.parameters[174] = Parameter('kdeg_Bax4', 2.9e-06) self.parameters[175] = Parameter('ks_Bax4', 0) self.parameters[176] = Parameter('kdeg_Bax4_Bcl2', 2.9e-06) self.parameters[177] = Parameter('ks_Bax4_Bcl2', 0) self.parameters[178] = Parameter('kdeg_Bax4_Mito', 2.9e-06) self.parameters[179] = Parameter('ks_Bax4_Mito', 0) self.parameters[180] = Parameter('ks_AMito', 0) self.parameters[181] = Parameter('kdeg_AMito_mCytoC', 2.9e-06) self.parameters[182] = Parameter('ks_AMito_mCytoC', 0) self.parameters[183] = Parameter('kdeg_AMito_mSmac', 2.9e-06) self.parameters[184] = Parameter('ks_AMito_mSmac', 0) self.parameters[185] = Parameter('kdeg_ACytoC', 2.9e-06) self.parameters[186] = Parameter('ks_ACytoC', 0) self.parameters[187] = Parameter('kdeg_ASmac', 2.9e-06) self.parameters[188] = Parameter('ks_ASmac', 0) self.parameters[189] = Parameter('kdeg_cCytoC', 2.9e-06) self.parameters[190] = Parameter('ks_cCytoC', 0) self.parameters[191] = Parameter('kdeg_cSmac', 2.9e-06) self.parameters[192] = Parameter('ks_cSmac', 0) self.parameters[193] = Parameter('kdeg_Apaf_cCytoC', 2.9e-06) self.parameters[194] = Parameter('ks_Apaf_cCytoC', 0) self.parameters[195] = Parameter('kdeg_XIAP_cSmac', 2.9e-06) self.parameters[196] = Parameter('ks_XIAP_cSmac', 0) self.parameters[197] = Parameter('kdeg_aApaf', 2.9e-06) self.parameters[198] = Parameter('ks_aApaf', 0) self.parameters[199] = Parameter('kdeg_Apop', 2.9e-06) self.parameters[200] = Parameter('ks_Apop', 0) self.parameters[201] = Parameter('kdeg_Apop_pC3', 2.9e-06) self.parameters[202] = Parameter('ks_Apop_pC3', 0) self.parameters[203] = Parameter('kdeg_Apop_XIAP', 2.9e-06) self.parameters[204] = Parameter('ks_Apop_XIAP', 0) self.parameters[205] = Parameter('__source_0', 1) self.observables[0] = Observable('Bid_unbound', [9], [1]) self.observables[1] = Observable('PARP_unbound', [8], [1]) self.observables[2] = Observable('mSmac_unbound', [15], [1]) self.observables[3] = Observable('tBid_total', [29, 33, 34], [1, 1, 1]) self.observables[4] = Observable('CPARP_total', [37], [1]) self.observables[5] = Observable('cSmac_total', [53, 55], [1, 1]) self.initial_conditions[0] = Initial(0, 0) self.initial_conditions[1] = Initial(1, 1) self.initial_conditions[2] = Initial(2, 2) self.initial_conditions[3] = Initial(3, 3) self.initial_conditions[4] = Initial(4, 4) self.initial_conditions[5] = Initial(5, 5) self.initial_conditions[6] = Initial(6, 6) self.initial_conditions[7] = Initial(7, 7) self.initial_conditions[8] = Initial(8, 8) self.initial_conditions[9] = Initial(9, 9) self.initial_conditions[10] = Initial(10, 10) self.initial_conditions[11] = Initial(11, 11) self.initial_conditions[12] = Initial(12, 12) self.initial_conditions[13] = Initial(13, 13) self.initial_conditions[14] = Initial(14, 14) self.initial_conditions[15] = Initial(15, 15) self.initial_conditions[16] = Initial(17, 16) self.initial_conditions[17] = Initial(16, 17) self.initial_conditions[18] = Initial(205, 18) if _use_inline: def ode_rhs(self, t, y, p): ydot = self.ydot scipy.weave.inline(r''' ydot[0] = -p[93]*y[0] - p[18]*y[0]*y[1] + p[88]*y[21] + p[19]*y[19] + p[92]*y[18]; ydot[1] = -p[94]*y[1] - p[18]*y[0]*y[1] + p[88]*y[21] + p[19]*y[19] + p[95]*y[18]; ydot[2] = -p[96]*y[2] - p[21]*y[2]*y[21] + p[22]*y[22] + p[97]*y[18]; ydot[3] = -p[98]*y[3] - p[23]*y[21]*y[3] - p[34]*y[3]*y[35] + p[24]*y[23] + p[35]*y[39] + p[99]*y[18]; ydot[4] = -p[100]*y[4] - p[26]*y[24]*y[4] + p[27]*y[25] + p[101]*y[18]; ydot[5] = -p[102]*y[5] - p[79]*y[5]*y[57] - p[28]*y[24]*y[5] + p[80]*y[58] + p[29]*y[26] + p[103]*y[18]; ydot[6] = -p[104]*y[6] - p[31]*y[28]*y[6] + p[32]*y[30] + p[105]*y[18]; ydot[7] = p[39]*y[31] - p[106]*y[7] - p[84]*y[57]*y[7] - p[86]*y[53]*y[7] - p[37]*y[28]*y[7] + p[85]*y[59] + p[87]*y[55] + p[38]*y[31] + p[107]*y[18]; ydot[8] = -p[108]*y[8] - p[40]*y[28]*y[8] + p[41]*y[32] + p[109]*y[18]; ydot[9] = -p[110]*y[9] - p[43]*y[24]*y[9] + p[44]*y[27] + p[111]*y[18]; ydot[10] = -p[89]*y[10] - p[46]*y[10]*y[29] + p[47]*y[33] + p[112]*y[18]; ydot[11] = -p[113]*y[11] - p[48]*y[11]*y[29] + p[49]*y[34] + p[114]*y[18]; ydot[12] = -p[115]*y[12] - p[53]*y[12]*y[40] - p[57]*y[12]*y[42] - p[61]*y[12]*y[44] + p[54]*y[41] + p[58]*y[43] + p[62]*y[45] + p[116]*y[18]; ydot[13] = p[90]*y[47] - p[117]*y[13] - p[63]*y[13]*y[44] + p[64]*y[46] + p[118]*y[18]; ydot[14] = -p[119]*y[14] - p[66]*y[14]*y[47] + p[67]*y[48] + p[120]*y[18]; ydot[15] = -p[121]*y[15] - p[69]*y[15]*y[47] + p[70]*y[49] + p[122]*y[18]; ydot[16] = -p[123]*y[16] - p[74]*y[16]*y[52] + p[75]*y[54] + p[124]*y[18]; ydot[17] = -p[125]*y[17] - p[77]*y[17]*y[56] + p[78]*y[57] + p[126]*y[18]; ydot[18] = 0; ydot[19] = -p[20]*y[19] - p[127]*y[19] + p[18]*y[0]*y[1] - p[19]*y[19] + p[128]*y[18]; ydot[20] = p[185]*y[50] + p[181]*y[48] + p[183]*y[49] + p[187]*y[51] + p[123]*y[16] + p[193]*y[54] + p[199]*y[57] + p[203]*y[59] + p[201]*y[58] + p[100]*y[4] + p[137]*y[25] + p[113]*y[11] + p[170]*y[42] + p[172]*y[43] + p[174]*y[44] + p[176]*y[45] + p[178]*y[46] + p[155]*y[34] + p[115]*y[12] + p[168]*y[41] + p[110]*y[9] + p[141]*y[27] + p[143]*y[28] + p[151]*y[32] + p[91]*y[36] + p[149]*y[31] + p[147]*y[30] + p[157]*y[35] + p[164]*y[39] + p[135]*y[24] + p[139]*y[26] + p[160]*y[37] + p[131]*y[22] + p[133]*y[23] + p[93]*y[0] + p[127]*y[19] + p[166]*y[40] + p[89]*y[10] + p[153]*y[33] + p[117]*y[13] + p[108]*y[8] + p[106]*y[7] + p[195]*y[55] + p[197]*y[56] + p[162]*y[38] + p[189]*y[52] + p[191]*y[53] + p[96]*y[2] + p[119]*y[14] + p[121]*y[15] + p[102]*y[5] + p[104]*y[6] + p[98]*y[3] + p[125]*y[17] + p[94]*y[1] + p[145]*y[29]; ydot[21] = p[20]*y[19] + p[25]*y[23] - p[21]*y[2]*y[21] - p[23]*y[21]*y[3] - p[88]*y[21] + p[22]*y[22] + p[24]*y[23] + p[130]*y[18]; ydot[22] = -p[131]*y[22] + p[21]*y[2]*y[21] - p[22]*y[22] + p[132]*y[18]; ydot[23] = -p[25]*y[23] - p[133]*y[23] + p[23]*y[21]*y[3] - p[24]*y[23] + p[134]*y[18]; ydot[24] = p[45]*y[27] + p[25]*y[23] + p[30]*y[26] + p[36]*y[39] - p[135]*y[24] - p[43]*y[24]*y[9] - p[26]*y[24]*y[4] - p[28]*y[24]*y[5] + p[44]*y[27] + p[27]*y[25] + p[29]*y[26] + p[136]*y[18]; ydot[25] = -p[137]*y[25] + p[26]*y[24]*y[4] - p[27]*y[25] + p[138]*y[18]; ydot[26] = -p[30]*y[26] - p[139]*y[26] + p[28]*y[24]*y[5] - p[29]*y[26] + p[140]*y[18]; ydot[27] = -p[45]*y[27] - p[141]*y[27] + p[43]*y[24]*y[9] - p[44]*y[27] + p[142]*y[18]; ydot[28] = p[81]*y[58] + p[30]*y[26] + p[33]*y[30] + p[42]*y[32] - p[143]*y[28] - p[31]*y[28]*y[6] - p[37]*y[28]*y[7] - p[40]*y[28]*y[8] + p[32]*y[30] + p[38]*y[31] + p[41]*y[32] + p[144]*y[18]; ydot[29] = p[45]*y[27] + p[50]*y[34] - p[145]*y[29] - p[46]*y[10]*y[29] - p[48]*y[11]*y[29] + p[47]*y[33] + p[49]*y[34] + p[146]*y[18]; ydot[30] = -p[33]*y[30] - p[147]*y[30] + p[31]*y[28]*y[6] - p[32]*y[30] + p[148]*y[18]; ydot[31] = -p[39]*y[31] - p[149]*y[31] + p[37]*y[28]*y[7] - p[38]*y[31] + p[150]*y[18]; ydot[32] = -p[42]*y[32] - p[151]*y[32] + p[40]*y[28]*y[8] - p[41]*y[32] + p[152]*y[18]; ydot[33] = -p[153]*y[33] + p[46]*y[10]*y[29] - p[47]*y[33] + p[154]*y[18]; ydot[34] = -p[50]*y[34] - p[155]*y[34] + p[48]*y[11]*y[29] - p[49]*y[34] + p[156]*y[18]; ydot[35] = p[33]*y[30] + p[36]*y[39] - p[157]*y[35] - p[34]*y[3]*y[35] + p[35]*y[39] + p[158]*y[18]; ydot[36] = p[39]*y[31] - p[91]*y[36] + p[159]*y[18]; ydot[37] = p[42]*y[32] - p[160]*y[37] + p[161]*y[18]; ydot[38] = p[50]*y[34] - p[162]*y[38] - p[51]*y[38] + p[52]*y[40] + p[163]*y[18]; ydot[39] = -p[36]*y[39] - p[164]*y[39] + p[34]*y[3]*y[35] - p[35]*y[39] + p[165]*y[18]; ydot[40] = -p[166]*y[40] + p[51]*y[38] - p[53]*y[12]*y[40] - 1.0*p[55]*pow(y[40], 2) - p[52]*y[40] + p[54]*y[41] + 2*p[56]*y[42] + p[167]*y[18]; ydot[41] = -p[168]*y[41] + p[53]*y[12]*y[40] - p[54]*y[41] + p[169]*y[18]; ydot[42] = -p[170]*y[42] + 0.5*p[55]*pow(y[40], 2) - p[57]*y[12]*y[42] - 1.0*p[59]*pow(y[42], 2) - p[56]*y[42] + p[58]*y[43] + 2*p[60]*y[44] + p[171]*y[18]; ydot[43] = -p[172]*y[43] + p[57]*y[12]*y[42] - p[58]*y[43] + p[173]*y[18]; ydot[44] = -p[174]*y[44] + 0.5*p[59]*pow(y[42], 2) - p[61]*y[12]*y[44] - p[63]*y[13]*y[44] - p[60]*y[44] + p[62]*y[45] + p[64]*y[46] + p[175]*y[18]; ydot[45] = -p[176]*y[45] + p[61]*y[12]*y[44] - p[62]*y[45] + p[177]*y[18]; ydot[46] = -p[65]*y[46] - p[178]*y[46] + p[63]*y[13]*y[44] - p[64]*y[46] + p[179]*y[18]; ydot[47] = p[65]*y[46] + p[68]*y[48] + p[71]*y[49] - p[90]*y[47] - p[66]*y[14]*y[47] - p[69]*y[15]*y[47] + p[67]*y[48] + p[70]*y[49] + p[180]*y[18]; ydot[48] = -p[68]*y[48] - p[181]*y[48] + p[66]*y[14]*y[47] - p[67]*y[48] + p[182]*y[18]; ydot[49] = -p[71]*y[49] - p[183]*y[49] + p[69]*y[15]*y[47] - p[70]*y[49] + p[184]*y[18]; ydot[50] = p[68]*y[48] - p[185]*y[50] - p[72]*y[50] + p[73]*y[52] + p[186]*y[18]; ydot[51] = p[71]*y[49] - p[187]*y[51] - p[82]*y[51] + p[83]*y[53] + p[188]*y[18]; ydot[52] = p[76]*y[54] - p[189]*y[52] + p[72]*y[50] - p[74]*y[16]*y[52] - p[73]*y[52] + p[75]*y[54] + p[190]*y[18]; ydot[53] = -p[191]*y[53] + p[82]*y[51] - p[86]*y[53]*y[7] - p[83]*y[53] + p[87]*y[55] + p[192]*y[18]; ydot[54] = -p[76]*y[54] - p[193]*y[54] + p[74]*y[16]*y[52] - p[75]*y[54] + p[194]*y[18]; ydot[55] = -p[195]*y[55] + p[86]*y[53]*y[7] - p[87]*y[55] + p[196]*y[18]; ydot[56] = p[76]*y[54] - p[197]*y[56] - p[77]*y[17]*y[56] + p[78]*y[57] + p[198]*y[18]; ydot[57] = p[81]*y[58] - p[199]*y[57] + p[77]*y[17]*y[56] - p[79]*y[5]*y[57] - p[84]*y[57]*y[7] - p[78]*y[57] + p[80]*y[58] + p[85]*y[59] + p[200]*y[18]; ydot[58] = -p[81]*y[58] - p[201]*y[58] + p[79]*y[5]*y[57] - p[80]*y[58] + p[202]*y[18]; ydot[59] = -p[203]*y[59] + p[84]*y[57]*y[7] - p[85]*y[59] + p[204]*y[18]; ''', ['ydot', 't', 'y', 'p']) return ydot else: def ode_rhs(self, t, y, p): ydot = self.ydot ydot[0] = -p[93]*y[0] - p[18]*y[0]*y[1] + p[88]*y[21] + p[19]*y[19] + p[92]*y[18] ydot[1] = -p[94]*y[1] - p[18]*y[0]*y[1] + p[88]*y[21] + p[19]*y[19] + p[95]*y[18] ydot[2] = -p[96]*y[2] - p[21]*y[2]*y[21] + p[22]*y[22] + p[97]*y[18] ydot[3] = -p[98]*y[3] - p[23]*y[21]*y[3] - p[34]*y[3]*y[35] + p[24]*y[23] + p[35]*y[39] + p[99]*y[18] ydot[4] = -p[100]*y[4] - p[26]*y[24]*y[4] + p[27]*y[25] + p[101]*y[18] ydot[5] = -p[102]*y[5] - p[79]*y[5]*y[57] - p[28]*y[24]*y[5] + p[80]*y[58] + p[29]*y[26] + p[103]*y[18] ydot[6] = -p[104]*y[6] - p[31]*y[28]*y[6] + p[32]*y[30] + p[105]*y[18] ydot[7] = p[39]*y[31] - p[106]*y[7] - p[84]*y[57]*y[7] - p[86]*y[53]*y[7] - p[37]*y[28]*y[7] + p[85]*y[59] + p[87]*y[55] + p[38]*y[31] + p[107]*y[18] ydot[8] = -p[108]*y[8] - p[40]*y[28]*y[8] + p[41]*y[32] + p[109]*y[18] ydot[9] = -p[110]*y[9] - p[43]*y[24]*y[9] + p[44]*y[27] + p[111]*y[18] ydot[10] = -p[89]*y[10] - p[46]*y[10]*y[29] + p[47]*y[33] + p[112]*y[18] ydot[11] = -p[113]*y[11] - p[48]*y[11]*y[29] + p[49]*y[34] + p[114]*y[18] ydot[12] = -p[115]*y[12] - p[53]*y[12]*y[40] - p[57]*y[12]*y[42] - p[61]*y[12]*y[44] + p[54]*y[41] + p[58]*y[43] + p[62]*y[45] + p[116]*y[18] ydot[13] = p[90]*y[47] - p[117]*y[13] - p[63]*y[13]*y[44] + p[64]*y[46] + p[118]*y[18] ydot[14] = -p[119]*y[14] - p[66]*y[14]*y[47] + p[67]*y[48] + p[120]*y[18] ydot[15] = -p[121]*y[15] - p[69]*y[15]*y[47] + p[70]*y[49] + p[122]*y[18] ydot[16] = -p[123]*y[16] - p[74]*y[16]*y[52] + p[75]*y[54] + p[124]*y[18] ydot[17] = -p[125]*y[17] - p[77]*y[17]*y[56] + p[78]*y[57] + p[126]*y[18] ydot[18] = 0 ydot[19] = -p[20]*y[19] - p[127]*y[19] + p[18]*y[0]*y[1] - p[19]*y[19] + p[128]*y[18] ydot[20] = p[185]*y[50] + p[181]*y[48] + p[183]*y[49] + p[187]*y[51] + p[123]*y[16] + p[193]*y[54] + p[199]*y[57] + p[203]*y[59] + p[201]*y[58] + p[100]*y[4] + p[137]*y[25] + p[113]*y[11] + p[170]*y[42] + p[172]*y[43] + p[174]*y[44] + p[176]*y[45] + p[178]*y[46] + p[155]*y[34] + p[115]*y[12] + p[168]*y[41] + p[110]*y[9] + p[141]*y[27] + p[143]*y[28] + p[151]*y[32] + p[91]*y[36] + p[149]*y[31] + p[147]*y[30] + p[157]*y[35] + p[164]*y[39] + p[135]*y[24] + p[139]*y[26] + p[160]*y[37] + p[131]*y[22] + p[133]*y[23] + p[93]*y[0] + p[127]*y[19] + p[166]*y[40] + p[89]*y[10] + p[153]*y[33] + p[117]*y[13] + p[108]*y[8] + p[106]*y[7] + p[195]*y[55] + p[197]*y[56] + p[162]*y[38] + p[189]*y[52] + p[191]*y[53] + p[96]*y[2] + p[119]*y[14] + p[121]*y[15] + p[102]*y[5] + p[104]*y[6] + p[98]*y[3] + p[125]*y[17] + p[94]*y[1] + p[145]*y[29] ydot[21] = p[20]*y[19] + p[25]*y[23] - p[21]*y[2]*y[21] - p[23]*y[21]*y[3] - p[88]*y[21] + p[22]*y[22] + p[24]*y[23] + p[130]*y[18] ydot[22] = -p[131]*y[22] + p[21]*y[2]*y[21] - p[22]*y[22] + p[132]*y[18] ydot[23] = -p[25]*y[23] - p[133]*y[23] + p[23]*y[21]*y[3] - p[24]*y[23] + p[134]*y[18] ydot[24] = p[45]*y[27] + p[25]*y[23] + p[30]*y[26] + p[36]*y[39] - p[135]*y[24] - p[43]*y[24]*y[9] - p[26]*y[24]*y[4] - p[28]*y[24]*y[5] + p[44]*y[27] + p[27]*y[25] + p[29]*y[26] + p[136]*y[18] ydot[25] = -p[137]*y[25] + p[26]*y[24]*y[4] - p[27]*y[25] + p[138]*y[18] ydot[26] = -p[30]*y[26] - p[139]*y[26] + p[28]*y[24]*y[5] - p[29]*y[26] + p[140]*y[18] ydot[27] = -p[45]*y[27] - p[141]*y[27] + p[43]*y[24]*y[9] - p[44]*y[27] + p[142]*y[18] ydot[28] = p[81]*y[58] + p[30]*y[26] + p[33]*y[30] + p[42]*y[32] - p[143]*y[28] - p[31]*y[28]*y[6] - p[37]*y[28]*y[7] - p[40]*y[28]*y[8] + p[32]*y[30] + p[38]*y[31] + p[41]*y[32] + p[144]*y[18] ydot[29] = p[45]*y[27] + p[50]*y[34] - p[145]*y[29] - p[46]*y[10]*y[29] - p[48]*y[11]*y[29] + p[47]*y[33] + p[49]*y[34] + p[146]*y[18] ydot[30] = -p[33]*y[30] - p[147]*y[30] + p[31]*y[28]*y[6] - p[32]*y[30] + p[148]*y[18] ydot[31] = -p[39]*y[31] - p[149]*y[31] + p[37]*y[28]*y[7] - p[38]*y[31] + p[150]*y[18] ydot[32] = -p[42]*y[32] - p[151]*y[32] + p[40]*y[28]*y[8] - p[41]*y[32] + p[152]*y[18] ydot[33] = -p[153]*y[33] + p[46]*y[10]*y[29] - p[47]*y[33] + p[154]*y[18] ydot[34] = -p[50]*y[34] - p[155]*y[34] + p[48]*y[11]*y[29] - p[49]*y[34] + p[156]*y[18] ydot[35] = p[33]*y[30] + p[36]*y[39] - p[157]*y[35] - p[34]*y[3]*y[35] + p[35]*y[39] + p[158]*y[18] ydot[36] = p[39]*y[31] - p[91]*y[36] + p[159]*y[18] ydot[37] = p[42]*y[32] - p[160]*y[37] + p[161]*y[18] ydot[38] = p[50]*y[34] - p[162]*y[38] - p[51]*y[38] + p[52]*y[40] + p[163]*y[18] ydot[39] = -p[36]*y[39] - p[164]*y[39] + p[34]*y[3]*y[35] - p[35]*y[39] + p[165]*y[18] ydot[40] = -p[166]*y[40] + p[51]*y[38] - p[53]*y[12]*y[40] - 1.0*p[55]*pow(y[40], 2) - p[52]*y[40] + p[54]*y[41] + 2*p[56]*y[42] + p[167]*y[18] ydot[41] = -p[168]*y[41] + p[53]*y[12]*y[40] - p[54]*y[41] + p[169]*y[18] ydot[42] = -p[170]*y[42] + 0.5*p[55]*pow(y[40], 2) - p[57]*y[12]*y[42] - 1.0*p[59]*pow(y[42], 2) - p[56]*y[42] + p[58]*y[43] + 2*p[60]*y[44] + p[171]*y[18] ydot[43] = -p[172]*y[43] + p[57]*y[12]*y[42] - p[58]*y[43] + p[173]*y[18] ydot[44] = -p[174]*y[44] + 0.5*p[59]*pow(y[42], 2) - p[61]*y[12]*y[44] - p[63]*y[13]*y[44] - p[60]*y[44] + p[62]*y[45] + p[64]*y[46] + p[175]*y[18] ydot[45] = -p[176]*y[45] + p[61]*y[12]*y[44] - p[62]*y[45] + p[177]*y[18] ydot[46] = -p[65]*y[46] - p[178]*y[46] + p[63]*y[13]*y[44] - p[64]*y[46] + p[179]*y[18] ydot[47] = p[65]*y[46] + p[68]*y[48] + p[71]*y[49] - p[90]*y[47] - p[66]*y[14]*y[47] - p[69]*y[15]*y[47] + p[67]*y[48] + p[70]*y[49] + p[180]*y[18] ydot[48] = -p[68]*y[48] - p[181]*y[48] + p[66]*y[14]*y[47] - p[67]*y[48] + p[182]*y[18] ydot[49] = -p[71]*y[49] - p[183]*y[49] + p[69]*y[15]*y[47] - p[70]*y[49] + p[184]*y[18] ydot[50] = p[68]*y[48] - p[185]*y[50] - p[72]*y[50] + p[73]*y[52] + p[186]*y[18] ydot[51] = p[71]*y[49] - p[187]*y[51] - p[82]*y[51] + p[83]*y[53] + p[188]*y[18] ydot[52] = p[76]*y[54] - p[189]*y[52] + p[72]*y[50] - p[74]*y[16]*y[52] - p[73]*y[52] + p[75]*y[54] + p[190]*y[18] ydot[53] = -p[191]*y[53] + p[82]*y[51] - p[86]*y[53]*y[7] - p[83]*y[53] + p[87]*y[55] + p[192]*y[18] ydot[54] = -p[76]*y[54] - p[193]*y[54] + p[74]*y[16]*y[52] - p[75]*y[54] + p[194]*y[18] ydot[55] = -p[195]*y[55] + p[86]*y[53]*y[7] - p[87]*y[55] + p[196]*y[18] ydot[56] = p[76]*y[54] - p[197]*y[56] - p[77]*y[17]*y[56] + p[78]*y[57] + p[198]*y[18] ydot[57] = p[81]*y[58] - p[199]*y[57] + p[77]*y[17]*y[56] - p[79]*y[5]*y[57] - p[84]*y[57]*y[7] - p[78]*y[57] + p[80]*y[58] + p[85]*y[59] + p[200]*y[18] ydot[58] = -p[81]*y[58] - p[201]*y[58] + p[79]*y[5]*y[57] - p[80]*y[58] + p[202]*y[18] ydot[59] = -p[203]*y[59] + p[84]*y[57]*y[7] - p[85]*y[59] + p[204]*y[18] return ydot def simulate(self, tspan, param_values=None, view=False): if param_values is not None: # accept vector of parameter values as an argument if len(param_values) != len(self.parameters): raise Exception("param_values must have length %d" % len(self.parameters)) self.sim_param_values[:] = param_values else: # create parameter vector from the values in the model self.sim_param_values[:] = [p.value for p in self.parameters] self.y0.fill(0) for ic in self.initial_conditions: self.y0[ic.species_index] = self.sim_param_values[ic.param_index] if self.y is None or len(tspan) != len(self.y): self.y = numpy.empty((len(tspan), len(self.y0))) if len(self.observables): self.yobs = numpy.ndarray(len(tspan), zip((obs.name for obs in self.observables), itertools.repeat(float))) else: self.yobs = numpy.ndarray((len(tspan), 0)) self.yobs_view = self.yobs.view(float).reshape(len(self.yobs), -1) # perform the actual integration self.integrator.set_initial_value(self.y0, tspan[0]) self.integrator.set_f_params(self.sim_param_values) self.y[0] = self.y0 t = 1 while self.integrator.successful() and self.integrator.t < tspan[-1]: self.y[t] = self.integrator.integrate(tspan[t]) t += 1 for i, obs in enumerate(self.observables): self.yobs_view[:, i] = \ (self.y[:, obs.species] * obs.coefficients).sum(1) if view: y_out = self.y.view() yobs_out = self.yobs.view() for a in y_out, yobs_out: a.flags.writeable = False else: y_out = self.y.copy() yobs_out = self.yobs.copy() return (y_out, yobs_out)
d39ace00459e163cdff4e3d6776bcfa7c4a230f4
6ae8717002f8fce4457cceb3375a114ddcb837df
/1-100/20. Valid Parentheses.py
b66f4412d2035e54f8a192c54000a27e0634fce7
[]
no_license
SunnyMarkLiu/LeetCode
31aea2954d5a84d11a1c4435f760c1d03c6c1243
852fad258f5070c7b93c35252f7404e85e709ea6
refs/heads/master
2020-05-30T07:17:33.992197
2018-03-29T03:57:51
2018-03-29T03:57:51
104,643,862
1
1
null
null
null
null
UTF-8
Python
false
false
1,812
py
#!/home/sunnymarkliu/software/miniconda2/bin/python # _*_ coding: utf-8 _*_ """ 1. 用栈来操作,将所有的字符依次入栈,当栈顶的括号和正要入栈的括号匹配时将栈顶的括号弹出且不入栈,否则入栈新的括号。 最后,只有当栈里没有括号时,才表明输入是有效的。 2. 实际上,通过观察可以发现:如果正要入栈的是右括号,而栈顶元素不是能与之消去的相应左括号,那么该输入字符串一定是无效的。 于是,可以大大加快判断过程。 @author: MarkLiu @time : 17-11-21 下午8:16 """ class Solution(object): def isValid2(self, s): """ beat 32.85% :type s: str :rtype: bool """ stack = [] # 括号匹配可以通过字典键值对来匹配 par_map = {')': '(', ']': '[', '}': '{'} for c in s: # 新入栈的字符需要进行匹配 if len(stack) and c in par_map and par_map[c] == stack[-1]: # 所要匹配的括号和栈顶的元素相等, 匹配成功 stack.pop() else: stack.append(c) return len(stack) == 0 def isValid(self, s): """ beat 60.91% :type s: str :rtype: bool """ stack = [] # 括号匹配可以通过字典键值对来匹配 par_map = {')': '(', ']': '[', '}': '{'} for c in s: if c == ']' or c == '}' or c == ')': if len(stack) == 0 or stack[-1] != par_map[c]: return False stack.pop() else: stack.append(c) return len(stack) == 0 print Solution().isValid(']')
51b5ce98c2d3c454bb0212a899c1aa3f2f7b4148
930c207e245c320b108e9699bbbb036260a36d6a
/BRICK-RDFAlchemy/generatedCode/brick/brickschema/org/schema/_1_0_2/Brick/Heating_Supply_Air_Temperature_Proportional_Band_Setpoint.py
b48526f07713fd30d5de45bfc291f268cd171cad
[]
no_license
InnovationSE/BRICK-Generated-By-OLGA
24d278f543471e1ce622f5f45d9e305790181fff
7874dfa450a8a2b6a6f9927c0f91f9c7d2abd4d2
refs/heads/master
2021-07-01T14:13:11.302860
2017-09-21T12:44:17
2017-09-21T12:44:17
104,251,784
1
0
null
null
null
null
UTF-8
Python
false
false
853
py
from rdflib import Namespace, Graph, Literal, RDF, URIRef from rdfalchemy.rdfSubject import rdfSubject from rdfalchemy import rdfSingle, rdfMultiple, rdfList from brick.brickschema.org.schema._1_0_2.Brick.Supply_Air_Temperature_Heating_Setpoint import Supply_Air_Temperature_Heating_Setpoint from brick.brickschema.org.schema._1_0_2.Brick.Discharge_Air_Temperature_Heating_Setpoint import Discharge_Air_Temperature_Heating_Setpoint from brick.brickschema.org.schema._1_0_2.Brick.Proportional_Band_Setpoint import Proportional_Band_Setpoint class Heating_Supply_Air_Temperature_Proportional_Band_Setpoint(Supply_Air_Temperature_Heating_Setpoint,Discharge_Air_Temperature_Heating_Setpoint,Proportional_Band_Setpoint): rdf_type = Namespace('https://brickschema.org/schema/1.0.2/Brick#').Heating_Supply_Air_Temperature_Proportional_Band_Setpoint
200344d96cc290df7c5cf3b41775aa37cee6ea10
30150c7f6ed7a10ac50eee3f40101bc3165ebf9e
/src/ai/RemoveDeadTasks.py
4f69a3614353cf178eb9fa00a568ccc56fbc93a1
[]
no_license
toontown-restoration-project/toontown
c2ad0d552cb9d5d3232ae6941e28f00c11ca3aa8
9bef6d9f823b2c12a176b33518eaa51ddbe3fd2f
refs/heads/master
2022-12-23T19:46:16.697036
2020-10-02T20:17:09
2020-10-02T20:17:09
300,672,330
0
0
null
null
null
null
UTF-8
Python
false
false
2,692
py
from . import RepairAvatars from . import DatabaseObject import time # this removes all traces of a list of tasks from all avatars; if they are # working on the task, it will disappear class DeadTaskRemover(RepairAvatars.AvatarIterator): # When we come to this many non-avatars in a row, assume we have # reached the end of the database. endOfListCount = 2000 def __init__(self, air, deadTaskIds): # pass in list of questIds of tasks to remove self.deadTaskIds = deadTaskIds RepairAvatars.AvatarIterator.__init__(self, air) def fieldsToGet(self, db): return ['setName', 'setMoney', 'setQuests', 'setQuestHistory', 'setRewardHistory'] def processAvatar(self, av, db): self.printSometimes(av) # grab a copy of the av's quests flatQuests = av.getQuests() # unflatten the quests questList = [] questLen = 5 for i in range(0, len(flatQuests), questLen): questList.append(flatQuests[i:i+questLen]) # make list of quests to remove toRemove = [] for quest in questList: id = quest[0] if id in self.deadTaskIds: reward = quest[3] toRemove.append([id, reward]) # remove the quests questsChanged = (len(toRemove) > 0) questHistoryChanged = 0 rewardHistoryChanged = 0 for questId, rewardId in toRemove: av.removeQuest(questId) if av.removeQuestFromHistory(questId): questHistoryChanged = 1 if av.removeRewardFromHistory(rewardId): rewardHistoryChanged = 1 # and store the changes in the DB if questsChanged: print("Fixing %s: %s" % (av.doId, av.name)) fields = ['setQuests'] if questHistoryChanged: fields.append('setQuestHistory') if rewardHistoryChanged: fields.append('setRewardHistory') db2 = DatabaseObject.DatabaseObject(self.air, av.doId) db2.storeObject(av, fields) def printSometimes(self, av): now = time.time() if now - self.lastPrintTime > self.printInterval: print("Avatar %d: %s" % (av.doId, av.name)) self.lastPrintTime = now from . import UtilityStart f = DeadTaskRemover(simbase.air, (list(range(6979, 6999+1)) + list(range(7979, 7999+1)) + list(range(8979, 8999+1)) + list(range(9979, 9999+1)) + list(range(10979, 10999+1)))) f.start() run()
fda15d4d9037a68453de5a43d5f6e76a8e7721f6
a80e9eb7ade3d43ce042071d796c00dd10b93225
/ch_3/L3_flexible.py
17eca2a9450b5b8399b92c5c76d17a05ea4d8359
[]
no_license
ksjpswaroop/python_primer
69addfdb07471eea13dccfad1f16c212626dee0a
99c21d80953be3c9dc95f3a316c04b0c5613e830
refs/heads/master
2020-07-14T17:37:45.923796
2014-06-06T22:30:48
2014-06-06T22:30:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,018
py
# Exercise 3.31 def L3(x, n=None, epsilon=None, return_n=False): if (n is None and epsilon is None) or \ (n is not None and epsilon is not None): print 'Error: Either n or epsilon must be given (not both)' term = x / (1. + x) s = term if n is not None: for i in range(2, n + 1): # recursive relation between ci and c(i-1) term *= (i - 1.) / i * x / (1. + x) s += term return (s, n) if return_n is True else s elif epsilon is not None: i = 1 while abs(term) > epsilon: i += 1 # recursive relation between ci and c(i-1) term *= (i - 1.) / i * x / (1. + x) s += term return (s, i) if return_n is True else s print L3(10, n=100) print L3(10, n=1000, return_n=True) print L3(10, epsilon=1e-10) print L3(10, epsilon=1e-10, return_n=True) """ Sample run: python L3_flexible.py 2.39788868474 (2.397895272798365, 1000) 2.39789527188 (2.397895271877886, 187 """
c7eb200876e8053297a5a2b32fbd8ecfb0abd3fb
c857d225b50c5040e132d8c3a24005a689ee9ce4
/problem270.py
51fe86bde94fcb1af98644897b073459c97c4db5
[]
no_license
pythonsnake/project-euler
0e60a6bd2abeb5bf863110c2a551d5590c03201e
456e4ef5407d2cf021172bc9ecfc2206289ba8c9
refs/heads/master
2021-01-25T10:44:27.876962
2011-10-21T00:46:02
2011-10-21T00:46:02
2,335,706
0
0
null
null
null
null
UTF-8
Python
false
false
628
py
""" A square piece of paper with integer dimensions nn is placed with a corner at the origin and two of its sides along the x- and y-axes. then, we cut it up respecting the following rules: we only make straight cuts between two points lying on different sides of the square, and having integer coordinates. two cuts cannot cross, but several cuts can meet at the same border point. proceed until no more legal cuts can be made. counting any reflections or rotations as distinct, we call c(n) the number of ways to cut an nn square. for example, c(1) = 2 and c(2) = 30 (shown below). what is c(30) mod 108 ? """
3b382c712e6e9267fcf983b30958256927465787
3679daa10ea95e90889e07e96e6c98c98f3751ea
/ipu/dummy_company/migrations/0003_auto_20170802_2227.py
1ab5a35cc8a29af8b8748f4991d6c9e2dded39f4
[]
no_license
rmn5124/ggsipu-placement-cell-portal
0a8fef69c75ea444588046fcc7b38d7cf5c8e8e5
11876c2171bb07308719b205a69cd8330eb08052
refs/heads/master
2023-09-01T12:01:47.475984
2019-09-02T21:49:01
2019-09-02T21:49:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
777
py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-02 16:57 from __future__ import unicode_literals from decimal import Decimal import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dummy_company', '0002_auto_20170626_0952'), ] operations = [ migrations.AlterField( model_name='dummysession', name='salary', field=models.DecimalField(decimal_places=2, default=0, help_text="Salary to be offered in LPA. If it's an internship, leave this as 0, and mention salary in placement details.", max_digits=4, validators=[django.core.validators.MinValueValidator(Decimal('0'))], verbose_name='Salary (Lakhs P.A.)'), ), ]
be9452319160a2be77ed98aa146eabfbc389b6cf
a1cf8c06ad8717d06833e81fa2d1241c8fe095a0
/Multi_output/util/gendataloader.py
8b33fe0e97fd50803aa3ff87887cb9a3e689701c
[]
no_license
webstorage119/Multi_iris_pattern_classification
2ea5381ac77397df4b5bf52215e66de757eb6a6d
1c1d204cf4e9961a5dead61cc546d4eb0a3db0a8
refs/heads/master
2022-11-11T07:50:11.896482
2020-06-30T02:07:47
2020-06-30T02:07:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,217
py
from keras.preprocessing.image import ImageDataGenerator from .constants import * from tensorflow.python.keras.utils import Sequence from sklearn.preprocessing import LabelBinarizer from keras.preprocessing.image import img_to_array import cv2 import os import numpy as np from CNNUtil import paths class ImageGenerator(Sequence): def __init__(self, data_dir= 'D:\Data\iris_pattern\Multi_output2_test40_train160', augmentations=None): self.total_paths, self.defect_lbs, self.lacuna_lbs, self.spoke_lbs, self.spot_lbs = self.get_total_data_path(data_dir) self.batch_size = FLG.BATCH_SIZE self.indices = np.random.permutation(len(self.total_paths)) self.augment = augmentations def get_total_data_path(self, data_dir): total_paths, defect_lbs, lacuna_lbs, spoke_lbs, spot_lbs = [], [], [], [], [] # 이미지 path와 정답(label) 세트를 저장할 list image_paths = sorted(list(paths.list_images(data_dir))) for image_path in image_paths: # a. 이미지 전체 파일 path 저장 total_paths.append(image_path) # b. 이미지 파일 path에서 이미지의 정답(label) 세트 추출 (defect, lacuna, spoke, spot) = image_path.split(os.path.sep)[-2].split("_") defect_lbs.append(defect) lacuna_lbs.append(lacuna) spoke_lbs.append(spoke) spot_lbs.append(spot) defect_lbs = np.array(defect_lbs) lacuna_lbs = np.array(lacuna_lbs) spoke_lbs = np.array(spoke_lbs) spot_lbs = np.array(spot_lbs) defect_lbs = LabelBinarizer().fit_transform(defect_lbs) lacuna_lbs = LabelBinarizer().fit_transform(lacuna_lbs) spoke_lbs = LabelBinarizer().fit_transform(spoke_lbs) spot_lbs = LabelBinarizer().fit_transform(spot_lbs) return total_paths, defect_lbs, lacuna_lbs, spoke_lbs, spot_lbs def load_image(self, image_path): image = cv2.imread(image_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (FLG.HEIGHT, FLG.WIDTH)) if self.augment is not None: image = self.augment(image=image)['image'] image = img_to_array(image) return image def __len__(self): return len(self.total_paths) // self.batch_size def __getitem__(self, idx): batch_idx = self.indices[idx * self.batch_size: (idx + 1) * self.batch_size] x_batch, defect_batch, lacuna_batch, spoke_batch, spot_batch = [], [], [], [], [] img_paths = [self.total_paths[i] for i in batch_idx] defect_batch = [self.defect_lbs[i] for i in batch_idx] lacuna_batch = [self.lacuna_lbs[i] for i in batch_idx] spoke_batch = [self.spoke_lbs[i] for i in batch_idx] spot_batch = [self.spot_lbs[i] for i in batch_idx] for img_path in img_paths: x_batch.append(self.load_image(img_path)) x_batch = np.array(x_batch, dtype="float") / 255.0 return [x_batch], [defect_batch, lacuna_batch, spoke_batch, spot_batch] def on_epoch_end(self): print(self.batch_size) self.indices = np.random.permutation(len(self.total_paths))
2e1bb1c09a79b09675def0d26be43ebc7146545c
ce372ecceda35faf0330d1e813a57babe9517687
/Image/urls.py
4a2fa2974c051112e5a8b8a9e1fccdc12e025163
[]
no_license
Jyonn/Rizya
9b92adafd563244f722c77e48e7ceb6334515901
5d7a1435adb14276c97ef65a120635c805857ad6
refs/heads/master
2023-05-28T19:59:01.695631
2021-06-17T09:17:16
2021-06-17T09:17:16
203,008,854
0
0
null
null
null
null
UTF-8
Python
false
false
127
py
from django.urls import path from Image.views import IDView urlpatterns = [ path('@<str:image_id>', IDView.as_view()), ]
98708c98148213ef45a019c8a4757116ef8de427
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_233/ch61_2020_03_11_10_58_49_976982.py
168113a54572db24f2e8f462c85dc91c75d24631
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
152
py
def filtra_positivos(lista): nova_lista = [] for i in lista: if i > 0: nova_lista.append(i) return nova_lista
ad06e9622a82dfa853a1591d3b9c6356e7d42702
4c9c028936379c510cebfe4830f460817d9bc3c8
/apartments/views/__init__.py
fd5d28f95da1e492d95e45828cc55e745f061a1a
[]
no_license
preciousidam/management-system
cd47d7c564fe0ff0ae459c702c63a3cb16eee8ab
c984012e2cbc7554b20b00fabafd24f3f5752ba8
refs/heads/main
2023-04-02T08:44:24.416866
2021-03-11T20:09:11
2021-03-11T20:09:11
341,899,263
0
0
null
2021-04-12T14:35:07
2021-02-24T12:50:41
Python
UTF-8
Python
false
false
91
py
from .views import TenancyViewSet, ApartmentViewSet from .agreement import AgreementViewSet
67ef7c330dffe15c88c23efd1072f43a6c9a5996
d177addc1830153404c71fa115a5584f94a392c3
/N941_ValidMountainArray.py
c19d2de2c95e45e68457fcbba8b25f8d89e4ebe1
[]
no_license
zerghua/leetcode-python
38a84452f60a360e991edf90c8156de03a949000
02726da394971ef02616a038dadc126c6ff260de
refs/heads/master
2022-10-25T11:36:22.712564
2022-10-02T19:56:52
2022-10-02T19:56:52
61,502,010
2
1
null
null
null
null
UTF-8
Python
false
false
1,378
py
# # Create by Hua on 5/10/22. # """ Given an array of integers arr, return true if and only if it is a valid mountain array. Recall that arr is a mountain array if and only if: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Example 1: Input: arr = [2,1] Output: false Example 2: Input: arr = [3,5,5] Output: false Example 3: Input: arr = [0,3,2,1] Output: true Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 104 """ class Solution(object): def validMountainArray(self, arr): """ :type arr: List[int] :rtype: bool thought: find largest num/index in arr first, and check its left and right should be strictly increasing and decreasing 05/10/2022 09:52 Accepted 236 ms 14.5 MB python easy 10 min. some corner cases. """ n = len(arr) if n < 3: return False peak = arr.index(max(arr)) if peak == 0 or peak == n-1: return False for i in range(1, peak+1): # check strictly increasing if arr[i] <= arr[i-1]: return False for i in range(peak+1, n): # check strictly decreasing if arr[i] >= arr[i-1]: return False return True
36d15f5608287176a5a9980524a7100216b6b6ff
a835dc3f52df8a291fab22e64e9e3e5cbecf0c6e
/lovelive_crawlin_api/lovelive_api/migrations/0015_auto_20181012_0306.py
90b0a3ec55126030aca51e537659ef0bcc5dfb3d
[]
no_license
tails5555/lovelive_crawlin_project
99d334bb7e3c892a59ae738158e954f4ad322296
d0bd42ab183a8a75a07f52c0cf7ab30cb634b513
refs/heads/master
2020-03-30T04:12:00.102091
2018-11-27T08:04:40
2018-11-27T08:04:40
150,729,532
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
# Generated by Django 2.1.2 on 2018-10-11 18:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lovelive_api', '0014_auto_20181012_0244'), ] operations = [ migrations.AlterField( model_name='cardimage', name='img_file', field=models.ImageField(upload_to='card_images'), ), ]
c774eba8f762603582d1bd6169a68a91053f588c
4b2229d6364c4f3919880ce24df0d40f1b1cff3c
/sequtus/tests/covers.py
60f9513327305f411936b3d01736a3d621d81f89
[]
no_license
Teifion/Sequtus-2
4960d3b3710bb24eb34bec23f8a639c7bb2922a3
d7dd3a9fbdf50e8b7545e03cb39d3762b9bf2eb7
refs/heads/master
2020-04-06T06:46:23.958577
2012-05-12T19:46:39
2012-05-12T19:46:39
3,030,129
0
0
null
null
null
null
UTF-8
Python
false
false
11,530
py
""" This code is released as-is with no warranty of any sort. You are welcome to alter and distribute though I'd appreciate credit being given where possible. Written by Teifion Jordan (http://woarl.com) Usage: covers.get_coverage() suite is expected to be a unittest.TestSuite root_dir is the root directory to start scanning from module_skip and dirs_skip are a list of strings of the relevant modules and dirs to miss from the scan (3rd party libraries for example) output_mode is the mode in which the results are output In each unittest.TestCase instance you need to add a property of "test_targets" as a list of functions and classes that test case targets so that covers knows what is covered. """ import os import re import sys import unittest import webbrowser from collections import OrderedDict get_module_name = re.compile(r'.*?/?(.*?)\.py') def get_coverage(suite, root_dir="default", verbose = True, module_skip = [], dirs_skip = [], output_mode="print"): if root_dir == "default": root_dir = "%s/" % sys.path[0] modules = OrderedDict() module_skip.extend(["__init__", "covers"]) dirs_skip.extend(["__pycache__", ".git"]) output = [] # First we need a list of all the modules we want to look at, we simply walk through all folders in the root directory for root, dirs, files in os.walk(root_dir): for d in dirs_skip: if d in dirs: dirs.remove(d) folder = root.replace(root_dir, "") for f in files: # We only want to look at python files if "".join(f[-3:len(f)]) == '.py': file_name = get_module_name.search(f) if file_name != None: file_name = file_name.groups()[0].strip() else: raise Warning("The file {0} passed the .py test but no match was found".format(f)) if file_name in module_skip: continue # Now to actually import it if folder == "": try: coverage_module = __import__(file_name) except ImportError as e: print("Error importing {0}".format(file_name)) raise else: try: coverage_module = __import__(folder.replace("/", "."), fromlist=[file_name]) coverage_module = getattr(coverage_module, file_name) except ValueError as e: print("Error importing {0}.{1}".format(folder.replace("/", "."), file_name)) print("Folder: {0}, File: {1}".format(folder, file_name)) raise except ImportError as e: print("Error importing {0}.{1}".format(folder.replace("/", "."), file_name)) print("Folder: {0}, File: {1}".format(folder, file_name)) raise # Now we add it to our list modules[(folder, file_name)] = coverage_module # Examine the test result data test_program_info = get_test_targets(suite) # test_program_info = get_test_targets(test_program.test) # Stats covered = 0 total = 0 red, yellow, green = 0, 0, 0 # Run through each module to get all classes and functions last_folder = '' output.append("/") for path, the_module in modules.items(): folder, module_name = path # We need to print the folder we're looking into if last_folder != folder: last_folder = folder output.append("\n{0}".format(folder)) # Look at this module and work out what we've covered in it line, temp_covered, temp_total = evaluate_module(module_name, the_module, test_program_info, verbose) if line: output.append(line) # Stats stuff covered += temp_covered total += temp_total if temp_total == 0: continue if temp_covered < temp_total: if temp_covered > 0: yellow += 1 else: red += 1 else: green += 1 if total != 0: percentage = (covered/total)*100 else: percentage = 0 # Now print out final verdict if output_mode == "web": output_html(output, covered, total, green, yellow, red) elif output_mode == "print": print("\n".join([colour_text(s) for s in output])) print("") print("%d out of %d (%d%%)" % (covered, total, percentage)) print("%d greens" % green) print("%d yellows" % yellow) print("%d reds" % red) elif output_mode == "summary": print("%d out of %d (%d%%)" % (covered, total, (percentage))) print("%d greens" % green) print("%d yellows" % yellow) print("%d reds" % red) def output_html(output, covered, total, green, yellow, red): html = [] html_patterns = ( (re.compile(r"''([^']*)''"), r"<strong>\1</strong>"), (re.compile(r'__([^_]*)__'), r'<em>\1</em>'), (re.compile(r"\*\*([^*]*)\*\*"), r"<blink>\1</blink>"), (re.compile(r"\[r\](.*?)\[\/r\]"), r"<span style='color: #A00;'>\1</span>"), (re.compile(r"\[g\](.*?)\[\/g\]"), r"<span style='color: #0A0;'>\1</span>"), (re.compile(r"\[y\](.*?)\[\/y\]"), r"<span style='color: #AA0;'>\1</span>"), (re.compile(r"\[b\](.*?)\[\/b\]"), r"<span style='color: #00A;'>\1</span>"), (re.compile(r"\[m\](.*?)\[\/m\]"), r"<span style='color: #A0A;'>\1</span>"), (re.compile(r"\[c\](.*?)\[\/c\]"), r"<span style='color: #0AA;'>\1</span>"), ) for l in output: text = l for regex, replacement in html_patterns: text = regex.sub(replacement, text) html.append(text) with open('/tmp/covers_py.html', 'w') as f: f.write("<pre>") f.write("\n".join(html)) f.write("</pre>") webbrowser.open('file:///tmp/covers_py.html') def get_test_targets(suite): targets = set() for module_tests in suite._tests: for t in module_tests._tests: try: for f in t.test_targets: targets.add(f) except AttributeError as e: # It's assumed it has no targets pass return list(targets) skipables = ("<type 'int'>", "<type 'str'>", "<type 'module'>", "<type 'NoneType'>", "<type 'dict'>", "<type 'tuple'>", "<type 'list'>" ) SRE_Pattern = type(re.compile("")) def get_testables(the_module): functions, classes = [], [] for d in dir(the_module): f = getattr(the_module, d) # These cause errors and we don't want to match them anyway if type(f) == SRE_Pattern: continue # If it's a function we add it to the list # In Python 3 we use <class not <type if str(f.__class__) == "<type 'function'>": if f.__module__ == the_module.__name__: functions.append(f) elif str(f.__class__) == "<type 'type'>": # If it's a class and from this module then want both it and any functions it may have if f.__module__ == the_module.__name__ or True: classes.append((f, get_type_functions(the_module, f))) elif str(f.__class__) in skipables: continue else: pass # print(f.__class__, str(f)[0:20]) return functions, classes def get_type_functions(the_module, the_type): functions = [] for d in dir(the_type): f = getattr(the_type, d) if str(f.__class__) == "<class 'function'>" or str(f.__class__) == "<type 'instancemethod'>": if f.__name__ != '__init__': if f.__module__ == the_module.__name__: functions.append(f) return functions def evaluate_module(module_name, the_module, test_program_info, verbose=False): output = [] functions, classes = get_testables(the_module) function_count = len(functions) # Each function/class that is a part of the module covered_functions = 0 for f in functions: function_count += 1 if f in test_program_info: covered_functions += 1 output.append(" [g]%s[/g]" % f.__name__) else: output.append(" [r]%s[/r]" % f.__name__) # Now classes for c, funcs in classes: function_count += len(funcs) if len(funcs) == 0: continue if sum([1 if f not in test_program_info else 0 for f in funcs]) > 0: all_tested = False else: all_tested = True # Class data if all_tested: output.append(" [g]%s[/g]" % c.__name__) else: output.append(" [r]%s[/r]" % c.__name__) for f in funcs: if f in test_program_info: covered_functions += 1 output.append(" [g]%s[/g]" % f.__name__) else: output.append(" [r]%s[/r]" % f.__name__) # If there were no functions we can call it quits now if function_count == 0: if verbose: return " %s has no functions" % module_name, 0, 0 else: return None, 0, 0 # At the top of the pile is the module name and it's stats if covered_functions < function_count: if covered_functions > 0: h = " [y]{0:24}[/y] ({1}/{2}, {3}%)".format(module_name, covered_functions, function_count, round((covered_functions/function_count)*100)) else: h = " [r]{0:24}[/r] ({1}/{2}, 0%)".format(module_name, covered_functions, function_count) else: h = " [g]{0:24}[/g] ({1}/{2}, 100%)".format(module_name, covered_functions, function_count) # And now we bundle it all up if verbose: output.insert(0, h) return "\n".join(output), covered_functions, function_count else: return h, covered_functions, function_count shell_patterns = ( (re.compile(r"''([^']*)''"), '\033[1;1m\\1\033[30;0m'), (re.compile(r'__([^_]*)__'), '\033[1;4m\\1\033[30;0m'), (re.compile(r"\*\*([^*]*)\*\*"), '\033[1;5m\\1\033[30;0m'), (re.compile(r"\[r\](.*?)\[\/r\]"), '\033[31m\\1\033[30;0m'), (re.compile(r"\[g\](.*?)\[\/g\]"), '\033[32m\\1\033[30;0m'), (re.compile(r"\[y\](.*?)\[\/y\]"), '\033[33m\\1\033[30;0m'), (re.compile(r"\[b\](.*?)\[\/b\]"), '\033[34m\\1\033[30;0m'), (re.compile(r"\[m\](.*?)\[\/m\]"), '\033[35m\\1\033[30;0m'), (re.compile(r"\[c\](.*?)\[\/c\]"), '\033[36m\\1\033[30;0m'), ) def colour_text(text): """ Converts text to display in the shell with pretty colours Bold: ''{TEXT}'' Underline: __{TEXT}__ Blink: **{TEXT}** Colour: [colour]{TEXT}[/colour] Colours supported: Red, Green, Yellow, Blue, Magenta, Cyan """ if type(text) != str: return text for regex, replacement in shell_patterns: text = regex.sub(replacement, text) return text
50baffaed091096a06ea1478956eb5c01a849c0e
aebe93e3c4d15f64b2611d9b8b5332ce05e37d72
/Implement_Queue_Stacks.py
bdb5d00130ba64bf23c940741f172441f900585f
[]
no_license
liuwei881/leetcode
37fa7d329df78f63a8aa48905096b46952533a95
33d329a7ce13aeeb1813b7471188cd689f91a1e8
refs/heads/master
2020-04-26T22:00:16.813430
2019-04-24T03:20:45
2019-04-24T03:20:45
173,858,310
1
0
null
null
null
null
UTF-8
Python
false
false
2,036
py
# coding=utf-8 """ Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Example: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // returns 1 queue.pop(); // returns 1 queue.empty(); // returns false Notes: You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). """ class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ swap = [] while self.stack: swap.append(self.stack.pop()) swap.append(x) while swap: self.stack.append(swap.pop()) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ return self.stack.pop() def peek(self) -> int: """ Get the front element. """ if self.stack: return self.stack[-1] return False def empty(self) -> bool: """ Returns whether the queue is empty. """ return len(self.stack) == 0 if __name__ =='__main__': # Your MyQueue object will be instantiated and called as such: x = 5 x1 = 6 obj = MyQueue() obj.push(x) obj.push(x1) param_2 = obj.pop() param_3 = obj.peek() param_4 = obj.empty() print(param_2, param_3, param_4)
5a4cb878245c61dc6dbbdffff2942db0a0164075
5ae98342461af8568aa03e6377f83efb649f6799
/helper/javascript_completions/show_hint_parameters_command.py
fe014339f7e004793f69700b701748a9cc81fb11
[ "MIT" ]
permissive
minimallinux/JavaScriptEnhancements
30651ffb647848646c52138dc3c1a02577fe3210
d9f578022d9cdf5ee6541319c6a129f896350bee
refs/heads/master
2021-05-05T21:56:07.179554
2018-01-03T02:46:12
2018-01-03T02:46:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,253
py
import sublime, sublime_plugin class show_hint_parametersCommand(sublime_plugin.TextCommand): def run(self, edit, **args): view = self.view scope = view.scope_name(view.sel()[0].begin()).strip() meta_fun_call = "meta.function-call.method.js" result = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call+" meta.group.js") if not result : meta_fun_call = "meta.function-call.js" result = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call+" meta.group.js") if result : point = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call)["region"].begin() sublime.set_timeout_async(lambda: on_hover_description_async(view, point, sublime.HOVER_TEXT, view.sel()[0].begin())) def is_enabled(self) : view = self.view sel = view.sel()[0] if not view.match_selector( sel.begin(), 'source.js - comment' ): return False scope = view.scope_name(view.sel()[0].begin()).strip() meta_fun_call = "meta.function-call.method.js" result = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call+" meta.group.js") if not result : meta_fun_call = "meta.function-call.js" result = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call+" meta.group.js") if result : point = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call)["region"].begin() scope_splitted = scope.split(" ") find_and_get_scope = Util.find_and_get_pre_string_and_matches(scope, meta_fun_call+" meta.group.js") find_and_get_scope_splitted = find_and_get_scope.split(" ") if ( ( len(scope_splitted) == len(find_and_get_scope_splitted) + 1 or scope == find_and_get_scope or ( len(scope_splitted) == len(find_and_get_scope_splitted) + 2 and ( Util.get_parent_region_scope(view, view.sel()[0])["scope"].split(" ")[-1] == "string.quoted.double.js" or Util.get_parent_region_scope(view, view.sel()[0])["scope"].split(" ")[-1] == "string.quoted.single.js" or Util.get_parent_region_scope(view, view.sel()[0])["scope"].split(" ")[-1] == "string.template.js" ) ) ) and not scope.endswith("meta.block.js") and not scope.endswith("meta.object-literal.js") ) : return True return False def is_visible(self) : view = self.view sel = view.sel()[0] if not view.match_selector( sel.begin(), 'source.js - comment' ): return False scope = view.scope_name(view.sel()[0].begin()).strip() meta_fun_call = "meta.function-call.method.js" result = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call+" meta.group.js") if not result : meta_fun_call = "meta.function-call.js" result = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call+" meta.group.js") if result : point = Util.get_region_scope_last_match(view, scope, view.sel()[0], meta_fun_call)["region"].begin() scope_splitted = scope.split(" ") find_and_get_scope = Util.find_and_get_pre_string_and_matches(scope, meta_fun_call+" meta.group.js") find_and_get_scope_splitted = find_and_get_scope.split(" ") if ( ( len(scope_splitted) == len(find_and_get_scope_splitted) + 1 or scope == find_and_get_scope or ( len(scope_splitted) == len(find_and_get_scope_splitted) + 2 and ( Util.get_parent_region_scope(view, view.sel()[0])["scope"].split(" ")[-1] == "string.quoted.double.js" or Util.get_parent_region_scope(view, view.sel()[0])["scope"].split(" ")[-1] == "string.quoted.single.js" or Util.get_parent_region_scope(view, view.sel()[0])["scope"].split(" ")[-1] == "string.template.js" ) ) ) and not scope.endswith("meta.block.js") and not scope.endswith("meta.object-literal.js") ) : return True return False
b2f89bafaa88589c3f1df86671f16797c3be58f1
20930fa97c20bc41a363782446c8939be47f7f98
/promus/command/_reset.py
e8e214aeb2cb85e56d1ca1d29ee207d038b789b0
[ "BSD-3-Clause" ]
permissive
jmlopez-rod/promus
1018214b502eb1dc0c7a7e5e7fcfaae7666c3826
2d5b8ac54afe721298f6326f45fd3587bc00d173
refs/heads/master
2016-09-10T03:35:01.710952
2014-08-22T22:01:22
2014-08-22T22:01:22
21,441,146
0
1
null
null
null
null
UTF-8
Python
false
false
1,459
py
"""_RESET This is an axilary function to fix the old repositories created with the beta version of promus. """ import textwrap import promus.core as prc DESC = """ Reset the git hooks. Note that this version does not create a backup of the current hooks. Also you must be in the git repository. """ def add_parser(subp, raw): "Add a parser to the main subparser. " tmpp = subp.add_parser('_reset', help='reset git hooks', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('--bare', action='store_true', help="Use this option for bare repositories") def reset_hooks(): """Command to rest hooks in a repository. """ print("resetting hooks:") hooks = ['commit-msg', 'post-checkout', 'post-commit', 'post-merge', 'pre-commit', 'pre-rebase', 'prepare-commit-msg'] for hook in hooks: print(" %s" % hook) path = './.git/hooks' prc.make_hook(hook, path) def reset_hooks_bare(): """Command to reset hooks in a bare repository. """ print("resetting hooks in bare repository:") hooks = ['post-receive', 'update'] for hook in hooks: print(" %s" % hook) path = './hooks' prc.make_hook(hook, path) def run(arg): """Run command. """ if arg.bare: reset_hooks_bare() else: reset_hooks()
f635881af6bfd767402839af0261703339e1f00a
5a5bcfe21defcaf6b050b0c92e8ec03cee7eb50f
/gencrud/gen/utils/querystring_parser/tests.py
f7d30e10bcc5b7a4b736b41322d789a188308548
[]
no_license
marychev/gencrud
dc146c570a81ed0665f6bec309f106d966be349a
d6dc478b9a079aba5589591fa2e79665179e28a2
refs/heads/master
2023-01-06T18:50:13.417451
2020-10-23T18:05:38
2020-10-23T18:05:38
262,617,213
2
0
null
2020-05-10T18:35:19
2020-05-09T16:55:28
Python
UTF-8
Python
false
false
12,456
py
# coding: utf-8 ''' Created on 2011-05-13 @author: berni Updated 2012-03-28 Tomasz 'Doppler' Najdek Updated 2012-09-24 Bernard 'berni' Kobos ''' import sys from .parser import (parse, MalformedQueryStringError) from .builder import build import unittest class KnownValues(unittest.TestCase): ''' Test output for known query string values ''' knownValuesClean = ( ({u'omg': {0: u'0001212'}}), ( # "packetname=fd&section[0]['words'][2]=&section[0]['words'][2]=&language=1&packetdesc=sdfsd&newlanguage=proponowany jezyk..&newsectionname=&section[0]['words'][1]=&section[0]['words'][1]=&packettype=radio&section[0]['words'][0]=sdfsd&section[0]['words'][0]=ds", {u"packetname": u"fd", u"section": {0: {u"words": {0: [u"sdfsd", u"ds"], 1: [u"", u""], 2: [u"", u""]}}}, u"language": u"1", u"packetdesc": u"sdfsd", u"newlanguage": u"proponowany jezyk..", u"newsectionname": u"", u"packettype": u"radio"} ), ( # "language=1&newlanguage=proponowany jezyk..&newsectionname=&packetdesc=Zajebiste slowka na jutrzejszy sprawdzian z chemii&packetid=4&packetname=Chemia spr&packettype=1&section[10]['name']=sekcja siatkarska&section[10]['words'][-1]=&section[10]['words'][-1]=&section[10]['words'][-2]=&section[10]['words'][-2]=&section[10]['words'][30]=noga&section[10]['words'][30]=leg&section[11]['del_words'][32]=kciuk&section[11]['del_words'][32]=thimb&section[11]['del_words'][33]=oko&section[11]['del_words'][33]=an eye&section[11]['name']=sekcja siatkarska1&section[11]['words'][-1]=&section[11]['words'][-1]=&section[11]['words'][-2]=&section[11]['words'][-2]=&section[11]['words'][31]=renca&section[11]['words'][31]=rukka&section[12]['name']=sekcja siatkarska2&section[12]['words'][-1]=&section[12]['words'][-1]=&section[12]['words'][-2]=&section[12]['words'][-2]=&section[12]['words'][34]=wlos&section[12]['words'][34]=a hair&sectionnew=sekcja siatkarska&sectionnew=sekcja siatkarska1&sectionnew=sekcja siatkarska2&tags=dance, angielski, taniec", {u"packetdesc": u"Zajebiste slowka na jutrzejszy sprawdzian z chemii", u"packetid": u"4", u"packetname": u"Chemia spr", u"section": { 10: {u"words": {-1: [u"", u""], -2: [u"", u""], 30: [u"noga", u"leg"]}, u"name": u"sekcja siatkarska"}, 11: {u"words": {-1: [u"", u""], -2: [u"", u""], 31: [u"renca", u"rukka"]}, u"del_words": {32: [u"kciuk", u"thimb"], 33: [u"oko", u"an eye"]}, u"name": u"sekcja siatkarska1"}, 12: {u"words": {-1: [u"", u""], -2: [u"", u""], 34: [u"wlos", u"a hair"]}, u"name": u"sekcja siatkarska2"}}, u"language": u"1", u"newlanguage": u"proponowany jezyk..", u"packettype": u"1", u"tags": u"dance, angielski, taniec", u"newsectionname": u"", u"sectionnew": [u"sekcja siatkarska", u"sekcja siatkarska1", u"sekcja siatkarska2"]} ), ( # "f=a hair&sectionnew[]=sekcja siatkarska&sectionnew[]=sekcja siatkarska1&sectionnew[]=sekcja siatkarska2", {u"f": u"a hair", u"sectionnew": {u"": [u"sekcja siatkarska", u"sekcja siatkarska1", u"sekcja siatkarska2"]}} ), # f = a ({u"f": u"a"}), # "" ({}), ) knownValues = ( ({u'omg': {0: u'0001212'}}), ( # "packetname=f%26d&section%5B0%5D%5B%27words%27%5D%5B2%5D=&section%5B0%5D%5B%27words%27%5D%5B2%5D=&language=1&packetdesc=sdfsd&newlanguage=proponowany+jezyk..&newsectionname=&section%5B0%5D%5B%27words%27%5D%5B1%5D=&section%5B0%5D%5B%27words%27%5D%5B1%5D=&packettype=radio&section%5B0%5D%5B%27words%27%5D%5B0%5D=sdfsd&section%5B0%5D%5B%27words%27%5D%5B0%5D=ds", {u"packetname": u"f&d", u"section": {0: {u"words": {0: [u"sdfsd", u"ds"], 1: [u"", u""], 2: [u"", u""]}}}, u"language": u"1", u"packetdesc": u"sdfsd", u"newlanguage": u"proponowany jezyk..", u"newsectionname": u"", u"packettype": u"radio"} ), ( # "language=1&newlanguage=proponowany+jezyk..&newsectionname=&packetdesc=Zajebiste+slowka+na+jutrzejszy+sprawdzian+z+chemii&packetid=4&packetname=Chemia+spr&packettype=1&section%5B10%5D%5B%27name%27%5D=sekcja+siatkarska&section%5B10%5D%5B%27words%27%5D%5B-1%5D=&section%5B10%5D%5B%27words%27%5D%5B-1%5D=&section%5B10%5D%5B%27words%27%5D%5B-2%5D=&section%5B10%5D%5B%27words%27%5D%5B-2%5D=&section%5B10%5D%5B%27words%27%5D%5B30%5D=noga&section%5B10%5D%5B%27words%27%5D%5B30%5D=leg&section%5B11%5D%5B%27del_words%27%5D%5B32%5D=kciuk&section%5B11%5D%5B%27del_words%27%5D%5B32%5D=thimb&section%5B11%5D%5B%27del_words%27%5D%5B33%5D=oko&section%5B11%5D%5B%27del_words%27%5D%5B33%5D=an+eye&section%5B11%5D%5B%27name%27%5D=sekcja+siatkarska1&section%5B11%5D%5B%27words%27%5D%5B-1%5D=&section%5B11%5D%5B%27words%27%5D%5B-1%5D=&section%5B11%5D%5B%27words%27%5D%5B-2%5D=&section%5B11%5D%5B%27words%27%5D%5B-2%5D=&section%5B11%5D%5B%27words%27%5D%5B31%5D=renca&section%5B11%5D%5B%27words%27%5D%5B31%5D=rukka&section%5B12%5D%5B%27name%27%5D=sekcja+siatkarska2&section%5B12%5D%5B%27words%27%5D%5B-1%5D=&section%5B12%5D%5B%27words%27%5D%5B-1%5D=&section%5B12%5D%5B%27words%27%5D%5B-2%5D=&section%5B12%5D%5B%27words%27%5D%5B-2%5D=&section%5B12%5D%5B%27words%27%5D%5B34%5D=wlos&section%5B12%5D%5B%27words%27%5D%5B34%5D=a+hair&sectionnew=sekcja%3Dsiatkarska&sectionnew=sekcja+siatkarska1&sectionnew=sekcja+siatkarska2&tags=dance%2C+angielski%2C+taniec", {u"packetdesc": u"Zajebiste slowka na jutrzejszy sprawdzian z chemii", u"packetid": u"4", u"packetname": u"Chemia spr", u"section": { 10: {u"words": {-1: [u"", u""], -2: [u"", u""], 30: [u"noga", u"leg"]}, u"name": u"sekcja siatkarska"}, 11: {u"words": {-1: [u"", u""], -2: [u"", u""], 31: [u"renca", u"rukka"]}, u"del_words": {32: [u"kciuk", u"thimb"], 33: [u"oko", u"an eye"]}, u"name": u"sekcja siatkarska1"}, 12: {u"words": {-1: [u"", u""], -2: [u"", u""], 34: [u"wlos", u"a hair"]}, u"name": u"sekcja siatkarska2"}}, u"language": u"1", u"newlanguage": u"proponowany jezyk..", u"packettype": u"1", u"tags": u"dance, angielski, taniec", u"newsectionname": "", u"sectionnew": [u"sekcja=siatkarska", u"sekcja siatkarska1", u"sekcja siatkarska2"]} ), ( # "f=a+hair&sectionnew%5B%5D=sekcja+siatkarska&sectionnew%5B%5D=sekcja+siatkarska1&sectionnew%5B%5D=sekcja+siatkarska2", {u"f": u"a hair", u"sectionnew": {u"": [u"sekcja siatkarska", u"sekcja siatkarska1", u"sekcja siatkarska2"]}} ), # f = a ({u"f": u"a"}), # "" ({}), ) knownValuesCleanWithUnicode = ( # f = some unicode ({u"f": u"\u9017"}), ) knownValuesWithUnicode = ( # f = some unicode ({u"f": u"\u9017"}), ) def test_parse_known_values_clean(self): """parse should give known result with known input""" self.maxDiff = None for dic in self.knownValuesClean: result = parse(build(dic), unquote=True) self.assertEqual(dic, result) def test_parse_known_values(self): """parse should give known result with known input (quoted)""" self.maxDiff = None for dic in self.knownValues: result = parse(build(dic)) self.assertEqual(dic, result) def test_parse_known_values_clean_with_unicode(self): """parse should give known result with known input""" self.maxDiff = None encoding = 'utf-8' if sys.version_info[0] == 2 else None for dic in self.knownValuesClean + self.knownValuesCleanWithUnicode: result = parse(build(dic, encoding=encoding), unquote=True, encoding=encoding) self.assertEqual(dic, result) def test_parse_known_values_with_unicode(self): """parse should give known result with known input (quoted)""" self.maxDiff = None encoding = 'utf-8' if sys.version_info[0] == 2 else None for dic in self.knownValues + self.knownValuesWithUnicode: result = parse(build(dic, encoding=encoding), encoding=encoding) self.assertEqual(dic, result) def test_parse_unicode_input_string(self): """https://github.com/bernii/querystring-parser/issues/15""" qs = u'first_name=%D8%B9%D9%84%DB%8C' expected = {u'first_name': u'\u0639\u0644\u06cc'} self.assertEqual(parse(qs.encode('ascii')), expected) self.assertEqual(parse(qs), expected) class ParseBadInput(unittest.TestCase): ''' Test for exceptions when bad input is provided ''' badQueryStrings = ( "f&a hair&sectionnew[]=sekcja siatkarska&sectionnew[]=sekcja siatkarska1&sectionnew[]=sekcja siatkarska2", "f=a hair&sectionnew[=sekcja siatkarska&sectionnew[]=sekcja siatkarska1&sectionnew[]=sekcja siatkarska2", "packetname==fd&newsectionname=", "packetname=fd&newsectionname=&section[0]['words'][1", "packetname=fd&newsectionname=&", ) def test_bad_input(self): """parse should fail with malformed querystring""" for qstr in self.badQueryStrings: self.assertRaises(MalformedQueryStringError, parse, qstr, False) class BuildUrl(unittest.TestCase): ''' Basic test to verify builder's functionality ''' request_data = { u"word": u"easy", u"more_words": [u"medium", u"average"], u"words_with_translation": {u"hard": u"trudny", u"tough": u"twardy"}, u"words_nested": {u"hard": [u"trudny", u"twardy"]} } def test_build(self): result = build(self.request_data) self.assertEquals(parse(result), self.request_data) def test_end_to_end(self): self.maxDiff = None querystring = build(self.request_data) result = parse(querystring) self.assertEquals(result, self.request_data) class BuilderAndParser(unittest.TestCase): ''' Testing both builder and parser ''' def test_end_to_end(self): parsed = parse('a[]=1&a[]=2') result = build(parsed) self.assertEquals(result, "a[]=1&a[]=2") class NormalizedParse(unittest.TestCase): ''' ''' knownValues = {"section": {10: {u"words": {-1: [u"", u""], -2: [u"", u""], 30: [u"noga", u"leg"]}, "name": u"sekcja siatkarska"}, 11: {u"words": {-1: [u"", u""], -2: [u"", u""], 31: [u"renca", u"rukka"]}, u"del_words": {32: [u"kciuk", u"thimb"], 33: [u"oko", u"an eye"]}, u"name": u"sekcja siatkarska1"}, 12: {u"words": {-1: [u"", u""], -2: [u"", u""], 34: [u"wlos", u"a hair"]}, u"name": u"sekcja siatkarska2"}}} knownValuesNormalized = {'section': [{'name': 'sekcja siatkarska', 'words': [['', ''], ['', ''], ['noga', 'leg']]}, {'del_words': [['kciuk', 'thimb'], ['oko', 'an eye']], 'name': 'sekcja siatkarska1', 'words': [['', ''], ['', ''], ['renca', 'rukka']]}, {'name': 'sekcja siatkarska2', # 'words': [['wlos', 'a hair'], ['', ''], # ['', '']]}]} 'words': [['', ''], ['', ''], ['wlos', 'a hair'], ]}]} def test_parse_normalized(self): result = parse(build(self.knownValues), normalized=True) self.assertEqual(self.knownValuesNormalized, result) if __name__ == "__main__": unittest.main()
e72a39d27f535fd09ff5275560423a14d4aeec5a
8e2d9ad65441f92234ec3bf1dfbcb31535d21331
/Baekjoon/11720_숫자의 합.py
2805502314908415ccb5cec321a93a2b92b5eb2f
[]
no_license
taesu-park/PycharmProjects
28671e7d4e27e2325ccbb4044e57db57ec27cc2a
0c39769564a6e51a35ff33bb7a992a46dd2db0ba
refs/heads/master
2020-07-06T15:32:52.980355
2020-03-18T19:09:32
2020-03-18T19:09:32
203,067,974
0
0
null
null
null
null
UTF-8
Python
false
false
87
py
N = int(input()) arr = list(input()) sum = 0 for i in arr: sum += int(i) print(sum)
203a44dd016c6c369edec9ac043147ed5e9b0d56
048df2b4dc5ad153a36afad33831017800b9b9c7
/atcoder/abc003/abc003_2.py
8d06191a63417901073e63aa87577afe758fc7c4
[]
no_license
fluffyowl/past-submissions
a73e8f5157c647634668c200cd977f4428c6ac7d
24706da1f79e5595b2f9f2583c736135ea055eb7
refs/heads/master
2022-02-21T06:32:43.156817
2019-09-16T00:17:50
2019-09-16T00:17:50
71,639,325
0
0
null
null
null
null
UTF-8
Python
false
false
306
py
s = raw_input() t = raw_input() atcoder = set(list('atcoder@')) for i in range(len(s)): if s[i] == t[i]: continue if s[i] == '@' and t[i] in atcoder: continue if t[i] == '@' and s[i] in atcoder: continue print 'You will lose' break else: print 'You can win'
d90c2a8eb4a3e0e16ee723fed99f987a006669e1
1af4ec17c474e5c05e4de1a471247b546f32c7c7
/funcoes/gerador_html_v2.py
4154f930334f5ab6d7483645c4e523224c07e1f7
[]
no_license
ribeiro-rodrigo-exemplos/curso-python
825d09bb4284e65c3ba67bed8dcf8b29ac1c90eb
101c610161775d73b46cc64a668451dfa65abf7d
refs/heads/master
2020-05-18T06:43:37.263995
2019-06-17T09:32:58
2019-06-17T09:32:58
184,241,840
0
0
null
null
null
null
UTF-8
Python
false
false
421
py
#!/usr/bin/python3 def tag_bloco(texto, classe='success', inline=False): tag = 'span' if inline else 'div' return f'<{tag} class="{classe}">{texto}</{tag}>' if __name__ == '__main__': print(tag_bloco('bloco')) print(tag_bloco('inline e classe', 'info', True)) print(tag_bloco('inline', inline=True)) print(tag_bloco(inline=True, texto='inline')) print(tag_bloco('falhou', classe='error'))
42333d8e0b5efa7e7e6a23a038e8b16586645d8c
c80d264e1e7af78505af076da879c62cfa247d35
/Vow_str.py
afa20822a95d536c5c957e93e792651fad8a9439
[]
no_license
shanthivimalanataraajan01/Codekataplayer
f3679c365099d0f6dedf2fe6b93bd308c67bc485
2af9997a164daef213b1053f0becfc0327735f21
refs/heads/master
2020-05-23T12:00:19.855401
2019-05-05T07:20:07
2019-05-05T07:20:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
260
py
def vow(x): c=0 v=['a','e','i','o','u'] for i in x: if i in v: c+=1 if c>=1: a=1 else: a=0 return a n=int(input()) g=[] d=0 for i in range(0,n): g.append(input()) for i in g: if vow(i)==1: d+=1 if d==len(g): print("yes") else: print("no")
d7a436e6e55cf21fc9c78b8d1320284f36f44d69
37f1125544ac1b4800402d981ce030c82b4993d8
/pythonitems/APIAutoTest20200304/demo/other/demo_unittest03.py
edd4364a6fec5462ef3dd21c08a57161179baf6c
[]
no_license
shixingjian/PythonItems
db6392451fda388ef4f4805aaf9991ec01bd36bd
6b6a4e4bae2e727581c8805676422f28b8f6231f
refs/heads/master
2022-11-21T01:17:23.607196
2020-07-22T08:37:44
2020-07-22T08:37:44
281,614,603
1
0
null
null
null
null
UTF-8
Python
false
false
1,920
py
#-*-coding:utf-8-*- #@Time:2020/4/910:02 #@Author:freya #@File:dem0_unnittest03.py from demo.other.demo_calculator import Calculator import unittest from ddt import ddt,data from lib.excelManage import readExcel import time from lib.sendCourseRequest import SendCourceRequest import json """ UnitTest结合DDT语法学习 """ mydata=[[1,2,3],[3,4,7],[4,5,9]] path=r'../../data/教管系统-测试用例V1.2.xls' #2-读取测试用例 mydata2=readExcel(path,1) @ddt class UnittestDemo3(unittest.TestCase): @classmethod def setUpClass(cls): cls.calculator=Calculator(12,3) print('setUp方法运行了\r\n') #1. 测试加法 def test_001(self): print('>>>>用例1运行了') result=self.calculator.add() self.assertEqual(result,15) #2. 测试减法 def test_002(self): print('>>>>用例2运行了') result=self.calculator.sub() self.assertEqual(result,9) #3. 测试乘法 def test_003(self): print('>>>>用例3运行了') result=self.calculator.mul() self.assertEqual(result,36) #4. 测试除法 def test_004(self): print('>>>>用例4运行了') result=self.calculator.div() self.assertEqual(result,4) # 5. 测试加法2 @data(*mydata) def test_005(self,data): result=self.calculator.add2(data[0],data[1]) self.assertEqual(result,data[2]) print('>>>>用例5运行了') # 6. 批量执行excel测试用例 @data(*mydata2) def test_006(self,row): # print(row) dictBody = SendCourceRequest(row) time.sleep(0.001) test = json.loads(row[6]) print('>>>>用例6运行了') # if 'reason' in dictBody.keys(): # self.assertEqual(dictBody['retcode'], test['code'],dictBody['reason']) # else: self.assertEqual(dictBody['retcode'], test['code'])
f6834b518da6ec85721a33f3d0411fe0f27e0ce3
336a5f79d935c277be6d4b22cf3cc58e48c1344d
/tensorflow_probability/python/math/psd_kernels/psd_kernel_properties_test.py
08b1970db617e8472a618484d6c93464c2dd7aff
[ "Apache-2.0" ]
permissive
fearghus-moloco/probability
9300328febe09f18bf84e31b7588106588a60fbd
4b675da7c431d7bb20029f9fdd28db859e6c025f
refs/heads/master
2023-08-06T08:36:03.041624
2021-09-10T22:34:54
2021-09-10T22:41:07
288,120,063
0
0
Apache-2.0
2020-08-17T08:04:39
2020-08-17T08:04:38
null
UTF-8
Python
false
false
6,236
py
# Copyright 2018 The TensorFlow Probability 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import hypothesis as hp from hypothesis import strategies as hps import tensorflow.compat.v2 as tf from tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps from tensorflow_probability.python.internal import tensor_util from tensorflow_probability.python.internal import test_util from tensorflow_probability.python.math.psd_kernels import hypothesis_testlib as kernel_hps # pylint is unable to handle @hps.composite (e.g. complains "No value for # argument '...' in function call"), so disable this lint for the file. # pylint: disable=no-value-for-parameter EXTRA_TENSOR_CONVERSION_KERNELS = { # The transformation is applied to each input individually. 'KumaraswamyTransformed': 1, } def assert_no_none_grad(kernel, method, wrt_vars, grads): for var, grad in zip(wrt_vars, grads): # For the GeneralizedMatern kernel, gradients with respect to `df` don't # exist. if tensor_util.is_ref(var) and var.name.strip('_0123456789:') == 'df': continue if grad is None: raise AssertionError('Missing `{}` -> {} grad for kernel {}'.format( method, var, kernel)) @test_util.test_all_tf_execution_regimes class KernelPropertiesTest(test_util.TestCase): @parameterized.named_parameters( {'testcase_name': dname, 'kernel_name': dname} for dname in sorted(list(kernel_hps.INSTANTIABLE_BASE_KERNELS.keys()) + list(kernel_hps.SPECIAL_KERNELS))) @hp.given(hps.data()) @tfp_hps.tfp_hp_settings( default_max_examples=10, suppress_health_check=[ hp.HealthCheck.too_slow, hp.HealthCheck.data_too_large]) def testKernelGradient(self, kernel_name, data): event_dim = data.draw(hps.integers(min_value=2, max_value=3)) feature_ndims = data.draw(hps.integers(min_value=1, max_value=2)) feature_dim = data.draw(hps.integers(min_value=2, max_value=4)) batch_shape = data.draw(tfp_hps.shapes(max_ndims=2)) kernel, kernel_parameter_variable_names = data.draw( kernel_hps.kernels( batch_shape=batch_shape, kernel_name=kernel_name, event_dim=event_dim, feature_dim=feature_dim, feature_ndims=feature_ndims, enable_vars=True)) # Check that variable parameters get passed to the kernel.variables kernel_variables_names = [ v.name.strip('_0123456789:') for v in kernel.variables] kernel_parameter_variable_names = [ n.strip('_0123456789:') for n in kernel_parameter_variable_names] self.assertEqual( set(kernel_parameter_variable_names), set(kernel_variables_names)) example_ndims = data.draw(hps.integers(min_value=1, max_value=2)) input_batch_shape = data.draw(tfp_hps.broadcast_compatible_shape( kernel.batch_shape)) xs = tf.identity(data.draw(kernel_hps.kernel_input( batch_shape=input_batch_shape, example_ndims=example_ndims, feature_dim=feature_dim, feature_ndims=feature_ndims))) # Check that we pick up all relevant kernel parameters. wrt_vars = [xs] + list(kernel.variables) self.evaluate([v.initializer for v in kernel.variables]) max_permissible = 2 + EXTRA_TENSOR_CONVERSION_KERNELS.get(kernel_name, 0) with tf.GradientTape() as tape: with tfp_hps.assert_no_excessive_var_usage( 'method `apply` of {}'.format(kernel), max_permissible=max_permissible ): tape.watch(wrt_vars) with tfp_hps.no_tf_rank_errors(): diag = kernel.apply(xs, xs, example_ndims=example_ndims) grads = tape.gradient(diag, wrt_vars) assert_no_none_grad(kernel, 'apply', wrt_vars, grads) # Check that copying the kernel works. with tfp_hps.no_tf_rank_errors(): diag2 = self.evaluate(kernel.copy().apply( xs, xs, example_ndims=example_ndims)) self.assertAllClose(diag, diag2) @parameterized.named_parameters( {'testcase_name': dname, 'kernel_name': dname} for dname in sorted(list(kernel_hps.INSTANTIABLE_BASE_KERNELS.keys()) + list(kernel_hps.SPECIAL_KERNELS))) @hp.given(hps.data()) @tfp_hps.tfp_hp_settings( default_max_examples=10, suppress_health_check=[ hp.HealthCheck.too_slow, hp.HealthCheck.data_too_large]) def testCompositeTensor(self, kernel_name, data): kernel, _ = data.draw( kernel_hps.kernels( kernel_name=kernel_name, event_dim=2, feature_dim=2, feature_ndims=1, enable_vars=True)) self.assertIsInstance(kernel, tf.__internal__.CompositeTensor) xs = tf.identity(data.draw(kernel_hps.kernel_input( batch_shape=[], example_ndims=1, feature_dim=2, feature_ndims=1))) with tfp_hps.no_tf_rank_errors(): diag = kernel.apply(xs, xs, example_ndims=1) # Test flatten/unflatten. flat = tf.nest.flatten(kernel, expand_composites=True) unflat = tf.nest.pack_sequence_as(kernel, flat, expand_composites=True) # Test tf.function. @tf.function def diag_fn(k): return k.apply(xs, xs, example_ndims=1) self.evaluate([v.initializer for v in kernel.variables]) with tfp_hps.no_tf_rank_errors(): self.assertAllClose(diag, diag_fn(kernel)) self.assertAllClose(diag, diag_fn(unflat)) if __name__ == '__main__': test_util.main()
37a541c1f5362364dd6c285b52b15dead97246ab
b7137589ec15f08f687fe4a56693be59e95e550f
/backend/blank_test_19535/wsgi.py
bb7e46c39a2636de4f8d656cfd59e9732578eb66
[]
no_license
crowdbotics-apps/blank-test-19535
25391cac32119702065fcd1070fcc6bb32379138
849e0186882cf69fd9008bb58685fc0e187b4b77
refs/heads/master
2022-12-07T03:07:26.627979
2020-08-24T14:30:14
2020-08-24T14:30:14
287,266,165
0
0
null
null
null
null
UTF-8
Python
false
false
409
py
""" WSGI config for blank_test_19535 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blank_test_19535.settings") application = get_wsgi_application()
3265659206a20735c52f8a36a3d204d9ed935475
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02850/s650053544.py
67d112724c3be08773f6d9bb68cb786210ef37d7
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
1,401
py
from collections import Counter, defaultdict import sys sys.setrecursionlimit(10 ** 5 + 10) # input = sys.stdin.readline from math import factorial import heapq, bisect import math import itertools import queue from collections import deque from fractions import Fraction def main(): num = int(input()) data = [list(map(int, input().split())) for i in range(num - 1)] node_data = defaultdict(set) for i in range(num - 1): a, b = data[i] node_data[a].add(b) node_data[b].add(a) ans_num = 0 for i in range(1, num + 1): ans_num = max(ans_num, len(node_data[i])) edge_data = defaultdict(int) ans_count = 0 for i in range(1, num + 1): now_list = list(node_data[i]) now_list.sort() count = bisect.bisect_left(now_list, i) + 1 use_set = set() for ele in now_list[:count - 1]: use_set.add(edge_data[(i, ele)]) now_indx = 1 for ele in now_list[count - 1:]: while now_indx in use_set: now_indx += 1 edge_data[(i, ele)] = now_indx edge_data[(ele, i)] = now_indx use_set.add(now_indx) ans_count = max(ans_count, now_indx) print(ans_count) for i in range(num - 1): a, b = data[i] ans = edge_data[(a, b)] print(ans) if __name__ == '__main__': main()
85ced45bf2ef40af67c5cbb064e9619f7baac7cf
e063c54c9e73b393e6092d2d1510d1f942904528
/src/cryptoadvance/specter/devices/generic.py
b4f00abda29ec6b7039f21dd6d5cddcd9ea04b63
[ "MIT" ]
permissive
zndtoshi/specter-desktop
bd1633dc273c2a6a4eedae7f545fb715155bb8ec
00c32b0fed4b49380de8e311d79a790756dacba5
refs/heads/master
2022-11-25T01:06:49.869265
2020-08-05T20:37:14
2020-08-05T20:37:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
446
py
from ..device import Device class GenericDevice(Device): def __init__(self, name, alias, device_type, keys, fullpath, manager): super().__init__(name, alias, 'other', keys, fullpath, manager) self.sd_card_support = True self.qr_code_support = True def create_psbts(self, base64_psbt, wallet): psbts = { 'qrcode': base64_psbt, 'sdcard': base64_psbt, } return psbts
d4dd4d3745bb28e8388a448e33d8e736a4a10859
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/335/usersdata/303/99133/submittedfiles/matriz1.py
8d6f119a5e174147ca17c1bd61a5ad1fbb6d2d1f
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
729
py
# -*- coding: utf-8 -*- a=[] m=int(input('')) n=int(input('')) for i in range(0,m,1): linha=[] for j in range(0,n,1): linha.append(int(input(''))) a.append(linha) #ANALISE SUPERIOR/INFERIOR c=[] for i in range(0,m,1): if sum(a[i])>=1: c.append(i) break for i in range(m-1,-1,-1): if sum(a[i])>=1: c.append(i) break #LIMITES LATERAIS lat=[] for i in range(0,m,1): for j in range(0,n,1): if a[i][j]==1: lat.append(j) lat=sorted(lat) #LIMITES INTEIROS c1=int(c[0]) c2=int(c[1]) x1=int(lat[0]) x2=int(lat[len(lat)-1]) #CRIAÇÃO DA NOVA MATRIZ n=[] for i in range(c1,c2+1,1): for j in range(x1,x2+1,1): n.append(a[i][j]) print(n)
cd7f1750274d2977bd85d9c9c294caeca2215804
0649b25962931fe2b659e64b6580640b647b675c
/watson/auth/providers/abc.py
2059353119b6f8ca6cbfee271ac4ed48938fc4b1
[ "BSD-2-Clause" ]
permissive
watsonpy/watson-auth
117994ef9bb2b45817955a002d77be2462be0337
44057e21e24f272f39414ff15a275cf6f9f009e2
refs/heads/master
2022-05-26T23:52:17.507355
2019-10-03T04:28:38
2019-10-03T04:28:38
16,093,607
0
0
BSD-3-Clause
2022-05-25T00:34:21
2014-01-21T05:29:44
Python
UTF-8
Python
false
false
3,673
py
import abc from sqlalchemy.orm import exc from watson.auth import crypto from watson.auth.providers import exceptions from watson.common import imports from watson.common.decorators import cached_property class Base(object): config = None session = None def __init__(self, config, session): self._validate_configuration(config) self.config = config self.session = session # Configuration def _validate_configuration(self, config): if 'class' not in config['model']: raise exceptions.InvalidConfiguration( 'User model not specified, ensure "class" key is set on provider["model"].') common_keys = [ 'system_email_from_address', 'reset_password_route', 'forgotten_password_route'] for key in common_keys: if key not in config: raise exceptions.InvalidConfiguration( 'Ensure "{}" key is set on the provider.'.format(key)) # User retrieval @property def user_model_identifier(self): return self.config['model']['identifier'] @cached_property def user_model(self): return imports.load_definition_from_string( self.config['model']['class']) @property def user_query(self): return self.session.query(self.user_model) def get_user(self, username): """Retrieves a user from the database based on their username. Args: username (string): The username of the user to find. """ user_field = getattr(self.user_model, self.user_model_identifier) try: return self.user_query.filter(user_field == username).one() except exc.NoResultFound: return None def get_user_by_email_address(self, email_address): email_column = getattr( self.user_model, self.config['model']['email_address']) try: return self.user_query.filter(email_column == email_address).one() except exc.NoResultFound: return None # Authentication def authenticate(self, username, password): """Validate a user against a supplied username and password. Args: username (string): The username of the user. password (string): The password of the user. """ password_config = self.config['password'] if len(password) > password_config['max_length']: return None user = self.get_user(username) if user: if crypto.check_password(password, user.password, user.salt, self.config['encoding']): return user return None def user_meets_requirements(self, user, requires): for require in requires or []: if not require(user): return False return True # Authorization def is_authorized(self, user, roles=None, permissions=None, requires=None): no_role = roles and not user.acl.has_role(roles) no_permission = permissions and not user.acl.has_permission( permissions) no_requires = self.user_meets_requirements(user, requires) return False if no_role or no_permission or not no_requires else True # Actions @abc.abstractmethod def logout(self, request): raise NotImplementedError # pragma: no cover @abc.abstractmethod def login(self, user, request): raise NotImplementedError # pragma: no cover @abc.abstractmethod def handle_request(self, request): raise NotImplementedError # pragma: no cover
d5dc3061eb7cbe5b2f99bf91cb705fc72aec5fe0
5ad0dace59e449fb0928d7b302f386a84d634e05
/MERFISH_probe_design/probe_design/quality_check.py
5fe0f510f97bb6cde2f80a95246af7eb9d347da1
[ "MIT" ]
permissive
r3fang/merfish_designer
69784fcadebfb912b0a5557081f120abcc16f2d8
c8ca3a1c825e6b381e0bbd9654ef7d3c9107bb9c
refs/heads/main
2023-09-03T17:16:08.554990
2021-10-21T17:33:33
2021-10-21T17:33:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,471
py
#!/usr/bin/env python3 import numpy as np import pandas as pd def check_and_standardize_transcriptome(transcriptome:pd.core.frame.DataFrame, remove_non_standard_columns:bool=False): '''Check the quality of the transcriptome and standardize it. Return a standardized transcriptome.''' standard_transcriptome = transcriptome # Check the existance of standarad columns standard_columns = ['transcript_id', 'sequence', 'gene_id', 'gene_short_name', 'FPKM'] for sc in standard_columns: if not sc in transcriptome.columns: print(f'\033[91m ERROR: missing the standard column {sc}!') # Remove non-standard columns if remove_non_standard_columns: nscs = [c for c in transcriptome.columns if c not in standard_columns] standard_transcriptome = transcriptome.drop(columns=nscs) # Check that the transcript ids are unique t_ids, counts = np.unique(np.array(standard_transcriptome['transcript_id']), return_counts=True) for i in range(len(t_ids)): if counts[i] > 1: print(f'\033[91m ERROR: the transcript {t_ids[i]} have {counts[i]} entries!') return standard_transcriptome def barcode_str_to_array(bc_str:str): return np.array([int(c) for c in bc_str]) def barcode_array_to_str(bc_array:np.ndarray): return ''.join(['1' if i > 0 else '0' for i in bc_array]) def coverage_string(probe_bit_counts:np.ndarray): return ':'.join([str(i) for i in probe_bit_counts if i > 0]) def max_N_non_overlapping_probes(shifts:list, target_length:int): ss = sorted(shifts) N_accepted = 0 tail = -1 for s in ss: if s > tail: N_accepted += 1 tail = s + target_length - 1 return N_accepted def generate_transcript_level_report(probe_dict:dict, transcriptome:pd.core.frame.DataFrame): '''Generate a data frame of transcript level metrics. ''' metrics = {'gene_id':[], 'gene_short_name':[], 'transcript_id':[], 'FPKM':[], 'length':[], 'barcode':[], 'N_probes':[], 'probe_bit_coverage':[], 'max_N_non_overlapping_probes':[]} for gk in probe_dict.keys(): for tk in probe_dict[gk].keys(): transcript_df = transcriptome[transcriptome['transcript_id'] == tk] # Add the basic metrics metrics['gene_id'].append(transcript_df.iloc[0]['gene_id']) metrics['gene_short_name'].append(transcript_df.iloc[0]['gene_short_name']) metrics['transcript_id'].append(transcript_df.iloc[0]['transcript_id']) metrics['FPKM'].append(transcript_df.iloc[0]['FPKM']) metrics['length'].append(len(transcript_df.iloc[0]['sequence'])) metrics['N_probes'].append(probe_dict[gk][tk].shape[0]) # Calculate barcode related metrics probe_barcodes = [barcode_str_to_array(bc_str) for bc_str in probe_dict[gk][tk]['probe_barcode']] probe_bit_counts = np.sum(probe_barcodes, axis=0) metrics['barcode'].append(barcode_array_to_str(probe_bit_counts)) metrics['probe_bit_coverage'].append(coverage_string(probe_bit_counts)) # Calculate the overlapping matric target_length = len(probe_dict[gk][tk].iloc[0]['target_sequence']) metrics['max_N_non_overlapping_probes'].append(max_N_non_overlapping_probes( list(probe_dict[gk][tk]['shift']), target_length)) return pd.DataFrame(metrics)
aff49207e5329af6de37a0e3f5893be8c2d66c42
e523652e0379f291f675e5cba4c1f667a3ac3b19
/commands/on
9338a7cc67189251954edfa16efecf5b8cb3426d
[ "Apache-2.0" ]
permissive
sbp/saxo
735bac23c8d214b85ca48c5c43bc12b1531ce137
27030c57ed565db1aafd801576555ae64893d637
refs/heads/master
2023-09-01T09:08:13.633734
2023-08-29T12:51:40
2023-08-29T12:51:40
9,411,794
25
13
Apache-2.0
2021-06-19T15:09:44
2013-04-13T10:06:52
Python
UTF-8
Python
false
false
1,287
#!/usr/bin/env python3 # http://inamidst.com/saxo/ # Created by Sean B. Palmer import calendar import datetime import random import re import time import saxo months = "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" r_arg = re.compile("(\d?\d %s)(?: (.*))?$" % months) @saxo.pipe def main(arg): if not arg: return "Set a reminder at a certain time. Must match " + r_arg.pattern match = r_arg.match(arg) if not match: return "Sorry, input must match " + r_arg.pattern now = datetime.datetime.now() t = datetime.datetime.strptime(match.group(1), "%d %b") t = t.replace(hour=8) t = t.replace(year=now.year) t = t.replace(second=random.randint(1, 60)) if t < now: t = t.replace(year=t.year + 1) message = match.group(2) unixtime = calendar.timegm(t.utctimetuple()) nick = saxo.env("nick") sender = saxo.env("sender") if not (nick or sender): return "Sorry, couldn't set a reminder!" if message: message = nick + ": " + message else: message = nick + "!" args = (unixtime, "msg", (sender, message)) saxo.client("schedule", *args) when = time.strftime("%d %b %Y %H:%M:%S UTC", time.gmtime(unixtime)) return "%s: Will remind at %s" % (nick, when)
be586f969f0d8cca5ea9db4244f816c8061ed23c
f8d3f814067415485bb439d7fe92dc2bbe22a048
/opencvlib/test/imgpipes/test_digikamlib.py
90d8375bb93b17004e2cf311cbea6861fabd1708
[]
no_license
gmonkman/python
2f9ab8f159c01f6235c86cb0cd52062cd3fdedd3
9123aa6baf538b662143b9098d963d55165e8409
refs/heads/master
2023-04-09T15:53:29.746676
2022-11-26T20:35:21
2022-11-26T20:35:21
60,254,898
0
2
null
2023-03-24T22:58:39
2016-06-02T10:25:27
Python
UTF-8
Python
false
false
2,074
py
# pylint: disable=C0103, too-few-public-methods, locally-disabled, no-self-use, unused-argument '''unit tests for digikamlib which is used to interact with the digikam sqlite database''' import unittest from inspect import getsourcefile as _getsourcefile import os.path as _path import opencvlib.imgpipes.digikamlib as digikamlib import funclib.iolib as iolib class Test(unittest.TestCase): '''unittest for keypoints''' def setUp(self): '''setup variables etc for use in test cases ''' self.pth = iolib.get_file_parts2(_path.abspath(_getsourcefile(lambda: 0)))[0] self.modpath = _path.normpath(self.pth) #@unittest.skip("Temporaily disabled while debugging") def test_images_by_tags_or(self): '''test_imagesbytags''' ImgP = digikamlib.ImagePaths('C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/digikam4.db') lst = ImgP.images_by_tags_or( album_label='images', relative_path='bass/angler', species=['bass', 'pollock']) print(str(len(lst))) #@unittest.skip("Temporaily disabled while debugging") def test_images_by_tags_outer_and_inner_or(self): '''test_imagesbytags''' ImgP = digikamlib.ImagePaths('C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/digikam4.db') lst = ImgP.images_by_tags_outerAnd_innerOr( album_label='images', relative_path='bass/angler', species=['bass', 'pollock'], pitch=['0', '45', '180'], roll='0', yaw=['0', '180']) print(str(len(lst))) #@unittest.skip("Temporaily disabled while debugging") def test_images_by_tags_outer_and(self): '''test_imagesbytags''' ImgP = digikamlib.ImagePaths('C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/digikam4.db') lst = ImgP.images_by_tags_outerAnd_innerOr( album_label='images', relative_path='bass/angler', species='bass', pitch='0') print(str(len(lst))) if __name__ == '__main__': unittest.main()
9bd874f1f17f209339092465488af26b4baf5faa
328ebfdbcef076ce0e930715f9bd786d7498185b
/lang/python/Complete-Python-Developer-in-2021-Zero-to-Mastery/1st pass/11-modules/newjokes/venv/lib/python3.9/site-packages/pip/_internal/commands/debug.py
3abef1af9d27bfb72ac967279b93f6cc91d5dd33
[]
no_license
pnowak2/learnjs
b618e6f9563b3e86be0b1a21d647698e289daec0
f8842b4e9e5d2eae6fb4e0d663b6699d74c90e9c
refs/heads/master
2023-08-30T05:04:00.227920
2023-08-18T10:58:24
2023-08-18T10:58:24
41,912,571
3
0
null
2023-03-31T06:58:40
2015-09-04T11:36:13
Python
UTF-8
Python
false
false
13,934
py
<<<<<<< HEAD import locale import logging import os import sys import pip._vendor from pip._vendor import pkg_resources from pip._vendor.certifi import where from pip._vendor.packaging.version import parse as parse_version from pip import __file__ as pip_location from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_pip_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from types import ModuleType from typing import Dict, List, Optional from pip._internal.configuration import Configuration logger = logging.getLogger(__name__) def show_value(name, value): # type: (str, Optional[str]) -> None logger.info('%s: %s', name, value) def show_sys_implementation(): # type: () -> None logger.info('sys.implementation:') implementation_name = sys.implementation.name with indent_log(): show_value('name', implementation_name) def create_vendor_txt_map(): # type: () -> Dict[str, str] vendor_txt_path = os.path.join( os.path.dirname(pip_location), '_vendor', 'vendor.txt' ) with open(vendor_txt_path) as f: # Purge non version specifying lines. # Also, remove any space prefix or suffixes (including comments). lines = [line.strip().split(' ', 1)[0] for line in f.readlines() if '==' in line] # Transform into "module" -> version dict. return dict(line.split('==', 1) for line in lines) # type: ignore def get_module_from_module_name(module_name): # type: (str) -> ModuleType # Module name can be uppercase in vendor.txt for some reason... module_name = module_name.lower() # PATCH: setuptools is actually only pkg_resources. if module_name == 'setuptools': module_name = 'pkg_resources' __import__( f'pip._vendor.{module_name}', globals(), locals(), level=0 ) return getattr(pip._vendor, module_name) def get_vendor_version_from_module(module_name): # type: (str) -> Optional[str] module = get_module_from_module_name(module_name) version = getattr(module, '__version__', None) if not version: # Try to find version in debundled module info pkg_set = pkg_resources.WorkingSet([os.path.dirname(module.__file__)]) package = pkg_set.find(pkg_resources.Requirement.parse(module_name)) version = getattr(package, 'version', None) return version def show_actual_vendor_versions(vendor_txt_versions): # type: (Dict[str, str]) -> None """Log the actual version and print extra info if there is a conflict or if the actual version could not be imported. """ for module_name, expected_version in vendor_txt_versions.items(): extra_message = '' actual_version = get_vendor_version_from_module(module_name) if not actual_version: extra_message = ' (Unable to locate actual module version, using'\ ' vendor.txt specified version)' actual_version = expected_version elif parse_version(actual_version) != parse_version(expected_version): extra_message = ' (CONFLICT: vendor.txt suggests version should'\ ' be {})'.format(expected_version) logger.info('%s==%s%s', module_name, actual_version, extra_message) def show_vendor_versions(): # type: () -> None logger.info('vendored library versions:') vendor_txt_versions = create_vendor_txt_map() with indent_log(): show_actual_vendor_versions(vendor_txt_versions) def show_tags(options): # type: (Values) -> None tag_limit = 10 target_python = make_target_python(options) tags = target_python.get_tags() # Display the target options that were explicitly provided. formatted_target = target_python.format_given() suffix = '' if formatted_target: suffix = f' (target: {formatted_target})' msg = 'Compatible tags: {}{}'.format(len(tags), suffix) logger.info(msg) if options.verbose < 1 and len(tags) > tag_limit: tags_limited = True tags = tags[:tag_limit] else: tags_limited = False with indent_log(): for tag in tags: logger.info(str(tag)) if tags_limited: msg = ( '...\n' '[First {tag_limit} tags shown. Pass --verbose to show all.]' ).format(tag_limit=tag_limit) logger.info(msg) def ca_bundle_info(config): # type: (Configuration) -> str levels = set() for key, _ in config.items(): levels.add(key.split('.')[0]) if not levels: return "Not specified" levels_that_override_global = ['install', 'wheel', 'download'] global_overriding_level = [ level for level in levels if level in levels_that_override_global ] if not global_overriding_level: return 'global' if 'global' in levels: levels.remove('global') return ", ".join(levels) class DebugCommand(Command): """ Display debug information. """ usage = """ %prog <options>""" ignore_require_venv = True def add_options(self): # type: () -> None cmdoptions.add_target_python_options(self.cmd_opts) self.parser.insert_option_group(0, self.cmd_opts) self.parser.config.load() def run(self, options, args): # type: (Values, List[str]) -> int logger.warning( "This command is only meant for debugging. " "Do not use this with automation for parsing and getting these " "details, since the output and options of this command may " "change without notice." ) show_value('pip version', get_pip_version()) show_value('sys.version', sys.version) show_value('sys.executable', sys.executable) show_value('sys.getdefaultencoding', sys.getdefaultencoding()) show_value('sys.getfilesystemencoding', sys.getfilesystemencoding()) show_value( 'locale.getpreferredencoding', locale.getpreferredencoding(), ) show_value('sys.platform', sys.platform) show_sys_implementation() show_value("'cert' config value", ca_bundle_info(self.parser.config)) show_value("REQUESTS_CA_BUNDLE", os.environ.get('REQUESTS_CA_BUNDLE')) show_value("CURL_CA_BUNDLE", os.environ.get('CURL_CA_BUNDLE')) show_value("pip._vendor.certifi.where()", where()) show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED) show_vendor_versions() show_tags(options) return SUCCESS ======= import locale import logging import os import sys import pip._vendor from pip._vendor import pkg_resources from pip._vendor.certifi import where from pip._vendor.packaging.version import parse as parse_version from pip import __file__ as pip_location from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_pip_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from types import ModuleType from typing import Dict, List, Optional from pip._internal.configuration import Configuration logger = logging.getLogger(__name__) def show_value(name, value): # type: (str, Optional[str]) -> None logger.info('%s: %s', name, value) def show_sys_implementation(): # type: () -> None logger.info('sys.implementation:') implementation_name = sys.implementation.name with indent_log(): show_value('name', implementation_name) def create_vendor_txt_map(): # type: () -> Dict[str, str] vendor_txt_path = os.path.join( os.path.dirname(pip_location), '_vendor', 'vendor.txt' ) with open(vendor_txt_path) as f: # Purge non version specifying lines. # Also, remove any space prefix or suffixes (including comments). lines = [line.strip().split(' ', 1)[0] for line in f.readlines() if '==' in line] # Transform into "module" -> version dict. return dict(line.split('==', 1) for line in lines) # type: ignore def get_module_from_module_name(module_name): # type: (str) -> ModuleType # Module name can be uppercase in vendor.txt for some reason... module_name = module_name.lower() # PATCH: setuptools is actually only pkg_resources. if module_name == 'setuptools': module_name = 'pkg_resources' __import__( f'pip._vendor.{module_name}', globals(), locals(), level=0 ) return getattr(pip._vendor, module_name) def get_vendor_version_from_module(module_name): # type: (str) -> Optional[str] module = get_module_from_module_name(module_name) version = getattr(module, '__version__', None) if not version: # Try to find version in debundled module info pkg_set = pkg_resources.WorkingSet([os.path.dirname(module.__file__)]) package = pkg_set.find(pkg_resources.Requirement.parse(module_name)) version = getattr(package, 'version', None) return version def show_actual_vendor_versions(vendor_txt_versions): # type: (Dict[str, str]) -> None """Log the actual version and print extra info if there is a conflict or if the actual version could not be imported. """ for module_name, expected_version in vendor_txt_versions.items(): extra_message = '' actual_version = get_vendor_version_from_module(module_name) if not actual_version: extra_message = ' (Unable to locate actual module version, using'\ ' vendor.txt specified version)' actual_version = expected_version elif parse_version(actual_version) != parse_version(expected_version): extra_message = ' (CONFLICT: vendor.txt suggests version should'\ ' be {})'.format(expected_version) logger.info('%s==%s%s', module_name, actual_version, extra_message) def show_vendor_versions(): # type: () -> None logger.info('vendored library versions:') vendor_txt_versions = create_vendor_txt_map() with indent_log(): show_actual_vendor_versions(vendor_txt_versions) def show_tags(options): # type: (Values) -> None tag_limit = 10 target_python = make_target_python(options) tags = target_python.get_tags() # Display the target options that were explicitly provided. formatted_target = target_python.format_given() suffix = '' if formatted_target: suffix = f' (target: {formatted_target})' msg = 'Compatible tags: {}{}'.format(len(tags), suffix) logger.info(msg) if options.verbose < 1 and len(tags) > tag_limit: tags_limited = True tags = tags[:tag_limit] else: tags_limited = False with indent_log(): for tag in tags: logger.info(str(tag)) if tags_limited: msg = ( '...\n' '[First {tag_limit} tags shown. Pass --verbose to show all.]' ).format(tag_limit=tag_limit) logger.info(msg) def ca_bundle_info(config): # type: (Configuration) -> str levels = set() for key, _ in config.items(): levels.add(key.split('.')[0]) if not levels: return "Not specified" levels_that_override_global = ['install', 'wheel', 'download'] global_overriding_level = [ level for level in levels if level in levels_that_override_global ] if not global_overriding_level: return 'global' if 'global' in levels: levels.remove('global') return ", ".join(levels) class DebugCommand(Command): """ Display debug information. """ usage = """ %prog <options>""" ignore_require_venv = True def add_options(self): # type: () -> None cmdoptions.add_target_python_options(self.cmd_opts) self.parser.insert_option_group(0, self.cmd_opts) self.parser.config.load() def run(self, options, args): # type: (Values, List[str]) -> int logger.warning( "This command is only meant for debugging. " "Do not use this with automation for parsing and getting these " "details, since the output and options of this command may " "change without notice." ) show_value('pip version', get_pip_version()) show_value('sys.version', sys.version) show_value('sys.executable', sys.executable) show_value('sys.getdefaultencoding', sys.getdefaultencoding()) show_value('sys.getfilesystemencoding', sys.getfilesystemencoding()) show_value( 'locale.getpreferredencoding', locale.getpreferredencoding(), ) show_value('sys.platform', sys.platform) show_sys_implementation() show_value("'cert' config value", ca_bundle_info(self.parser.config)) show_value("REQUESTS_CA_BUNDLE", os.environ.get('REQUESTS_CA_BUNDLE')) show_value("CURL_CA_BUNDLE", os.environ.get('CURL_CA_BUNDLE')) show_value("pip._vendor.certifi.where()", where()) show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED) show_vendor_versions() show_tags(options) return SUCCESS >>>>>>> 09ca5278bea3c4aca18b55f7b3bde8928f648bf3
d3d58a4b31205e7f350a10f5cafce63d2264d44f
facb8b9155a569b09ba66aefc22564a5bf9cd319
/wp2/era5_scripts/01_netCDF_extraction/erafive902TG/417-tideGauge.py
ab7076eb96dc93a1d051f0c632732ff5642fe508
[]
no_license
moinabyssinia/modeling-global-storm-surges
13e69faa8f45a1244a964c5de4e2a5a6c95b2128
6e385b2a5f0867df8ceabd155e17ba876779c1bd
refs/heads/master
2023-06-09T00:40:39.319465
2021-06-25T21:00:44
2021-06-25T21:00:44
229,080,191
0
0
null
null
null
null
UTF-8
Python
false
false
4,595
py
# -*- coding: utf-8 -*- """ Created on Mon Jun 01 10:00:00 2020 ERA5 netCDF extraction script @author: Michael Tadesse """ import time as tt import os import pandas as pd from d_define_grid import Coordinate, findPixels, findindx from c_read_netcdf import readnetcdf from f_era5_subsetV2 import subsetter def extract_data(delta= 1): """ This is the master function that calls subsequent functions to extract uwnd, vwnd, slp for the specified tide gauges delta: distance (in degrees) from the tide gauge """ print('Delta = {}'.format(delta), '\n') #defining the folders for predictors nc_path = {'slp' : "/lustre/fs0/home/mtadesse/era_five/slp",\ "wnd_u": "/lustre/fs0/home/mtadesse/era_five/wnd_u",\ 'wnd_v' : "/lustre/fs0/home/mtadesse/era_five/wnd_v"} surge_path = "/lustre/fs0/home/mtadesse/obs_surge" csv_path = "/lustre/fs0/home/mtadesse/erafive_localized" #cd to the obs_surge dir to get TG information os.chdir(surge_path) tg_list = os.listdir() ################################# #looping through the predictor folders ################################# for pf in nc_path.keys(): print(pf, '\n') os.chdir(nc_path[pf]) #################################### #looping through the years of the chosen predictor #################################### for py in os.listdir(): os.chdir(nc_path[pf]) #back to the predictor folder print(py, '\n') #get netcdf components - give predicor name and predictor file nc_file = readnetcdf(pf, py) lon, lat, time, pred = nc_file[0], nc_file[1], nc_file[2], \ nc_file[3] x = 417 y = 418 #looping through individual tide gauges for t in range(x, y): #the name of the tide gauge - for saving purposes # tg = tg_list[t].split('.mat.mat.csv')[0] tg = tg_list[t] #extract lon and lat data from surge csv file print("tide gauge", tg, '\n') os.chdir(surge_path) if os.stat(tg).st_size == 0: print('\n', "This tide gauge has no surge data!", '\n') continue surge = pd.read_csv(tg, header = None) #surge_with_date = add_date(surge) #define tide gauge coordinate(lon, lat) tg_cord = Coordinate(float(surge.iloc[1,4]), float(surge.iloc[1,5])) print(tg_cord) #find closest grid points and their indices close_grids = findPixels(tg_cord, delta, lon, lat) ind_grids = findindx(close_grids, lon, lat) ind_grids.columns = ['lon', 'lat'] #loop through preds# #subset predictor on selected grid size print("subsetting \n") pred_new = subsetter(pred, ind_grids, time) #create directories to save pred_new os.chdir(csv_path) #tide gauge directory tg_name = tg.split('.csv')[0] try: os.makedirs(tg_name) os.chdir(tg_name) #cd to it after creating it except FileExistsError: #directory already exists os.chdir(tg_name) #predictor directory pred_name = pf try: os.makedirs(pred_name) os.chdir(pred_name) #cd to it after creating it except FileExistsError: #directory already exists os.chdir(pred_name) #time for saving file print("saving as csv") yr_name = py.split('_')[-1] save_name = '_'.join([tg_name, pred_name, yr_name])\ + ".csv" pred_new.to_csv(save_name) #return to the predictor directory os.chdir(nc_path[pf]) #run script extract_data(delta= 1)
b3bbf241bc800e52afdc11e43aaefdfc56e938a5
c9acc2aebb8ba0aa285c38a75e920073923670f9
/tianyayingshi/src/sentiment/snownlp/normal/__init__.py
a4231e2b2e06164135a4b518fa72a3893c6fa28d
[]
no_license
taojy123/BySM
4821d92b73c8d9d2bb38356e2d0fc1893fd8497a
6988d7b33085f2d4ae8e4773f494ff18190318a5
refs/heads/master
2020-04-05T14:35:58.520256
2016-09-06T07:18:55
2016-09-06T07:18:55
27,417,148
0
0
null
null
null
null
UTF-8
Python
false
false
1,128
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import re import codecs from . import zh from . import pinyin stop_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'stop-words_chinese_1_zh.txt') pinyin_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pinyin.txt') stop = set() fr = codecs.open(stop_path, 'r', 'utf-8') for word in fr: stop.add(word.strip()) fr.close() pin = pinyin.PinYin(pinyin_path) def filter_stop(words): return list(filter(lambda x: x not in stop, words)) def zh2hans(sent): return zh.transfer(sent) def get_sentences(doc): line_break = re.compile('[\r\n]') delimiter = re.compile('[,。?!;]') sentences = [] for line in line_break.split(doc): line = line.strip() if not line: continue for sent in delimiter.split(line): sent = sent.strip() if not sent: continue sentences.append(sent) return sentences def get_pinyin(sentence): return pin.get(sentence)
0899c62e03a18f7bd82ee50637c5476d2490ef39
641ff82ed3dd80c20dcfffd44fd183350eb11836
/PyFunceble/core/__init__.py
f80a742a6bb57d657e7de163d8e97846d22b84da
[ "MIT" ]
permissive
cargo12/PyFunceble
3d338b0b6d8b4dbff30090dc694c54457cf1e65b
d6033601909e88495f5b102e45ee7d5a48dbe46a
refs/heads/master
2021-02-05T08:20:34.229758
2020-02-02T20:27:42
2020-02-02T20:27:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,194
py
""" The tool to check the availability or syntax of domains, IPv4, IPv6 or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Provides the core interfaces. Author: Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/master/ Project homepage: https://pyfunceble.github.io/ License: :: MIT License Copyright (c) 2017, 2018, 2019, 2020 Nissar Chababy 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, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .api import APICore as API from .cli import CLICore as CLI from .file import FileCore as File from .multiprocess import MultiprocessCore as Multiprocess from .simple import SimpleCore as Simple
79aa3263058778bc9d862d6e547ac28284d77218
e073d58c135e4b27b861946a6e84aa5b2e0ae7f2
/datastructure/double_pointer/ReverseString.py
aaa9f0f09a857e1e8fb20514e15fbc435fca632e
[]
no_license
yinhuax/leet_code
c4bdb69752d441af0a3bcc0745e1133423f60a7b
9acba92695c06406f12f997a720bfe1deb9464a8
refs/heads/master
2023-07-25T02:44:59.476954
2021-09-04T09:07:06
2021-09-04T09:07:06
386,097,065
0
0
null
null
null
null
UTF-8
Python
false
false
1,187
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Mike # @Contact : [email protected] # @Time : 2021/1/25 23:25 # @File : ReverseString.py from typing import List """ 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/array-and-string/cacxi/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 """ class ReverseString(object): def __init__(self): pass def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ i, j = len(s) - 1, 0 while i > j: s[i], s[j] = s[j], s[i] i -= 1 j += 1 if __name__ == '__main__': print(ReverseString().reverseString(["h", "e", "l", "l", "o"]))
e8885c3766b279cf42727722c441609806e35ff1
c988a8856d2d3fb7771417b4c7810e528a197d2b
/restaurant py.py
6e141d75b64eaccbbd3ff3c4f0ded38e66fb6987
[]
no_license
arunekuriakose/MyPython
0c8a9161fef20bf77f7ba31149ec4ba0fa79b0bd
19f44819612a8490d430bafec0616f68ce109776
refs/heads/master
2022-01-20T07:56:48.505226
2019-07-22T06:26:52
2019-07-22T06:26:52
198,158,499
0
0
null
null
null
null
UTF-8
Python
false
false
2,350
py
def Ref(): x=random.randint(10908,500876) randomRef=str(x) rand.set(randomRef) if (Fries.get()==""): CoFries=0 else: CoFries=float(Fries.get()) if (Noodles.get()==""): CoNoodles=0 else: CoNoodles=float(Noodles.get()) if (Soup.get()==""): CoSoup=0 else: CoSoup=float(Soup.get()) if (Burger.get()==""): CoBurger=0 else: CoBurger=float(Burger.get()) if (Sandwich.get()==""): CoSandwich=0 else: CoSandwich=float(Sandwich.get()) if (Drinks.get()==""): CoD=0 else: CoD=float(Drinks.get()) CostofFries =CoFries * 140 CostofDrinks=CoD * 65 CostofNoodles = CoNoodles* 90 CostofSoup = CoSoup * 140 CostBurger = CoBurger* 260 CostSandwich=CoSandwich * 300 CostofMeal= "Rs", str('%.2f' % (CostofFries+CostofDrinks+CostofNoodles+CostofSoup+CostBurger+CostSandwich)) PayTax=((CostofFries+CostofDrinks+CostofNoodles+CostofSoup+CostBurger+CostSandwich) * 0.2) TotalCost=(CostofFries+CostofDrinks+CostofNoodles+CostofSoup+CostBurger+CostSandwich) Ser_Charge= ((CostofFries+CostofDrinks+CostofNoodles+CostofSoup+CostBurger+CostSandwich)/99) Service = "Rs", str ('%.2f' % Ser_Charge) OverAllCost ="Rs", str ('%.2f' % (PayTax+TotalCost+Ser_Charge)) PaidTax= "Rs", str ('%.2f' % PayTax) Service_Charge.set(Service) Cost.set(CostofMeal) Tax.set(PaidTax) SubTotal.set(CostofMeal) Total.set(OverAllCost) def qExit(): root.destroy() def Reset(): rand.set("") Fries.set("") Noodles.set("") Soup.set("") SubTotal.set("") Total.set("") Service_Charge.set("") Drinks.set("") Tax.set("") Cost.set("") Burger.set("") Sandwich.set("") """ #====================================Restaraunt Info 1=========================================================== rand = StringVar() Fries=StringVar() Noodles=StringVar() Soup=StringVar() SubTotal=StringVar() Total=StringVar() Service_Charge=StringVar() Drinks=StringVar() Tax=StringVar() Cost=StringVar() Burger=StringVar() Sandwich=StringVar() root.mainloop() """
1f2eee3ef88caeef047310f977d6057f636ec90e
7f60d03d7326a2768ffb103b7d635260ff2dedd7
/system/base/expat/actions.py
a7eacf5e14263dd9faa35ca3c6069079237186fe
[]
no_license
haneefmubarak/repository
76875e098338143852eac230d5232f4a7b3c68bd
158351499450f7f638722667ffcb00940b773b66
refs/heads/master
2021-01-17T17:51:22.358811
2014-03-24T19:41:12
2014-03-24T19:41:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
377
py
#!/usr/bin/python # Created For SolusOS from pisi.actionsapi import shelltools, get, autotools, pisitools def setup(): autotools.configure ("--prefix=/usr --disable-static") def build(): autotools.make () def install(): autotools.rawInstall ("DESTDIR=%s" % get.installDIR()) # Add the documentation pisitools.dodoc ("doc/*.css", "doc/*.png", "doc/*.html")
e308b90da0b42e67a6db5c0131db265389a98250
567ecf4ea5afbd7eb3003f7e14e00c7b9289b9c6
/ax/utils/common/tests/test_testutils.py
c86a3a1a299a37c71651c9a594ba17df307b3a09
[ "MIT" ]
permissive
danielrjiang/Ax
f55ef168a59381b5a03c6d51bc394f6c72ed0f39
43014b28683b3037b5c7307869cb9b75ca31ffb6
refs/heads/master
2023-03-31T12:19:47.118558
2019-12-02T16:47:39
2019-12-02T16:49:36
225,493,047
0
0
MIT
2019-12-03T00:09:52
2019-12-03T00:09:51
null
UTF-8
Python
false
false
2,254
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import io import sys from ax.utils.common.testutils import TestCase def _f(): e = RuntimeError("Test") raise e def _g(): _f() # Lines along the path are matched too class TestTestUtils(TestCase): def test_raises_on(self): with self.assertRaisesOn(RuntimeError, "raise e"): _f() # Check that we fail if the source line is not what we expect with self.assertRaisesRegex(Exception, "was not found in the traceback"): with self.assertRaisesOn(RuntimeError, 'raise Exception("Test")'): _f() # Check that the exception passes through if it's not the one we meant to catch with self.assertRaisesRegex(RuntimeError, "Test"): with self.assertRaisesOn(AssertionError, "raise e"): _f() with self.assertRaisesOn( RuntimeError, "_f() # Lines along the path are matched too" ): _g() # Use this as a context manager to get the position of an error with self.assertRaisesOn(RuntimeError) as cm: _f() self.assertEqual(cm.filename, __file__) self.assertEqual(cm.lineno, 12) def test_silence_warning_normal(self): new_stderr = io.StringIO() old_err = sys.stderr try: sys.stderr = new_stderr with self.silence_stderr(): print("A message", file=sys.stderr) finally: sys.stderr = old_err self.assertEqual(new_stderr.getvalue(), "") def test_silence_warning(self): new_stderr = io.StringIO() old_err = sys.stderr with self.assertRaises(AssertionError): try: sys.stderr = new_stderr with self.silence_stderr(): print("A message", file=sys.stderr) raise AssertionError() finally: sys.stderr = old_err self.assertTrue(new_stderr.getvalue().startswith("A message\n")) def test_fail_deprecated(self): self.assertEqual(1, 1) with self.assertRaises(RuntimeError): self.assertEquals(1, 1)
da4ba7f8e2bcf8f18cb88f0f33133479d6f3c350
eb4119dda59e44fc418be51a33c11e5d32f29fd7
/src/ssadmin/migrations/0002_auto_20161111_1238.py
ad31ef9ffd6873708716cc6852985b4aad46eac4
[ "MIT" ]
permissive
daimon99/ssadmin
4ee08f4d56bc8f27099f1e1caa72a3ca8b8b1b57
9a1470712bdca5b0db17895d4c8215555d6b1b04
refs/heads/master
2020-12-24T12:29:49.070231
2016-11-11T13:26:34
2016-11-11T13:26:34
72,992,364
0
0
null
null
null
null
UTF-8
Python
false
false
2,003
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-11 12:38 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('ssadmin', '0001_initial'), ] operations = [ migrations.CreateModel( name='flow_add_history', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('port', models.IntegerField()), ], ), migrations.CreateModel( name='flow_update_history', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='FlowUseHistory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('port', models.IntegerField()), ('limit', models.BigIntegerField()), ('remaining', models.BigIntegerField()), ('used', models.BigIntegerField()), ], ), migrations.CreateModel( name='password_change_history', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.RemoveField( model_name='ssuser', name='balance', ), migrations.RemoveField( model_name='ssuser', name='up_user', ), migrations.AddField( model_name='flow_add_history', name='ssuser', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ssadmin.SSUser'), ), ]
227540b49e24fa651eda6583afdce8ca0f953d93
5f40f48e6cb75278a746ca28aad8a2b7826678e1
/passstatement.py
8fc41cc66f823174c771125f712b8de48b40cb44
[]
no_license
Techsrijan/kipmbsc
b5be3fe8a2693980f65e19b50b92036fbdfc85c0
d766b4ec36bf7e4a31dbc388ddbcfb471d5c0700
refs/heads/main
2023-08-15T12:38:34.628808
2021-10-19T11:14:39
2021-10-19T11:14:39
406,292,625
0
18
null
null
null
null
UTF-8
Python
false
false
79
py
a=int(input("Enter First number")) if a%2==0: pass else: print("odd no")
900b433e08f9ae6f6f1b68885f1633a7b7c47e66
3c0104047e826816f7e945434b718b33b7499629
/sandbox/MP/fun.py
b08d78db857ed97a1ecad1a1fa8188ba5907855b
[]
no_license
larsendt/xhab-spot
8080d6a213e407fb75cc246702e1dbbcd94eae57
bd2bdfcb0414f8ed0cbb3be95a5ba13d9baf6b4b
refs/heads/master
2021-01-19T11:02:49.250480
2014-05-06T17:29:30
2014-05-06T17:29:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
379
py
import lcddriver import time lcd=lcddriver.lcd() lcd.lcd_print_char('X',2, 7) lcd.lcd_print_char('-',2, 8) lcd.lcd_print_char('H',2, 9) lcd.lcd_print_char('A',2, 10) lcd.lcd_print_char('B',2, 11) lcd.lcd_print_char('2',3, 7) lcd.lcd_print_char('0',3, 8) lcd.lcd_print_char('1',3, 9) lcd.lcd_print_char('4',3, 10) lcd.lcd_print_char('!',3, 11) lcd.lcd_cursor_placement(4,19)
7c85e2f48091128f9c0e0f945e742828363d5869
9bcba8f3162eacea872dbadc9990a164f945f70a
/Packages/comandos/node_npm_install.py
5c253d9822e9ba351460bbabafd8c34996310aff
[]
no_license
programadorsito/Packages
a4cb568219dbc10a69e15a2832ef52d19eb83061
af748327f128ed90bb146dc12bb53b76ccb609fd
refs/heads/master
2021-01-10T04:41:38.676159
2016-04-06T07:52:45
2016-04-06T07:52:45
55,560,324
0
0
null
null
null
null
UTF-8
Python
false
false
375
py
import sublime, os, platform import sublime_plugin import subprocess import webbrowser from subprocess import PIPE, Popen class NodeNpmInstallCommand(sublime_plugin.TextCommand): def run(self, edit): window=sublime.active_window() view=window.active_view() view.run_command("ejecutar_comando", {"comando":'npm install -g @package'})
3a5508257210a35777bad02559099ad92ffc4f1b
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/fHwaeLLz2vN9XzFft_7.py
a8758fac440826142925a996fcd7c906f5aadd50
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
56
py
def yen_to_usd(yen): return round(yen / 107.5, 2)
7bfd8413070f139e0e99eef5b6377b13be31dc6e
61f8733c7e25610d04eaccd59db28aa65897f846
/dot blog/Built-in functions/sorted.py
27db07a9356814e0017a97afc970ff639092283a
[]
no_license
masato932/study-python
7e0b271bb5c8663fad1709e260e19ecb2d8d4681
03bedc5ec7a9ecb3bafb6ba99bce15ccd4ae29cc
refs/heads/main
2023-03-27T13:32:05.605593
2021-03-21T10:45:16
2021-03-21T10:45:16
342,985,998
0
0
null
null
null
null
UTF-8
Python
false
false
791
py
# x = [5, 8, 4, 1, 3, 2, 7, 6] # y = sorted(x) # print(y) # x = [5, 8, 4, 1, 3, 2, 7, 6] # y = sorted(x, reverse=True) # print(y) # x = (5, 8, 4, 1, 3, 2, 7, 6) # y = sorted(x, reverse=True) # print(y) # x = {'b':20, 'c':30, 'a':9, 'd':10} # y = sorted(x, reverse=True) # print(y) # x = {'b':20, 'c':20, 'a':40, 'd':10} # y = sorted(x.values(), reverse=True) # print(y) # x = {'b':20, 'c':30, 'a':40, 'd':10} # y = sorted(x.items(), reverse=True) # print(y) # x = 'cbazdtRMLNKII' # y = sorted(x, reverse=True) # print(y) # x = ['apple', 'Apple', 'amazon', 'Amazon', 'windows', 'Windows', 'walmart', 'Walmart'] # y = sorted(x, reverse=True) # print(y) x = ['apple', 'Apple', 'amazon', 'Amazon', 'windows', 'Windows', 'walmart', 'Walmart'] y = sorted(x, key=len, reverse=True) print(y)
233fa2bcb9aae97ffdfc0577a2228c2fc29f90a1
eb5e319b2e7052a007b645d200f810241a2dd07c
/backend/wma_22660/urls.py
8ad2fe276469de71f56428bdadfbabe0cd4afacc
[]
no_license
crowdbotics-apps/wma-22660
206bb7c670385a65528a9b14f0783f354397a1a6
da2a25ff937242eed2b2ab3dbec4fd690b3db0a1
refs/heads/master
2023-01-14T07:49:09.570432
2020-11-16T04:23:15
2020-11-16T04:23:15
313,189,080
0
0
null
null
null
null
UTF-8
Python
false
false
2,578
py
"""wma_22660 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from allauth.account.views import confirm_email from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ path("", include("home.urls")), path("accounts/", include("allauth.urls")), path("api/v1/", include("home.api.v1.urls")), path("admin/", admin.site.urls), path("users/", include("users.urls", namespace="users")), path("rest-auth/", include("rest_auth.urls")), # Override email confirm to use allauth's HTML view instead of rest_auth's API view path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email), path("rest-auth/registration/", include("rest_auth.registration.urls")), path("api/v1/", include("task.api.v1.urls")), path("task/", include("task.urls")), path("api/v1/", include("task_profile.api.v1.urls")), path("task_profile/", include("task_profile.urls")), path("api/v1/", include("tasker_business.api.v1.urls")), path("tasker_business/", include("tasker_business.urls")), path("api/v1/", include("location.api.v1.urls")), path("location/", include("location.urls")), path("api/v1/", include("wallet.api.v1.urls")), path("wallet/", include("wallet.urls")), path("api/v1/", include("task_category.api.v1.urls")), path("task_category/", include("task_category.urls")), path("home/", include("home.urls")), ] admin.site.site_header = "WMA" admin.site.site_title = "WMA Admin Portal" admin.site.index_title = "WMA Admin" # swagger api_info = openapi.Info( title="WMA API", default_version="v1", description="API documentation for WMA App", ) schema_view = get_schema_view( api_info, public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns += [ path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs") ]
396dc83dbf9b54aab58f727e635fc95ce30d5f00
4216a5fbdea90359abd5597589a12876f02d002c
/2016-March/python/set_container.py
8494241f9abdcf75a9b8283ae792f865c21e94eb
[]
no_license
tammachari/big-datascience
014bfa26f37bb99e933a645aec0b2e8b2f74061f
6e4d2cfffca73297e1284ea6c1498fb08637f641
refs/heads/master
2020-07-04T15:11:32.579219
2018-10-07T05:11:48
2018-10-07T05:11:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
413
py
#set container creation and access animals = set(['cat', 'dog']) 'cat' in animals 'fish' in animals animals.add('fish') 'fish' in animals len(animals) animals.add('cat') len(animals) animals.remove('cat') len(animals) #loops animals = set(['cat', 'dog', 'fish']) for animal in animals: print animal for idx, animal in enumerate(animals): print '#%d: %s' % (idx + 1, animal)
d9b209934784709b9de630de941350bbf9018263
0961bff0127e0a71114876a0f6f76b92df720764
/backend/manage.py
5069bf5715b1bf4a8d5782467697d723a35b0dd6
[]
no_license
crowdbotics-apps/ecommerce-22008
43e1744ff0c0a4b32aef2f0aa62dfe9d934d40f7
fc4e5cb3b2e40cdc7fbbbc5cf096020f62b8a4a8
refs/heads/master
2022-12-31T05:04:15.885597
2020-10-27T10:45:11
2020-10-27T10:45:11
307,666,388
0
0
null
null
null
null
UTF-8
Python
false
false
635
py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce_22008.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
28f42444746b3833cfc883c113d802f3661801af
115c43a6b9bb198d07003684692a37fc97bb626d
/tests/test_utils.py
7d33d71bed289559ec953c02022d218261e27e48
[ "BSD-3-Clause" ]
permissive
rodriguez-facundo/pyecore
c79fe8a900fdf4cd8b6ccad6253c2bd57f96ac9f
22b67ad8799594f8f44fd8bee497583d4f12ed63
refs/heads/master
2020-05-17T11:43:04.227860
2019-04-19T15:27:00
2019-04-19T15:27:00
183,692,299
0
0
BSD-3-Clause
2019-07-08T20:14:49
2019-04-26T20:48:15
Python
UTF-8
Python
false
false
3,133
py
import pytest from pyecore.ecore import * from pyecore.utils import DynamicEPackage, original_issubclass, alias import builtins @pytest.fixture(scope='module') def simplemm(): A = EClass('A') B = EClass('B') Root = EClass('Root') pack = EPackage('pack', nsURI='http://pack/1.0', nsPrefix='pack') pack.eClassifiers.extend([Root, A, B]) return pack @pytest.fixture(scope='module') def complexmm(): A = EClass('A') B = EClass('B') Root = EClass('Root') pack = EPackage('pack', nsURI='http://pack/1.0', nsPrefix='pack') pack.eClassifiers.extend([Root, A, B]) innerpackage = EPackage('inner', nsURI='http://inner', nsPrefix='inner') C = EClass('C') D = EClass('D') innerpackage.eClassifiers.extend([C, D]) pack.eSubpackages.append(innerpackage) return pack def test_dynamic_access_eclasses(simplemm): SimpleMM = DynamicEPackage(simplemm) assert SimpleMM.A assert SimpleMM.B def test_dynamic_access_innerpackage(complexmm): ComplexMM = DynamicEPackage(complexmm) assert ComplexMM.A assert ComplexMM.B assert ComplexMM.inner.C assert ComplexMM.inner.D def test_dynamic_addition_eclasses(complexmm): ComplexMM = DynamicEPackage(complexmm) E = EClass('E') complexmm.eClassifiers.append(E) assert ComplexMM.E F = EClass('F') complexmm.eSubpackages[0].eClassifiers.append(F) assert ComplexMM.inner.F G = EClass('G') H = EClass('H') complexmm.eClassifiers.extend([G, H]) assert ComplexMM.G assert ComplexMM.H def test_dynamic_removal_eclasses(complexmm): ComplexMM = DynamicEPackage(complexmm) assert ComplexMM.Root complexmm.eClassifiers.remove(ComplexMM.Root) with pytest.raises(AttributeError): ComplexMM.Root assert ComplexMM.A complexmm.eClassifiers[0].delete() with pytest.raises(AttributeError): ComplexMM.A def test_original_issubclass(): issub = builtins.issubclass with original_issubclass(): assert builtins.issubclass is not issub assert builtins.issubclass is issub def test_alias_function_static(): @EMetaclass class A(object): from_ = EAttribute(eType=EString) a = A() assert getattr(a, 'from', -1) == -1 alias('from', A.from_, eclass=A) assert getattr(a, 'from') is None @EMetaclass class B(object): as_ = EAttribute(eType=EInt) b = B() assert getattr(b, 'as', -1) == -1 alias('as', B.as_) assert getattr(b, 'as') is 0 b.as_ = 4 assert b.as_ == 4 assert getattr(b, 'as') == 4 def test_alias_function_dynamic(): A = EClass('A') A.eStructuralFeatures.append(EAttribute('from', EString)) a = A() assert getattr(a, 'from_', -1) == -1 alias('from_', A.findEStructuralFeature('from'), eclass=A) assert a.from_ is None B = EClass('B') B.eStructuralFeatures.append(EAttribute('as', EInt)) b = B() assert getattr(b, 'as_', -1) == -1 alias('as_', B.findEStructuralFeature('as')) assert b.as_ is 0 b.as_ = 4 assert b.as_ == 4 assert getattr(b, 'as') == 4
120081f44e650aa2d0ef6c904ee981f9df20e1cc
6123df2ee8648c7977c99564197f7834c7ea83a1
/DataPreprocessing/MobileDataProcess/Preprocess/processingData.py
f2fe7483745581748bd67caf8d397e825e24d04d
[]
no_license
JiaqiuWang/DataStatusPrediction
2b66a24f992df64d93506f54e041d93282213c6e
9eb3eff99f0f804857f3a1d70227f75c91a8258d
refs/heads/master
2020-05-21T21:34:28.571549
2017-08-17T08:44:12
2017-08-17T08:44:12
84,649,900
0
0
null
null
null
null
UTF-8
Python
false
false
13,202
py
""" 读入csv数据,到内存中 """ import time import pandas as pd import DataPreprocessing.NaturalLanProcess as dpt4 # 引入自然语言处理 import pymongo import codecs import re class ProcessingData: # 类公有变量 nan_list = [] # 存放空值行的队列 # 构造函数 def __init__(self, file_path, db_name, collection_name, ip_address, flag_insert, encode): self.file_path = file_path self.db_name = db_name self.collection_name = collection_name self.ip_address = ip_address # 全局变量-连接指定IP地址的数据库 self.client = pymongo.MongoClient(self.ip_address, 27017) # 获取数据库 self.db = self.client.get_database(self.db_name) # 获取集合 self.collection = self.db.get_collection(self.collection_name) # 是否插入数据库标识位 self.flag_insert = flag_insert self.encode = encode # 析构函数 def __del__(self): class_name = self.__class__.__name__ self.client.close() print(class_name, "Destroy.") # --------------------------------------------------------------------------------------- # 读取文本中每行的节点队 def read_file(self): data = pd.read_csv(self.file_path, encoding=self.encode) # 读取数据 print("data:") count = 0 # 计数器 # 逐个元素判断是否为空值,将空值行,放入一个队列中 for i in range(len(data)): print("i:", i) user_id = "" # 用户ID service_id = "" # 服务ID date_time = "" # 格式化时间 time_stamp = "" # 时间戳 activity = "" # 行为 content = "" # 内容 key_words = [] # 内容关键词(自然语言做的分词) title_text = "" # 标题 star_badge = "" # 奖励 row = data.iloc[i] # 数据元组 # print("type:", type(row), "row: ", row) for j in data.columns: j = str(j) # if str(data.iloc[i][j]) == "nan": # print("空值", row, j, "element:", data.iloc[i][j]) # self.nan_list.append(row) # continue element = str(data.iloc[i][j]) if j == "用户ID": user_id = element print(j, ":", user_id) if j == "服务ID": service_id = element print(j, ":", service_id) if j == "时间": if str(data.iloc[i][j]) == "nan": # print("空值", row, j, "element:", data.iloc[i][j]) self.nan_list.append(row) continue element = element.replace("Z", "") date_time = element print(j, ":", date_time) # 将格式化时间转换成时间戳10位 # 1中间过程,一般都需要将字符串转化为时间数组 timeArray = time.strptime(element, "%Y-%m-%d %H:%M:%S") # 2将"2011-09-28 10:00:00"转化为时间戳 timestamp = int(time.mktime(timeArray)) print("timestamp:", timestamp, " type:", type(timestamp)) time_stamp = timestamp if j == "行为": activity = element print(j, ":", activity) if j == "内容": content = element print(j, ":", content) temp_keywords = dpt4.main(element) # keywords是一个List结构 print("keywords:", temp_keywords) key_words += temp_keywords if j == "title": title_text = element print(j, ":", title_text) temp_keywords = dpt4.main(title_text) # keywords是一个List结构 print("keywords:", temp_keywords) key_words += temp_keywords if j == "标记": star_badge = element print(j, ":", star_badge) temp_keywords = dpt4.main(star_badge) # keywords是一个List结构 print("keywords:", temp_keywords) key_words += temp_keywords # end if # 调用Switch结构 # 输出每一行的input_list _id = self.get_next_counter() insert_text = {"uid": self.collection_name, "用户ID": user_id, "服务ID": service_id, "时间": date_time, "timestamp": time_stamp, "activity": activity, "内容": content, "keywords": key_words, "title": title_text, "标记": star_badge, "_id": _id} print("row_input_list:", insert_text) count += 1 # 插入数据库 if self.flag_insert == "1": self.input_database(insert_text) print() # end for, 判断是不是有空值的元组 print("The number of log:", count) if self.nan_list: for var_nan in self.nan_list: print("NaN row:", var_nan) print("空值的个数:", len(self.nan_list)) # --------------------------------------------------------------------------------------- """ 数据库操作 """ # 写入MongoDB数据库 def input_database(self, input_tuple): # 添加单条记录到集合中 self.collection.insert(input_tuple) # 批量插入数据 def input_many_database(self, input_tuple): # 添加单条记录到集合中 self.collection.insert_many(input_tuple) # 查询所有collections def find_all(self): # 查询所有 for data in self.collection.find(): print(data) print("总记录数为:", self.collection.find().count()) self.client.close() # 更新数据库 def update_database(self): self.collection.update({"_id": 1, "pPer_id": "p2"}, {"$set": {"pName": "卫国"}}) self.client.close() # 查找一个文档 def find_one(self): for u in self.collection.find({"_id": 1}): print("符合条件的记录(_id:1 ): ", u) self.client.close() # 删除一个数据 def delete_one(self): for u in self.collection.find({"_id": 1}): print("符合条件的记录(_id:1 ): ", u) self.collection.remove({"_id": 1}) self.client.close() # 删除所有数据 def delete_all(self): self.collection.remove() self.client.close() # ---------------------------------------------------------------------------------------------------------- """ 读取txt文本文件到内存中 """ def read_lines_from_file(self, filename): counter = 0 # 计数器 f = codecs.open(filename, "r+", self.encode) # 读取中文 line = f.readline() # 读取一行 # line.replace('\r\n', ' ') line = line.replace("  ", "") line.strip() # 删除字符串左右的空格 first_datetime = "" first_timestamp = "" second_datetime = "" second_timestamp = "" last_time = 0 app_name = "" app_nic_name = "" while line: line = line.strip('\r\n') # 去掉每个字符的'\r\n' print("line:", line) line = f.readline() elements = line.split(",") print("element_size:", len(elements)) if len(elements) < 3: continue for i in range(len(elements)): print("i:", i, ", elements[i]:", elements[i]) if (i == 0) and elements[i]: first_datetime = elements[i] first_timestamp = self.transform_datetime(first_datetime) if (i == 1) and elements[i]: second_datetime = elements[i] second_timestamp = self.transform_datetime(second_datetime) if (i == 2) and elements[i]: app_name = elements[i] if (i == 3) and elements[i]: app_nic_name = elements[i] if first_timestamp and second_timestamp: last_time = second_timestamp - first_timestamp _id = self.get_next_counter() input_text = {"_id": _id, "uid": self.collection_name, "first_datetime": first_datetime, "first_timestamp": first_timestamp, "second_datetime": second_datetime, "second_timestamp": second_timestamp, "app_name": app_name, "app_nickname": app_nic_name, "last_time": last_time } print("input_text:", input_text) counter += 1 # 插入数据库 if self.flag_insert == "1": self.input_database(input_text) print("The number of log:", counter) f.close() # ---------------------------------------------------------------------------------------------------------- """ 获取自增1的_id,默认与初始参数相同的数据库 """ def get_next_counter(self): collection = self.db.get_collection("counters") _id_obj = collection.find_and_modify(query={'_id': self.collection_name}, update={"$inc": {"no": +1}}, upsert=False, full_response=True, new=True) # print("_id_obj:", _id_obj) _id = _id_obj.get("value").get("no") # print("_id:", _id) return _id # ---------------------------------------------------------------------------------------------------------- """ 将标准时间转换成时间戳 """ @classmethod def transform_datetime(cls, date_time): # 转化成时间戳 matchObj = re.search(r'(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})', date_time, re.M | re.I) if matchObj: date_time = matchObj.group(0) timeArray = time.strptime(date_time, "%Y-%m-%d %H:%M:%S") # 2将"2011-09-28 10:00:00"转化为时间戳 timestamp = int(time.mktime(timeArray)) return timestamp else: return None # ---------------------------------------------------------------------------------------------------------- """ switch功能 """ class Switch(object): def __init__(self, value): self.value = value self.fall = False def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: # changed for self.fall = True return True else: return False # The following example is pretty much the exact use-case of a dictionary, # but is included for its simplicity. Note that you can include statements # in each suite. v = 'ten3' for case in Switch(v): if case('one'): print("1") break if case('two'): print("2") break if case('ten'): print('10') break if case('eleven'): print("11") break if case(): # default, could also just omit condition or 'if True' print("something else!") # No need to break here, it'll stop anyway # ---------------------------------------------------------------------------------------------------------- """ 注意修改:UID UID UID UID UID UID UID UID UID UID UID UID UID UID UID UID UID UID UID UID """ def main_operation(): """Part1: 初始化参数""" file_path = 'data/评论.csv' # 读取文件路径和文件名 ip_address = "127.0.0.1" # 主机IP地址 db_name = "predictionData" # 数据库名字 collection_name = "MU47" # 集合的名字 flag_insert = "1" # 1代表写入数据库, 其他代表不输入数据库 file_name = "../data/log47.txt" encode = 'utf-8' # 编码方式 dp1 = ProcessingData(file_path, db_name, collection_name, ip_address, flag_insert, encode) dp1.read_lines_from_file(file_name) if __name__ == "__main__": # 记录算法运行开始时间 start_time = time.clock() # main_operation main_operation() # 记录算法运行结束时间 end_time = time.clock() print("Running time: %s Seconds" % (end_time - start_time)) # 输出运行时间(包括最后输出所有结果)
bf0a7bbad9c3796914a9d05b6776b5e21c20e70f
86137c14ebfef6f3cf0bc3af92f443f93f48ae7d
/dvrl/main_domain_adaptation.py
d5406d61435059b04741b615df7b809730994c99
[ "Apache-2.0" ]
permissive
jisungyoon/google-research
692a51a91df36022dba9eb9e439fb69c1b6035e7
8e4097cc7c9b7cc57d85fd2f57d0684e737c3fc3
refs/heads/master
2020-08-23T14:37:43.706773
2019-10-21T18:20:41
2019-10-21T18:24:43
216,641,313
1
0
Apache-2.0
2019-10-21T18:46:49
2019-10-21T18:46:49
null
UTF-8
Python
false
false
5,391
py
# coding=utf-8 # Copyright 2019 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Main experiment for domain adaptation. Main experiment of a domain adaptation application using "Data Valuation using Reinforcement Learning (DVRL)" """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import lightgbm import numpy as np import tensorflow as tf from dvrl import data_loading from dvrl import dvrl from dvrl import dvrl_metrics def main(args): """Main function of DVRL for domain adaptation experiment. Args: args: train_no, valid_no, normalization, network parameters """ # Data loading # The number of training and validation samples dict_no = dict() dict_no['source'] = args.train_no dict_no['valid'] = args.valid_no # Setting and target store type setting = 'train-on-rest' target_store_type = 'B' # Network parameters parameters = dict() parameters['hidden_dim'] = args.hidden_dim parameters['comb_dim'] = args.comb_dim parameters['iterations'] = args.iterations parameters['activation'] = tf.nn.tanh parameters['layer_number'] = args.layer_number parameters['batch_size'] = args.batch_size parameters['learning_rate'] = args.learning_rate # Checkpoint file name checkpoint_file_name = args.checkpoint_file_name # Data loading data_loading.load_rossmann_data(dict_no, setting, target_store_type) print('Finished data loading.') # Data preprocessing # Normalization methods: 'minmax' or 'standard' normalization = args.normalization # Extracts features and labels. Then, normalizes features x_source, y_source, x_valid, y_valid, x_target, y_target, _ = \ data_loading.preprocess_data(normalization, 'source.csv', 'valid.csv', 'target.csv') print('Finished data preprocess.') # Run DVRL # Resets the graph tf.reset_default_graph() problem = 'regression' # Predictor model definition pred_model = lightgbm.LGBMRegressor() # Flags for using stochastic gradient descent / pre-trained model flags = {'sgd': False, 'pretrain': False} # Initializes DVRL dvrl_class = dvrl.Dvrl(x_source, y_source, x_valid, y_valid, problem, pred_model, parameters, checkpoint_file_name, flags) # Trains DVRL dvrl_class.train_dvrl('rmspe') print('Finished dvrl training.') # Outputs # Data valuation dve_out = dvrl_class.data_valuator(x_source, y_source) print('Finished date valuation.') # Evaluations # Evaluation model eval_model = lightgbm.LGBMRegressor() # DVRL-weighted learning dvrl_perf = dvrl_metrics.learn_with_dvrl(dve_out, eval_model, x_source, y_source, x_valid, y_valid, x_target, y_target, 'rmspe') # Baseline prediction performance (treat all training samples equally) base_perf = dvrl_metrics.learn_with_baseline(eval_model, x_source, y_source, x_target, y_target, 'rmspe') print('Finish evaluation.') print('DVRL learning performance: ' + str(np.round(dvrl_perf, 4))) print('Baseline performance: ' + str(np.round(base_perf, 4))) return if __name__ == '__main__': # Inputs for the main function parser = argparse.ArgumentParser() parser.add_argument( '--normalization', help='data normalization method', default='minmax', type=str) parser.add_argument( '--train_no', help='number of training samples', default=667027, type=int) parser.add_argument( '--valid_no', help='number of validation samples', default=8443, type=int) parser.add_argument( '--hidden_dim', help='dimensions of hidden states', default=100, type=int) parser.add_argument( '--comb_dim', help='dimensions of hidden states after combinding with prediction diff', default=10, type=int) parser.add_argument( '--layer_number', help='number of network layers', default=5, type=int) parser.add_argument( '--iterations', help='number of iterations', default=1000, type=int) parser.add_argument( '--batch_size', help='number of batch size for RL', default=50000, type=int) parser.add_argument( '--learning_rate', help='learning rates for RL', default=0.001, type=float) parser.add_argument( '--checkpoint_file_name', help='file name for saving and loading the trained model', default='./tmp/model.ckpt', type=str) args_in = parser.parse_args() # Calls main function main(args_in)
f45993035beacee89af6f73781deef6bd4d70eb8
81d0bfe1262008587ddf5ac12ae034d6922b9747
/.history/Smart/admin/routes_20201121105136.py
f9e3333b2e15b0050561af767aad2f7d7b4be435
[]
no_license
elvinyeka/Smart-Mobile
525fffac14b8c460e85002bbf154bf54b4a341fe
a32f557306ae1bfe3ae01f5a8beef93727cfbc47
refs/heads/master
2023-06-09T09:52:18.446572
2021-07-06T11:35:34
2021-07-06T11:35:34
313,988,596
2
0
null
null
null
null
UTF-8
Python
false
false
2,102
py
from flask import render_template,session,request,redirect, flash, url_for, flash from Smart import app, db, bcrypt from .forms import RegistrationForm, LoginForm from .models import User @app.route('/') def index(): return render_template('index.html', title='home') @app.route('/admin') def admin(): return render_template('admin/index.html', title='Admin Page') @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): hash_password = bcrypt.generate_password_hash(form.password.data) user = User(name=form.name.data, username=form.username.data, email=form.email.data, password=hash_password) db.session.add(user) db.session.commit() flash(f'{form.name.data} Qeydiyyat uğurlu oldu', 'success') return redirect(url_for('login')) return render_template('admin/register.html', form=form,title='Registeration Page') @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm(request.form) if request.method == 'POST' and form.validate(): user = User.query.filter_by(email = form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): session['email'] = form.email.data flash(f'Xoş gəldiniz {form.email.data} Girişiniz uğurlu oldu.', 'success') return redirect(request.args.get('next') or url_for('admin')) else: flash('Şifrə səhvdir. Yenidən cəhd edin', 'danger') return render_template('admin/login.html',form=form, title='login') @app.route('/contact') def contact(): return render_template('contact.html', title='contact') @app.route('/compare') def compare(): return render_template('compare.html', title='compare') @app.route('/single-product') def single_product(): return render_template('single-product.html',title='product') @app.route('/brand-product') def brand_product(): return render_template('brand-product.html',title='brand')
0168af70be6863c8cd4c801977ae32fd19efe41d
c210b5111fbe0bafda441bdc8fa12cd8eb77a20b
/vframe/src/settings/app_cfg.py
dd37e85e67f9ddcd6cec0a47ec42e1e41b7b9db6
[ "MIT" ]
permissive
noticeable/vframe_workshop
345fc214bf6f755042a5f8470d002fd9a244c1a7
7adf822a0687b5621b04bf790d2c9e77f3371284
refs/heads/master
2020-04-28T19:59:32.826001
2019-01-29T20:28:20
2019-01-29T20:28:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,390
py
from os.path import join import logging from src.settings import types from src.utils import click_utils # ----------------------------------------------------------------------------- # Enun lists used for custom Click Params # ----------------------------------------------------------------------------- LogLevelVar = click_utils.ParamVar(types.LogLevel) # # data_store DATA_STORE_WORKSHOP = 'data_store_workshop' DIR_MODELS = join(DATA_STORE_WORKSHOP,'models') # Frameworks DIR_MODELS_CAFFE = join(DIR_MODELS,'caffe') # ----------------------------------------------------------------------------- # click chair settings # ----------------------------------------------------------------------------- DIR_COMMANDS_WORKSHOP = 'commands/workshop' # ----------------------------------------------------------------------------- # Logging options exposed for custom click Params # ----------------------------------------------------------------------------- LOGGER_NAME = 'vframe' LOGLEVELS = { types.LogLevel.DEBUG: logging.DEBUG, types.LogLevel.INFO: logging.INFO, types.LogLevel.WARN: logging.WARN, types.LogLevel.ERROR: logging.ERROR, types.LogLevel.CRITICAL: logging.CRITICAL } LOGLEVEL_OPT_DEFAULT = types.LogLevel.DEBUG.name LOGFILE_FORMAT = "%(log_color)s%(levelname)-8s%(reset)s %(cyan)s%(filename)s:%(lineno)s:%(bold_cyan)s%(funcName)s() %(reset)s%(message)s"
ae043d66c4ad98c31097144126a59624e7599423
958b0471c52eff93415216cdd1a2b2ad3947a89b
/lmnet/tests/lmnet_tests/test_data_augmentor.py
a63bb7720eca4a9421a42ea46cf7657298739225
[ "Apache-2.0" ]
permissive
fumihwh/blueoil
4deb606e334b8456e7ace41e3f091ad6dc41afb6
acb5a270f201f34fe5a5b27a4b395d9c3a838b27
refs/heads/master
2020-04-01T22:29:27.525697
2018-10-18T09:23:37
2018-10-18T09:23:37
153,711,347
1
0
null
2018-10-19T01:49:02
2018-10-19T01:49:02
null
UTF-8
Python
false
false
8,978
py
# -*- coding: utf-8 -*- # Copyright 2018 The Blueoil 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= import time import numpy as np import PIL.Image import PIL.ImageDraw import pytest from lmnet.datasets.lm_things_on_a_table import LmThingsOnATable from lmnet.pre_processor import ( ResizeWithGtBoxes ) from lmnet.data_processor import ( Sequence ) from lmnet.data_augmentor import ( Blur, Brightness, Color, Contrast, Crop, FlipLeftRight, FlipTopBottom, Hue, Pad, RandomPatchCut, SSDRandomCrop, iou, _crop_boxes, ) # Apply reset_default_graph() and set_test_environment() in conftest.py to all tests in this file. pytestmark = pytest.mark.usefixtures("reset_default_graph", "set_test_environment") # TODO(wakisaka): All the tests are only checking if they are just working. IS_DEBUG = False def _show_images_with_boxes(images, labels): if not IS_DEBUG: return """show image and bounding box for debug""" images_min = abs(images.min()) images_max = (images + images_min).max() images = (images + images_min) * (255 / images_max) images = (images).astype(np.uint8) for image, label in zip(images, labels): image = PIL.Image.fromarray(image) draw = PIL.ImageDraw.Draw(image) for box in label: xy = [box[0], box[1], box[0] + box[2], box[1] + box[3]] draw.rectangle(xy) image.show() time.sleep(0.5) def _show_image(image): if not IS_DEBUG: return """show image for debug""" image = PIL.Image.fromarray(image) image.show() time.sleep(1) def _image(): image = PIL.Image.open("tests/fixtures/sample_images/cat.jpg") return np.array(image) def test_sequence(): batch_size = 3 image_size = [256, 512] augmentor = Sequence([ FlipLeftRight(is_bounding_box=True), FlipTopBottom(is_bounding_box=True), SSDRandomCrop(), ]) dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=augmentor, ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_blur(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=Blur((0, 1)), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_brightness(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=Brightness(), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_color(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=Color((0.0, 2.0)), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_contrast(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=Contrast((0.0, 2.0)), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_crop(): img = _image() augmentor = Crop(size=(100, 200), resize=(200, 200)) result = augmentor(**{'image': img}) image = result['image'] _show_image(image) assert image.shape[0] == 100 assert image.shape[1] == 200 assert image.shape[2] == 3 def test_filp_left_right(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=FlipLeftRight(is_bounding_box=True), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_filp_top_bottom(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=FlipTopBottom(is_bounding_box=True), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_hue(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=Hue((-10, 10)), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) def test_pad(): img = _image() assert img.shape[0] == 480 assert img.shape[1] == 480 assert img.shape[2] == 3 augmentor = Pad(100) result = augmentor(**{'image': img}) image = result['image'] _show_image(image) assert image.shape[0] == 680 assert image.shape[1] == 680 assert image.shape[2] == 3 augmentor = Pad((40, 30)) result = augmentor(**{'image': img}) image = result['image'] _show_image(image) assert image.shape[0] == 480 + 30 * 2 assert image.shape[1] == 480 + 40 * 2 assert image.shape[2] == 3 def test_random_patch_cut(): img = _image() assert img.shape[0] == 480 assert img.shape[1] == 480 assert img.shape[2] == 3 augmentor = RandomPatchCut(num_patch=10, max_size=10, square=True) result = augmentor(**{'image': img}) image = result['image'] assert image.shape[0] == 480 assert image.shape[1] == 480 assert image.shape[2] == 3 _show_image(image) def test_ssd_random_crop(): batch_size = 3 image_size = [256, 512] dataset = LmThingsOnATable( batch_size=batch_size, pre_processor=ResizeWithGtBoxes(image_size), augmentor=SSDRandomCrop(), ) for _ in range(5): images, labels = dataset.feed() _show_images_with_boxes(images, labels) assert np.all(labels[:, :, 2] <= 512) assert np.all(labels[:, :, 3] <= 256) def test_iou(): box = np.array([ 10, 20, 80, 60, ]) boxes = np.array([ [10, 20, 80, 60, ], [10, 20, 40, 30, ], [50, 50, 80, 60, ], ]) expected = np.array([ 1, 0.25, (40 * 30) / (80 * 60 * 2 - 40 * 30), ]) ious = iou(boxes, box) assert np.allclose(ious, expected) def test_crop_boxes(): boxes = np.array([ [10, 20, 80, 60, 100], ]) # boxes include crop crop_rect = [30, 30, 5, 5] expected = np.array([ [0, 0, 5, 5, 100], ]) cropped = _crop_boxes(boxes, crop_rect) assert np.allclose(cropped, expected) crop_rect = [80, 30, 100, 100] expected = np.array([ [0, 0, 10, 50, 100], ]) cropped = _crop_boxes(boxes, crop_rect) assert np.allclose(cropped, expected) # crop include box crop_rect = [5, 5, 100, 100] expected = np.array([ [5, 15, 80, 60, 100], ]) cropped = _crop_boxes(boxes, crop_rect) assert np.allclose(cropped, expected) # overlap crop_rect = [10, 20, 80, 60] expected = np.array([ [0, 0, 80, 60, 100], ]) cropped = _crop_boxes(boxes, crop_rect) assert np.allclose(cropped, expected) # When crop rect is external boxes, raise error. crop_rect = [0, 0, 5, 100] with pytest.raises(AssertionError): cropped = _crop_boxes(boxes, crop_rect) crop_rect = [0, 0, 100, 5] with pytest.raises(AssertionError): cropped = _crop_boxes(boxes, crop_rect) crop_rect = [95, 0, 5, 5] with pytest.raises(AssertionError): cropped = _crop_boxes(boxes, crop_rect) crop_rect = [30, 85, 5, 5] with pytest.raises(AssertionError): cropped = _crop_boxes(boxes, crop_rect) if __name__ == '__main__': test_sequence() test_blur() test_brightness() test_color() test_contrast() test_crop() test_filp_left_right() test_filp_top_bottom() test_hue() test_pad() test_random_patch_cut() test_ssd_random_crop() test_iou() test_crop_boxes()
054bdccad3c52d4833d907224a62b801552fde4e
4d892dc51e2dda0fcce246ac608fc4e0ce98c52b
/FirstStepsInPython/Fundamentals/Exercice/Lists Basics/01. Invert Values.py
94485830d6ba2cdf174235b9aeba6a63d40b5521
[ "MIT" ]
permissive
inovei6un/SoftUni-Studies-1
510088ce65e2907c2755a15e427fd156909157f0
3837c2ea0cd782d3f79353e61945c08a53cd4a95
refs/heads/main
2023-08-14T16:44:15.823962
2021-10-03T17:30:48
2021-10-03T17:30:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
199
py
str_nums = input() some_list = str_nums.split(input()) result = [] for el in some_list: result.append((int(el) * -1)) print(result) # INPUT 1 # 1 2 -3 -3 5 # INPUT 2 # -4 0 2 57 -101 # INPUT END
43a0237619f79a2a4564f43277d436d2cd99c135
ea24104edfb276f4db780638fcc8e6cf7f7dceb8
/setup.py
fb5b5953ca8e448d8bacb6b06e3d65a80473b5a4
[ "MIT" ]
permissive
jmoujaes/dpaste
6e195dc7f3a53ae2850aa4615514876597b6564d
27d608e5da4b045ea112823ec8d271add42fd89d
refs/heads/master
2021-01-25T14:33:06.648359
2018-03-03T19:57:51
2018-03-03T19:57:51
123,708,048
0
0
MIT
2018-03-03T16:08:54
2018-03-03T16:08:54
null
UTF-8
Python
false
false
1,704
py
#!/usr/bin/env python from sys import exit from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox errno = tox.cmdline(self.test_args) exit(errno) long_description = u'\n\n'.join(( open('README.rst').read(), open('CHANGELOG').read() )) setup( name='dpaste', version='2.13', description='dpaste is a Django based pastebin. It\'s intended to run ' 'separately but its also possible to be installed into an ' 'existing Django project like a regular app.', long_description=long_description, author='Martin Mahner', author_email='[email protected]', url='https://github.com/bartTC/dpaste/', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Framework :: Django', ], packages=find_packages(), package_data={ 'dpaste': ['static/*.*', 'templates/*.*'], 'docs': ['*'], }, include_package_data=True, install_requires=[ 'django>=1.8,<2.0', 'pygments>=1.6', ], tests_require=[ 'tox>=1.6.1' ], cmdclass={ 'test': Tox }, )
de0326f435ffc96d79b974c8650e7f1ab6479947
cdbb5bb7cbf188f8773a3a1425c2043f0af8a423
/Attributes_and_Methods/gym_04E/project/gym.py
a1be11e84e7dfcd76026101a0fc75df9d371e352
[ "MIT" ]
permissive
MihailMarkovski/Python-OOP-2020
72ac4f150907a6fa2fb93393cfcd2f36656e7256
f0ac610bb758c2882e452684c8d7f533fcc33fe4
refs/heads/main
2023-01-31T18:24:53.184269
2020-12-17T09:39:01
2020-12-17T09:39:01
321,456,100
0
0
null
null
null
null
UTF-8
Python
false
false
2,507
py
# from Attributes_and_Methods.gym_04E.project.equipment import Equipment # from Attributes_and_Methods.gym_04E.project.exercise_plan import ExercisePlan # from Attributes_and_Methods.gym_04E.project.subscription import Subscription # from Attributes_and_Methods.gym_04E.project.customer import Customer # from Attributes_and_Methods.gym_04E.project.trainer import Trainer class Gym: def __init__(self): self.customers = [] self.trainers = [] self.equipment = [] self.plans = [] self.subscriptions = [] def add_customer(self, customer): if customer not in self.customers: self.customers.append(customer) def add_trainer(self, trainer): if trainer not in self.trainers: self.trainers.append(trainer) def add_equipment(self, equipment): if equipment not in self.equipment: self.equipment.append(equipment) def add_plan(self, plan): if plan not in self.plans: self.plans.append(plan) def add_subscription(self, subscription): if subscription not in self.subscriptions: self.subscriptions.append(subscription) def subscription_info(self, subscription_id: int): subscription = [s for s in self.subscriptions if s.id == subscription_id][0] customer = [c for c in self.customers if subscription.customer_id == c.id][0] trainer = [t for t in self.trainers if t.id == subscription.trainer_id][0] plan = [p for p in self.plans if trainer.id == p.trainer_id][0] equipment = [e for e in self.equipment if e.id == plan.equipment_id][0] result = f'{subscription}\n{customer}\n{trainer}\n{equipment}\n{plan}' return result # all_objects = [subscription, customer, trainer, equipment, plan] # result = '' # for idx, obj in enumerate(all_objects): # if idx == len(all_objects) - 1: # result += f'{obj}' # else: # result += f'{obj}\n' # return result # customer = Customer("John", "Maple Street", "[email protected]") # equipment = Equipment("Treadmill") # trainer = Trainer("Peter") # subscription = Subscription("14.05.2020", 1, 1, 1) # plan = ExercisePlan(1, 1, 20) # # gym = Gym() # # gym.add_customer(customer) # gym.add_equipment(equipment) # gym.add_trainer(trainer) # gym.add_plan(plan) # gym.add_subscription(subscription) # # print(Customer.get_next_id()) # # print(gym.subscription_info(1))
4d7318f876ee78f727ddf1f05e561ff13553e914
26b66f2d11b28bc5f859021e011d3b5d1e1ed8ee
/old-stuff-for-reference/nightjar-base/nightjar-src/python-src/nightjar/entry/central_configurator/process.py
e72b185f4fca333d13e8607059cce6c75f42dbc8
[ "MIT" ]
permissive
groboclown/nightjar-mesh
8f12c8b90a0b4dd5b6f871123e2d3d0c89001db2
3655307b4a0ad00a0f18db835b3a0d04cb8e9615
refs/heads/master
2022-12-13T13:04:02.096054
2020-08-12T23:30:30
2020-08-12T23:30:30
207,360,091
3
1
MIT
2022-12-13T11:13:30
2019-09-09T16:59:02
Python
UTF-8
Python
false
false
1,516
py
""" Process templates. """ from typing import Iterable from ...backend.api.deployment_map import AbcDeploymentMap from .content_gen import ( generate_content, ) from .input_data_gen import load_service_color_data, load_namespace_data from ...backend.api.data_store import ( AbcDataStoreBackend, CollectorDataStore, ConfigurationReaderDataStore, ConfigurationWriterDataStore, ) from ...protect import RouteProtection def process_templates( backend: AbcDataStoreBackend, deployment_map: AbcDeploymentMap, namespaces: Iterable[str], namespace_protections: Iterable[RouteProtection], service_protection: RouteProtection, ) -> None: """ Process all the namespace and service/color templates into the envoy proxy content. This can potentially take up a lot of memory. It's performing a trade-off of minimizing service calls for memory. """ namespace_data = load_namespace_data(deployment_map, namespaces, namespace_protections) service_color_data = load_service_color_data(deployment_map, namespaces, service_protection) with CollectorDataStore(backend) as collector: with ConfigurationReaderDataStore(backend) as config_reader: with ConfigurationWriterDataStore(backend) as config_writer: generate_content( collector, config_reader, config_writer, namespace_data, service_color_data, namespace_protections, )
645e37cf5ff4fd8435a05cd045daca41fdaa7ae3
cd0068a04a706aa902947d5f1233a7f07bec150c
/Python/function_practice/p1.py
d6bf1b18c9618753d720d712b4fdb9a3dd78f7ea
[]
no_license
eLtronicsVilla/Miscellaneous
b0c579347faad12cee64408c2a112b33b38a6201
e83f44af985faad93336c1307aeae8694905c3e3
refs/heads/master
2021-11-28T04:22:08.278055
2021-08-14T19:53:29
2021-08-14T19:53:29
161,993,103
0
0
null
2021-08-14T19:53:29
2018-12-16T11:11:10
C++
UTF-8
Python
false
false
462
py
#def myfuncs(a,b,c=0,d=0): # return sum((a,b,c,d))*0.05 #print(myfuncs(1,2,3,4)) #def myfunc(*args): # return sum(args) * 0.05 #print(myfunc(10,20,30,40)) ''' def myfunc(*args): for item in args: print(item) print(myfunc(20,30,40,50,60)) ''' def myfunc(**kwargs): print(kwargs) if 'fruit' in kwargs: print('My fruit of choice is {}'.format(kwargs['fruit'])) else: print('I did not find any fruit here') myfunc(fruit='apple',veggie = 'lettuce')
263693b9ffd66f4793977371b94af2600527b9f6
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2411/60610/283132.py
096e0adccc969e68233bd1a8ca9eecae10d02711
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
502
py
num=int(input()) mid=[] for i in range(num): mid.append(list(map(int,input().split(",")))); count=0; if(mid[0][0]!=mid[1][0]): k0=(mid[0][1]-mid[1][1])/(mid[0][0]-mid[1][0]); for i in range(2,len(mid)): k1=(mid[0][1]-mid[i][1])/(mid[0][0]-mid[i][0]); if(k0!=k1): count=1; break; else: for i in range(2, len(mid)): if(mid[i][0]!=mid[0][0]): count=1; break; if(count==0): print("True"); else: print("False");
4d10a36856ffec58d86503f620e0a58e88e7c2fe
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/tree-big-6789.py
90e343f098ce06b0514dea3ebf740dba02f06941
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
23,289
py
# Binary-search trees class TreeNode(object): value:int = 0 left:"TreeNode" = None right:"TreeNode" = None def insert(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode(x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode(x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode2(object): value:int = 0 value2:int = 0 left:"TreeNode2" = None left2:"TreeNode2" = None right:"TreeNode2" = None right2:"TreeNode2" = None def insert(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode3(object): value:int = 0 value2:int = 0 value3:int = 0 left:"TreeNode3" = None left2:"TreeNode3" = None left3:"TreeNode3" = None right:"TreeNode3" = None right2:"TreeNode3" = None right3:"TreeNode3" = None def insert(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode4(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 left:"TreeNode4" = None left2:"TreeNode4" = None left3:"TreeNode4" = None left4:"TreeNode4" = None right:"TreeNode4" = None right2:"TreeNode4" = None right3:"TreeNode4" = None right4:"TreeNode4" = None def insert(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode5(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 value5:int = 0 left:"TreeNode5" = None left2:"TreeNode5" = None left3:"TreeNode5" = None left4:"TreeNode5" = None left5:"TreeNode5" = None right:"TreeNode5" = None right2:"TreeNode5" = None right3:"TreeNode5" = None right4:"TreeNode5" = None right5:"TreeNode5" = None def insert(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode5", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode5", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class Tree(object): root:TreeNode = None size:int = 0 def insert(self:"Tree", x:int) -> object: if self.root is None: self.root = makeNode(x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree2(object): root:TreeNode2 = None root2:TreeNode2 = None size:int = 0 size2:int = 0 def insert(self:"Tree2", x:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree2", x:int, x2:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree2", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree2", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree3(object): root:TreeNode3 = None root2:TreeNode3 = None root3:TreeNode3 = None size:int = 0 size2:int = 0 size3:int = 0 def insert(self:"Tree3", x:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree3", x:int, x2:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree3", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree3", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree3", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree3", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree4(object): root:TreeNode4 = None root2:TreeNode4 = None root3:TreeNode4 = None root4:TreeNode4 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 def insert(self:"Tree4", x:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree4", x:int, x2:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree4", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree4", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree4", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree4", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree5(object): root:TreeNode5 = None root2:TreeNode5 = None root3:TreeNode5 = None root4:TreeNode5 = None root5:TreeNode5 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 size5:$ID = 0 def insert(self:"Tree5", x:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree5", x:int, x2:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree5", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree5", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree5", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree5", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def makeNode(x: int) -> TreeNode: b:TreeNode = None b = TreeNode() b.value = x return b def makeNode2(x: int, x2: int) -> TreeNode2: b:TreeNode2 = None b2:TreeNode2 = None b = TreeNode2() b.value = x return b def makeNode3(x: int, x2: int, x3: int) -> TreeNode3: b:TreeNode3 = None b2:TreeNode3 = None b3:TreeNode3 = None b = TreeNode3() b.value = x return b def makeNode4(x: int, x2: int, x3: int, x4: int) -> TreeNode4: b:TreeNode4 = None b2:TreeNode4 = None b3:TreeNode4 = None b4:TreeNode4 = None b = TreeNode4() b.value = x return b def makeNode5(x: int, x2: int, x3: int, x4: int, x5: int) -> TreeNode5: b:TreeNode5 = None b2:TreeNode5 = None b3:TreeNode5 = None b4:TreeNode5 = None b5:TreeNode5 = None b = TreeNode5() b.value = x return b # Input parameters n:int = 100 n2:int = 100 n3:int = 100 n4:int = 100 n5:int = 100 c:int = 4 c2:int = 4 c3:int = 4 c4:int = 4 c5:int = 4 # Data t:Tree = None t2:Tree = None t3:Tree = None t4:Tree = None t5:Tree = None i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 k:int = 37813 k2:int = 37813 k3:int = 37813 k4:int = 37813 k5:int = 37813 # Crunch t = Tree() while i < n: t.insert(k) k = (k * 37813) % 37831 if i % c != 0: t.insert(i) i = i + 1 print(t.size) for i in [4, 8, 15, 16, 23, 42]: if t.contains(i): print(i)
b4d8cc119dc15ee7f84c18bfe77ddafd53fcd24d
645050387b6d65986490045696a23b99484bfb07
/week-15/course_management_system/course_management_system/lectures/urls.py
073ec02e00ef9c31e4bba1d08f76b5ca8b9c2033
[]
no_license
ViktorBarzin/HackBulgaria-Python
73fd36299afd3fcbf5601c4a932780252db90001
7bae4528ded8ca3a33bb12c2a67123cc621d8b8f
refs/heads/master
2020-12-25T15:08:23.345972
2017-06-07T01:19:36
2017-06-07T01:19:36
67,701,776
0
1
null
null
null
null
UTF-8
Python
false
false
303
py
from django.conf.urls import url, include from django.contrib import admin from course_management_system.lectures import views urlpatterns = [ url(r'new/$', views.create_lecture), url(r'edit/(?P<lecture_id>[0-9]+)', views.edit_lecture), url(r'(?P<lecture_id>[0-9]+)', views.show_lecture) ]
958567a0c2066e663ecf210b5eb2888606d39a19
b6aa9768dbac327943e0220df1c56ce38adc6de1
/127_word-ladder.py
9008bcaef54814bc92db08d538d8421e074a2a43
[]
no_license
Khrystynka/LeetCodeProblems
f86e4c1e46f70f874924de137ec5efb2f2518766
917bd000c2a055dfa2633440a61ca4ae2b665fe3
refs/heads/master
2021-03-17T00:51:10.102494
2020-09-28T06:31:03
2020-09-28T06:31:03
246,954,162
0
0
null
null
null
null
UTF-8
Python
false
false
1,128
py
# Problem Title: Word Ladder from collections import defaultdict, deque class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ L = len(beginWord) d = defaultdict(list) for word in wordList: for i in range(L): d[word[:i]+'*'+word[i+1:]] += [word] visited = set(beginWord) queu = deque([(beginWord, 1)]) next_words = [] while queu: (word, level) = queu.popleft() if word == endWord: return level next_words = [] for i in range(L): intermid_word = word[:i]+'*'+word[i+1:] next_words += (d[intermid_word]) d[intermid_word] = [] # print next_words, word for word in next_words: if word not in visited: visited.add(word) queu.append((word, level+1)) # print queu return 0
59483881abc2212735a5b71e41b3c45117bcc327
c34308d9e283d3689baeade246b69dad13eea0c1
/cn/wensi/file/osDemo.py
02f4fc3e0382fce16dfa0eab109f7456893718ad
[]
no_license
michaelChen07/studyPython
d19fe5762cfbccdff17248d7d5574939296d3954
11a2d9dd0b730cad464393deaf733b4a0903401f
refs/heads/master
2021-01-19T00:20:27.347088
2017-05-13T08:43:44
2017-05-13T08:43:44
73,004,133
1
1
null
null
null
null
UTF-8
Python
false
false
749
py
#encoding=utf-8 import os #获取当前工作目录 print os.getcwd() #更改当前目录 os.chdir(r"D:\workspace\PycharmProjects\studyPython\cn\wensi\practice") print os.getcwd() #当前工作目录下的文件 print os.listdir(os.getcwd()) #指定目录下的文件 print os.listdir(r"D:\test") #返回当前目录 print os.curdir #创建指定级数的目录 def create_multiple_dir(dir_path,depth,dir_name): try: os.chdir(dir_path) except Exception,e: return -1 for i in range(depth): os.mkdir(dir_name+str(i)) os.chdir(dir_name+str(i)) with open(dir_name+str(i)+".txt","w") as fp: fp.write(dir_name+str(i)) return 0 print create_multiple_dir("e:\\test",5,"gloryroad")
90940afeec0ca4c91817d149ca18e38d03b93486
2781ffdb7dd131c43d5777d33ee002643c839c28
/DataCamp Practice/Supervised Learning With Scikit Learn/03-fine-tuning-your-model/01-metrics-for-classification.py
0a3ce40f7a5a2daa30330b0f25b204d57c35c593
[]
no_license
AbuBakkar32/Python-Essential-Practice
b5e820d2e27e557b04848b5ec63dd78ae5b554c4
8659cf5652441d32476dfe1a8d90184a9ae92b3b
refs/heads/master
2022-11-13T23:07:16.829075
2020-06-27T18:46:52
2020-06-27T18:46:52
275,432,093
4
0
null
null
null
null
UTF-8
Python
false
false
2,799
py
''' Metrics for classification In Chapter 1, you evaluated the performance of your k-NN classifier based on its accuracy. However, as Andy discussed, accuracy is not always an informative metric. In this exercise, you will dive more deeply into evaluating the performance of binary classifiers by computing a confusion matrix and generating a classification report. You may have noticed in the video that the classification report consisted of three rows, and an additional support column. The support gives the number of samples of the true response that lie in that class - so in the video example, the support was the number of Republicans or Democrats in the test set on which the classification report was computed. The precision, recall, and f1-score columns, then, gave the respective metrics for that particular class. Here, you'll work with the PIMA Indians dataset obtained from the UCI Machine Learning Repository. The goal is to predict whether or not a given female patient will contract diabetes based on features such as BMI, age, and number of pregnancies. Therefore, it is a binary classification problem. A target value of 0 indicates that the patient does not have diabetes, while a value of 1 indicates that the patient does have diabetes. As in Chapters 1 and 2, the dataset has been preprocessed to deal with missing values. The dataset has been loaded into a DataFrame df and the feature and target variable arrays X and y have been created for you. In addition, sklearn.model_selection.train_test_split and sklearn.neighbors.KNeighborsClassifier have already been imported. Your job is to train a k-NN classifier to the data and evaluate its performance by generating a confusion matrix and classification report. INSTRUCTIONS 100XP Import classification_report and confusion_matrix from sklearn.metrics. Create training and testing sets with 40% of the data used for testing. Use a random state of 42. Instantiate a k-NN classifier with 6 neighbors, fit it to the training data, and predict the labels of the test set. Compute and print the confusion matrix and classification report using the confusion_matrix() and classification_report() functions. ''' # Import necessary modules from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix # Create training and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4,random_state=42) # Instantiate a k-NN classifier: knn knn = KNeighborsClassifier(n_neighbors=6) # Fit the classifier to the training data knn.fit(X_train, y_train) # Predict the labels of the test data: y_pred y_pred = knn.predict(X_test) # Generate the confusion matrix and classification report print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred))
734fb833af5a331b634893629da08f294d27f864
3953a4cf5dee0667c08e1fe1250a3067090e3f24
/mural/config/urls.py
cdebfe9af3dc61e698750dae88078701104bb273
[]
no_license
DigitalGizmo/msm_mural_project
41960242c84050ee578da90afabcb7f9bc1923df
5566a2b6f7445dc53d8aaf96cf7d24236fd5ed96
refs/heads/master
2020-03-07T11:04:49.633149
2019-02-13T18:10:44
2019-02-13T18:10:44
127,447,243
0
0
null
null
null
null
UTF-8
Python
false
false
1,082
py
"""mural URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path from django.views.generic import TemplateView from panels import views urlpatterns = [ # path('', TemplateView.as_view(template_name="index.html")), path('', views.PanelListView.as_view(), name='index.html'), path('panels/', include('panels.urls', namespace='panels')), path('pops/', include('pops.urls', namespace='pops')), path('admin/', admin.site.urls), ]
bd186ab2c1021b3099528a8ac1bc3737cae828d1
7738e950c103fb23b48d5e004eddcf108ea71fa1
/Cursoemvideo/Mundo1/exercise022.py
b16615322ed621abdab7671f36f3fe2f08ba44ed
[]
no_license
pedrottoni/Studies-Python
c9bdbaf4b4aaa209bf32aa93d6ee4814a0a39c53
f195bcb4c6868689ec0cf05c34cd4d5a6c7b3ea1
refs/heads/master
2021-09-26T05:23:02.398552
2020-02-12T04:48:23
2020-02-12T04:48:23
203,452,221
0
0
null
2021-09-22T18:21:51
2019-08-20T20:48:07
Python
UTF-8
Python
false
false
899
py
''' Crie um programa que leia o nome completo de uma pessoa e mostre: - O nome com todas as letras maiúsculas e minúsculas. - Quantas letras ao todo(sem considerar espaços). - Quantas letras tem o primeiro nome. ''' name = str(input("Digite seu nome completo: ")) name_up = name.upper() name_low = name.lower() name_len_replace = len(name.replace(" ", "")) name_len_count = len(name) - name.count(" ") name_firstname_len_split = name.split() name_firstname_len_find = name.find(" ") print( f"Seu nome em letras maiúsculas é: {name_up}\nSeu nome em letras minúsculas é: {name_low}\nSeu nome sem espaçoes possui {name_len_replace} letras, usando o replace\nSeu nome sem espaçoes possui {name_len_count} letras, usando o count\nSeu primeiro nome possui {len(name_firstname_len_split[0])} letras, usando o split\nSeu primeiro nome possui {name_firstname_len_find} letras, usando o find" )
61669adcae1d0c4f10ad7a70ae68b63f3087dc03
060ce17de7b5cdbd5f7064d1fceb4ded17a23649
/fn_exchange_online/fn_exchange_online/components/exchange_online_move_message_to_folder.py
61835d74a362f1bd66d5ce67124b3febefa59fb1
[ "MIT" ]
permissive
ibmresilient/resilient-community-apps
74bbd770062a22801cef585d4415c29cbb4d34e2
6878c78b94eeca407998a41ce8db2cc00f2b6758
refs/heads/main
2023-06-26T20:47:15.059297
2023-06-23T16:33:58
2023-06-23T16:33:58
101,410,006
81
107
MIT
2023-03-29T20:40:31
2017-08-25T14:07:33
Python
UTF-8
Python
false
false
4,764
py
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. # -*- coding: utf-8 -*- # pragma pylint: disable=unused-argument, no-self-use """Function implementation""" import logging from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError from resilient_lib import validate_fields, RequestsCommon, ResultPayload from fn_exchange_online.lib.ms_graph_helper import MSGraphHelper, MAX_RETRIES_TOTAL, MAX_RETRIES_BACKOFF_FACTOR, MAX_BATCHED_REQUESTS CONFIG_DATA_SECTION = 'fn_exchange_online' LOG = logging.getLogger(__name__) class FunctionComponent(ResilientComponent): """Component that implements Resilient function 'exchange_online_move_message_to_folder""" def load_options(self, opts): """ Get app.config parameters and validate them. """ self.opts = opts self.options = opts.get(CONFIG_DATA_SECTION, {}) required_fields = ["microsoft_graph_token_url", "microsoft_graph_url", "tenant_id", "client_id", "client_secret", "max_messages", "max_users"] validate_fields(required_fields, self.options) def __init__(self, opts): """constructor provides access to the configuration options""" super(FunctionComponent, self).__init__(opts) self.load_options(opts) @handler("reload") def _reload(self, event, opts): """Configuration options have changed, save new values""" self.load_options(opts) @function("exchange_online_move_message_to_folder") def _exchange_online_move_message_to_folder_function(self, event, *args, **kwargs): """Function: This function will move an Exchange Online message to the specified folder in the users mailbox.""" try: # Initialize the results payload rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs) # Validate fields validate_fields(['exo_email_address', 'exo_messages_id', 'exo_destination_mailfolder_id'], kwargs) # Get the function parameters: email_address = kwargs.get("exo_email_address") # text message_id = kwargs.get("exo_messages_id") # text mailfolders_id = kwargs.get("exo_mailfolders_id") # text destination_id = kwargs.get("exo_destination_mailfolder_id") # text LOG.info(u"exo_email_address: %s", email_address) LOG.info(u"exo_messages_id: %s", message_id) LOG.info(u"exo_mailfolders_id: %s", mailfolders_id) LOG.info(u"exo_destination_id: %s", destination_id) yield StatusMessage(u"Starting move message for email address: {} to mail folder {}".format(email_address, destination_id)) # Get the MS Graph helper class MS_graph_helper = MSGraphHelper(self.options.get("microsoft_graph_token_url"), self.options.get("microsoft_graph_url"), self.options.get("tenant_id"), self.options.get("client_id"), self.options.get("client_secret"), self.options.get("max_messages"), self.options.get("max_users"), self.options.get("max_retries_total", MAX_RETRIES_TOTAL), self.options.get("max_retries_backoff_factor", MAX_RETRIES_BACKOFF_FACTOR), self.options.get("max_batched_requests", MAX_BATCHED_REQUESTS), RequestsCommon(self.opts, self.options).get_proxies()) # Call MS Graph API to get the user profile response = MS_graph_helper.move_message(email_address, mailfolders_id, message_id, destination_id) # If message was deleted a 201 code is returned. if response.status_code == 201: success = True new_message_id = response.json().get('id') new_web_link = response.json().get('webLink') response_json = {'new_message_id': new_message_id, 'new_web_link': new_web_link} else: success = False response_json = response.json() results = rp.done(success, response_json) yield StatusMessage(u"Returning delete results for email address: {}".format(email_address)) # Produce a FunctionResult with the results yield FunctionResult(results) except Exception as err: LOG.error(err) yield FunctionError(err)
ecb1ca3c00d1db51f7132f218cca24f0f9be33af
52b5773617a1b972a905de4d692540d26ff74926
/.history/clouds_20200703185904.py
374d79f890156c551577f693e911a567575c824b
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
772
py
def jumpingClouds(c): i = 0 jumps = 0 lastCloud = len(c)-1 while i < lastCloud: # if i+1 == lastCloud: # jumps +=1 # i+=1 # elif c[i+2] == 0: # jumps +=1 # i = i + 2 # else: # jumps +=1 # i +=1 # print(jumps) if : print('here') jumps +=1 i =i+2 print('c---->',c[i],'i-->',i,'jumps',jumps) elif c[i+1] == 0: print('here2') jumps +=1 i +=1 print('c---->',c[i],'i-->',i,'jumps',jumps) print(jumps) jumpingClouds([0, 0, 0, 1, 0, 0])
2f4e1ef39e3ec5bc5cfffda8e34746dd2360f9c5
7c3116ca951c1c989fcc6cd673993ce6b1d4be5a
/modules/Eventlog/lv1_os_win_event_logs_registry_handling.py
caa2035832bf5a5e3814ef9a90fbad9d90f81c82
[ "Apache-2.0" ]
permissive
Kimwonkyung/carpe
c8c619c29350d6edc464dbd9ba85aa3b7f847b8a
58a8bf7a7fc86a07867890c2ce15c7271bbe8e78
refs/heads/master
2022-12-15T13:51:47.678875
2020-09-11T05:25:43
2020-09-11T05:25:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,234
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os, sys, re from datetime import datetime from utility import database class Registry_Handling_Information: par_id = '' case_id = '' evd_id = '' task = '' time = '' registry_path = '' registry_value_name = '' old_value = '' new_value = '' user_sid = '' event_id = '' source = '' event_id_description = '' def EVENTLOGREGISTRYHANDLING(configuration): #db = database.Database() #db.open() registry_list = [] registry_count = 0 query = r"SELECT data, event_id, time_created, source, user_sid FROM lv1_os_win_evt_total where event_id like '4657' and source like '%Security.evtx%'" #result_query = db.execute_query_mul(query) result_query = configuration.cursor.execute_query_mul(query) for result_data in result_query: registry_handling_information = Registry_Handling_Information() try: if result_data[1] == '4657': registry_list.append(registry_handling_information) registry_list[registry_count].task = 'Modified' registry_list[registry_count].event_id = result_data[1] registry_list[registry_count].time = result_data[2] registry_list[registry_count].source = result_data[3] registry_list[registry_count].user_sid = result_data[4] registry_list[registry_count].event_id_description = 'A registry value was modified' if 'SubjectUserName' in result_data[0]: dataInside = r"SubjectUserName\">(.*)<" m = re.search(dataInside, result_data[0]) registry_list[registry_count].user = m.group(1) if 'ObjectName' in result_data[0]: dataInside = r"ObjectName\">(.*)<" m = re.search(dataInside, result_data[0]) registry_list[registry_count].registry_path = m.group(1) if 'ObjectValueName' in result_data[0]: dataInside = r"ObjectValueName\">(.*)<" m = re.search(dataInside, result_data[0]) registry_list[registry_count].registry_value_name = m.group(1) if r"OldValue\" " in result_data[0]: registry_list[registry_count].old_value = ' ' if r"OldValue\">" in result_data[0]: dataInside = r"OldValue\">(.*)<" m = re.search(dataInside, result_data[0]) registry_list[registry_count].old_value = m.group(1) registry_list[registry_count].registry_value_name = m.group(1) if r"NewValue\" " in result_data[0]: registry_list[registry_count].new_value = ' ' if 'NewValue' in result_data[0]: dataInside = r"NewValue\">(.*)<" m = re.search(dataInside, result_data[0]) registry_list[registry_count].new_value = m.group(1) registry_count = registry_count + 1 except: print("EVENT LOG REGISTRY HANDLING ERROR") #db.close() return registry_list
6ca185cdacbd5790f016b989c1bb9f28545a4402
bd185738ea6a74d1e76d9fc9d8cbc59f94990842
/helpline/migrations/0012_hotdesk_user.py
9440e21db2fcbf2a8064e17c7132565c9c0001c3
[ "BSD-2-Clause" ]
permissive
aondiaye/myhelpline
c4ad9e812b3a13c6c3c8bc65028a3d3567fd6a98
d72120ee31b6713cbaec79f299f5ee8bcb7ea429
refs/heads/master
2020-12-22T05:32:59.576519
2019-10-29T08:52:55
2019-10-29T08:52:55
236,683,448
1
0
NOASSERTION
2020-01-28T07:50:18
2020-01-28T07:50:17
null
UTF-8
Python
false
false
667
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-08-28 13:12 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('helpline', '0011_auto_20180828_1231'), ] operations = [ migrations.AddField( model_name='hotdesk', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL), ), ]
95ab68d99f08e0ae94963ea25c02f5a805fb9b4c
5b058d332251bcf5fe6eafb8e98c0132ab9a4e36
/pimr/studentapp/views.py
add5bec511e507ce3b58c30a09de43b00a7c6c6a
[]
no_license
shivaconceptsolution/DJANGO6-7-BATCH-PALAASIA
fcfa708c212966f57445361a0d23eafdcd4fcbcb
8b1a0707cd2837efa6ccfac2ccc6385084e69770
refs/heads/master
2020-06-28T13:02:04.798925
2019-08-26T13:44:31
2019-08-26T13:44:31
200,240,920
1
0
null
null
null
null
UTF-8
Python
false
false
2,240
py
from django.shortcuts import redirect,render from django.http import HttpResponse from .models import Student,Reg def index(request): return render(request,"studentapp/index.html") def reg(request): s = Student(rno=request.GET['txtrno'],sname=request.GET['txtname'],branch=request.GET['txtbranch'],fees=request.GET['txtfees']) s.save() return render(request,"studentapp/index.html") def login(request): return render(request,"studentapp/login.html") def loginlogic(request): e = request.POST["txtemail"] pa = request.POST["txtpass"] s = Reg.objects.filter(email=e,passsword=pa) if(s.count()==1): return redirect('viewstudent') else: return render(request,"studentapp/login.html",{"key":"invalid userid password"}) def about(request): return render(request,"studentapp/about.html") def contact(request): return render(request,"studentapp/contact.html") def viewstudent(request): res = Student.objects.all() return render(request,"studentapp/viewstudent.html",{'sturec':res}) def editstu(request): sid= request.GET["q"] res = Student.objects.get(pk=sid) print("value is ",res.rno) return render(request,"studentapp/editstu.html",{'s':res}) def deletestu(request): sid= request.GET["q"] res = Student.objects.get(pk=sid) res.delete() return redirect('viewstudent') def updatestu(request): sid= request.POST["txtid"] res = Student.objects.get(pk=sid) res.rno=request.POST["txtrno"] res.sname=request.POST["txtsname"] res.branch=request.POST["txtbranch"] res.fees=request.POST["txtfees"] res.save() return redirect('viewstudent') def si(request): p=12000 r=2.2 t=2 si=(p*r*t)/100 return HttpResponse("Result is "+str(si)) def add(request): return render(request,"studentapp/add.html") def addlogic(request): a = request.POST["txtnum1"] b = request.POST["txtnum2"] if(request.POST['btnsubmit'] =="ADD"): c = int(a)+int(b) elif(request.POST['btnsubmit'] =="SUB"): c = int(a)-int(b) elif(request.POST['btnsubmit'] =="MULTI"): c = int(a)*int(b) else: c = int(a)/int(b) return render(request,"studentapp/add.html",{'key':'result is '+str(c)})
dbdf6c8369d0743ee83ab81a07ca6a51dbbe400f
b4a1037c86a1ef04f3172746b98a68bfb42e8361
/fileupload/views.py
094ad790b7db4c5ec490959f931475b1a7120508
[]
no_license
Gathiira/authentication-system-
b51abb074d9d6f526857cbed98417ab1e42f53be
5b0ceebc5bf0b7ca9f3eb00835a3e4f3e16ab31f
refs/heads/main
2023-06-11T21:30:36.960821
2021-06-08T11:14:15
2021-06-08T11:14:15
367,470,745
3
1
null
null
null
null
UTF-8
Python
false
false
1,840
py
from rest_framework import generics, permissions, status from rest_framework.response import Response from fileupload.models import UploadFile from fileupload.serializers import FileDetailSerializer import os class UploadFileView(generics.CreateAPIView): queryset = UploadFile.objects.all() serializer_class = FileDetailSerializer permission_classes = (permissions.IsAuthenticated, ) def create(self, request): files = request.FILES.getlist("file") all_files = [] for file in files: if file.size > 15360 * 1024: return Response( {'details': 'File is too large'}, status=status.HTTP_400_BAD_REQUEST) allowed_extension = ['.jpeg', '.jpg', '.png', '.pdf'] extension = os.path.splitext(file.name)[1] if extension not in allowed_extension: return Response( {"details": f"Invalid file format. Kindly upload {','.join(allowed_extension)} only"}, status=status.HTTP_400_BAD_REQUEST) file_param = { "file": file, "filename": file.name, } file_inst = UploadFile.objects.create(**file_param) all_files.append({ "id": file_inst.id, "filename": file_inst.filename, }) return Response(all_files) class FileDetailsView(generics.ListAPIView): serializer_class = FileDetailSerializer def get_queryset(self): payload = self.request.query_params.dict() _files = payload.get('file', None) if not _files: return [] files = _files.split(',') file_query = UploadFile.objects.filter( id__in=files).order_by('-date_created') return file_query
9a6833424861ef79177af3855dd81b325de3b4de
685f4474699d769dae88537c69f5517ac13a8431
/EL64.py
0e76bdbf387850b49ca63c3ad464c238a486b1da
[]
no_license
Pumafied/Project-Euler
7466f48e449b7314598c106398c0be0424ae72d5
0c3e80a956893ce1881a9694131d52b156b9d3d8
refs/heads/master
2016-09-05T22:45:09.733696
2013-04-20T04:46:48
2013-04-20T04:46:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,772
py
# All square roots are periodic when written as continued fractions and can be written in the form: # N = a0 + # 1 # a1 + # 1 # a2 + # 1 # a3 + ... # For example, let us consider 23: # 23 = 4 + 23 — 4 = 4 + # 1 # = 4 + # 1 # 1 # 23—4 # 1 + # 23 – 3 # 7 # If we continue we would get the following expansion: # 23 = 4 + # 1 # 1 + # 1 # 3 + # 1 # 1 + # 1 # 8 + ... # The process can be summarised as follows: # a0 = 4, # 1 # 23—4 # = # 23+4 # 7 # = 1 + # 23—3 # 7 # a1 = 1, # 7 # 23—3 # = # 7(23+3) # 14 # = 3 + # 23—3 # 2 # a2 = 3, # 2 # 23—3 # = # 2(23+3) # 14 # = 1 + # 23—4 # 7 # a3 = 1, # 7 # 23—4 # = # 7(23+4) # 7 # = 8 + 23—4 # a4 = 8, # 1 # 23—4 # = # 23+4 # 7 # = 1 + # 23—3 # 7 # a5 = 1, # 7 # 23—3 # = # 7(23+3) # 14 # = 3 + # 23—3 # 2 # a6 = 3, # 2 # 23—3 # = # 2(23+3) # 14 # = 1 + # 23—4 # 7 # a7 = 1, # 7 # 23—4 # = # 7(23+4) # 7 # = 8 + 23—4 # It can be seen that the sequence is repeating. For conciseness, we use the notation 23 = [4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats indefinitely. # The first ten continued fraction representations of (irrational) square roots are: # 2=[1;(2)], period=1 # 3=[1;(1,2)], period=2 # 5=[2;(4)], period=1 # 6=[2;(2,4)], period=2 # 7=[2;(1,1,1,4)], period=4 # 8=[2;(1,4)], period=2 # 10=[3;(6)], period=1 # 11=[3;(3,6)], period=2 # 12= [3;(2,6)], period=2 # 13=[3;(1,1,1,1,6)], period=5 # Exactly four continued fractions, for N 13, have an odd period. # How many continued fractions for N 10000 have an odd period?
e51dfa0c0743c4bb60091b16980b697214e98e70
039f2c747a9524daa1e45501ada5fb19bd5dd28f
/AGC033/AGC033b.py
6f0b0176bcb0b9a0e4cfa3997f1de464dd155b2e
[ "Unlicense" ]
permissive
yuto-moriizumi/AtCoder
86dbb4f98fea627c68b5391bf0cc25bcce556b88
21acb489f1594bbb1cdc64fbf8421d876b5b476d
refs/heads/master
2023-03-25T08:10:31.738457
2021-03-23T08:48:01
2021-03-23T08:48:01
242,283,632
0
0
null
null
null
null
UTF-8
Python
false
false
168
py
#AGC033b def main(): import sys input=sys.stdin.readline sys.setrecursionlimit(10**6) # map(int, input().split()) if __name__ == '__main__': main()
25dc6353c69fd55923f4ed203e084e1c14265a36
cbcdf195338307b0c9756549a9bffebf3890a657
/django-stubs/contrib/contenttypes/fields.pyi
1b80e2e17b7a9b55545f5f6df39adf35106323a8
[ "MIT" ]
permissive
mattbasta/django-stubs
bc482edf5c6cdf33b85005c2638484049c52851b
8978ad471f2cec0aa74256fe491e2e07887f1006
refs/heads/master
2020-04-27T08:38:22.694104
2019-03-06T09:05:08
2019-03-06T09:05:24
174,178,933
1
0
MIT
2019-03-06T16:18:01
2019-03-06T16:18:00
null
UTF-8
Python
false
false
4,573
pyi
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, Generic from django.contrib.contenttypes.models import ContentType from django.core.checks.messages import Error from django.db.models.base import Model from django.db.models.fields.related import ForeignObject from django.db.models.fields.related_descriptors import ReverseManyToOneDescriptor from django.db.models.fields.reverse_related import ForeignObjectRel from django.db.models.fields import Field, PositiveIntegerField from django.db.models.fields.mixins import FieldCacheMixin from django.db.models.query import QuerySet from django.db.models.query_utils import FilteredRelation, PathInfo from django.db.models.sql.where import WhereNode class GenericForeignKey(FieldCacheMixin): auto_created: bool = ... concrete: bool = ... editable: bool = ... hidden: bool = ... is_relation: bool = ... many_to_many: bool = ... many_to_one: bool = ... one_to_many: bool = ... one_to_one: bool = ... related_model: Any = ... remote_field: Any = ... ct_field: str = ... fk_field: str = ... for_concrete_model: bool = ... rel: None = ... column: None = ... def __init__(self, ct_field: str = ..., fk_field: str = ..., for_concrete_model: bool = ...) -> None: ... name: Any = ... model: Any = ... def contribute_to_class(self, cls: Type[Model], name: str, **kwargs: Any) -> None: ... def get_filter_kwargs_for_object(self, obj: Model) -> Dict[str, Optional[ContentType]]: ... def get_forward_related_filter(self, obj: Model) -> Dict[str, int]: ... def check(self, **kwargs: Any) -> List[Error]: ... def get_cache_name(self) -> str: ... def get_content_type( self, obj: Optional[Model] = ..., id: Optional[int] = ..., using: Optional[str] = ... ) -> ContentType: ... def get_prefetch_queryset( self, instances: Union[List[Model], QuerySet], queryset: Optional[QuerySet] = ... ) -> Tuple[List[Model], Callable, Callable, bool, str, bool]: ... def __get__( self, instance: Optional[Model], cls: Type[Model] = ... ) -> Optional[Union[GenericForeignKey, Model]]: ... def __set__(self, instance: Model, value: Optional[Model]) -> None: ... class GenericRel(ForeignObjectRel): field: GenericRelation limit_choices_to: Optional[Union[Dict[str, Any], Callable[[], Any]]] model: Type[Model] multiple: bool on_delete: Callable parent_link: bool related_name: str related_query_name: None symmetrical: bool def __init__( self, field: GenericRelation, to: Union[Type[Model], str], related_name: None = ..., related_query_name: Optional[str] = ..., limit_choices_to: Optional[Union[Dict[str, Any], Callable[[], Any]]] = ..., ) -> None: ... class GenericRelation(ForeignObject): auto_created: bool = ... many_to_many: bool = ... many_to_one: bool = ... one_to_many: bool = ... one_to_one: bool = ... rel_class: Any = ... mti_inherited: bool = ... object_id_field_name: Any = ... content_type_field_name: Any = ... for_concrete_model: Any = ... to_fields: Any = ... def __init__( self, to: Union[Type[Model], str], object_id_field: str = ..., content_type_field: str = ..., for_concrete_model: bool = ..., related_query_name: Optional[str] = ..., limit_choices_to: Optional[Union[Dict[str, Any], Callable[[], Any]]] = ..., **kwargs: Any ) -> None: ... def check(self, **kwargs: Any) -> List[Error]: ... def resolve_related_fields(self) -> List[Tuple[PositiveIntegerField, Field]]: ... def get_path_info(self, filtered_relation: Optional[FilteredRelation] = ...) -> List[PathInfo]: ... def get_reverse_path_info(self, filtered_relation: None = ...) -> List[PathInfo]: ... def value_to_string(self, obj: Model) -> str: ... model: Any = ... def set_attributes_from_rel(self) -> None: ... def get_internal_type(self) -> str: ... def get_content_type(self) -> ContentType: ... def get_extra_restriction( self, where_class: Type[WhereNode], alias: Optional[str], remote_alias: str ) -> WhereNode: ... def bulk_related_objects(self, objs: List[Model], using: str = ...) -> QuerySet: ... class ReverseGenericManyToOneDescriptor(ReverseManyToOneDescriptor): field: GenericRelation rel: GenericRel def related_manager_cls(self): ... def create_generic_related_manager(superclass: Any, rel: Any): ...