blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
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
684 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
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
a7041cf991e52b763f3cd3bc1245544d989aa779
33836016ea99776d31f7ad8f2140c39f7b43b5fe
/fip_collab/2014_11_06_composite_test/microstructure_function.py
40648669fbe68bcc57b24375b06e393199591580
[]
no_license
earthexploration/MKS-Experimentation
92a2aea83e041bfe741048d662d28ff593077551
9b9ff3b468767b235e7c4884b0ed56c127328a5f
refs/heads/master
2023-03-17T23:11:11.313693
2017-04-24T19:24:35
2017-04-24T19:24:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,441
py
# -*- coding: utf-8 -*- """ Created on Fri May 23 14:25:50 2014 This script reads a set of microstructures designated by the set-ID and saves the microstructure function in real and frequency space. @author: nhpnp3 """ import time import numpy as np import functions_composite as rr import scipy.io as sio def msf(el,ns,H,set_id,wrt_file): start = time.time() ## import microstructures tmp = np.zeros([H,ns,el**3]) microstructure = sio.loadmat('M_%s%s.mat' %(ns,set_id))['M'] microstructure = microstructure.swapaxes(0,1) for h in xrange(H): tmp[h,...] = (microstructure == h).astype(int) del microstructure tmp = tmp.swapaxes(0,1) micr = tmp.reshape([ns,H,el,el,el]) del tmp np.save('msf_%s%s' %(ns,set_id),micr) end = time.time() timeE = np.round((end - start),3) msg = "generate real-space microstructure function from GSH-coefficients: %s seconds" %timeE rr.WP(msg,wrt_file) ## Microstructure functions in frequency space start = time.time() M = np.fft.fftn(micr, axes = [2,3,4]) del micr size = M.nbytes np.save('M_%s%s' %(ns,set_id),M) end = time.time() timeE = np.round((end - start),3) msg = "FFT3 conversion of micr to M_%s%s: %s seconds" %(ns,set_id,timeE) rr.WP(msg,wrt_file) msg = 'Size of M_%s%s: %s bytes' %(ns,set_id,size) rr.WP(msg,wrt_file)
[ "noahhpaulson@gmail.com" ]
noahhpaulson@gmail.com
3c15ad74bdae4f5394409a54f52da75f6dfa9934
6fff0893ef43f1018d65f2e8e1bf27d9f8accf5b
/pw_stm32cube_build/py/setup.py
4a4f3b3318d0244b9e89d087778c77c813a96b56
[ "Apache-2.0" ]
permissive
isabella232/pigweed
eeb68a4eda6f0a9b5ef0b8145d0204bc9f85bfdc
53c2f3e2569d7e582d3dd3056ceb9b2c3b8197b2
refs/heads/main
2023-06-03T10:32:29.498066
2021-06-17T06:38:15
2021-06-17T20:44:55
378,165,913
0
0
Apache-2.0
2021-06-18T13:54:37
2021-06-18T13:53:40
null
UTF-8
Python
false
false
1,131
py
# Copyright 2021 The Pigweed 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 # # 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. """pw_stm32cube_build""" import setuptools # type: ignore setuptools.setup( name='pw_stm32cube_build', version='0.0.1', author='Pigweed Authors', author_email='pigweed-developers@googlegroups.com', description='Python scripts for stm32cube targets', packages=setuptools.find_packages(), package_data={'pw_stm32cube_build': ['py.typed']}, zip_safe=False, entry_points={ 'console_scripts': [ 'stm32cube_builder = pw_stm32cube_build.__main__:main', ] }, install_requires=[])
[ "pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com
de18343ee3eb88b08ceb551823642e31ba91135a
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_118/1777.py
0029905c5b8fadd6cd1b84c5cdcbc74c89c48176
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
974
py
# /usr/bin/python import sys import math def dbg(s): sys.stderr.write(str(s) +"\n") def reads(t): return map(t, input().split(" ")) def read(t) : return t(input()) palss = { 0: [], 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 2: [11, 22, 33, 44, 55, 66, 77, 88, 99], } pals = palss[1] + palss[2] fsq = [] def gen_pals(n): ps = palss.get(n) if ps != None: return ps p_list = gen_pals(n-2) ps = [] for i in range(1, 10): for p in p_list: np = int(str(i) + str(p) + str(i)) ps.append(np) pals.append(np) palss[n] = ps return ps def gen_fsq(max_fsq): for p in pals: maybe_fsq = p**2 if maybe_fsq > max_fsq: return if maybe_fsq in pals_set: fsq.append(maybe_fsq) G = 3 for i in range(1, G+1): gen_pals(i) pals.remove(0) max_pal = pals[-1] pals_set = set(pals) gen_fsq(max_pal) T = read(int) for t in range(1, T+1): [A, B] = reads(int) cnt = 0 for f in fsq: if f >= A and f <= B: cnt += 1 print("Case #%d: %d" % (t, cnt))
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
db41ab0764713f49b58abe113aa3b99dfbace9db
a3139097d228a89255422fbfc5ee9b10992aeca1
/day_02/transcripts/trans_sets.py
2dc2e76eabc38d3dec809e54772d4dd68d597b90
[]
no_license
Code360In/07122020PYLVC
4d8e88163a00c56004d3920d5802a6c945e4af89
a0e4dd708c973ff333930191a77f289091969a3d
refs/heads/main
2023-01-29T09:03:41.375978
2020-12-11T14:00:09
2020-12-11T14:00:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,515
py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> s1 = {'a', 'a', 'b', 'b', 'c' ,'d', 'e', 'f', 'g' } >>> type(s1) <class 'set'> >>> s1 {'f', 'c', 'a', 'g', 'b', 'd', 'e'} >>> s1[2] Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> s1[2] TypeError: 'set' object is not subscriptable >>> 'a' in s1 True >>> s2 = set("defghijk") >>> s2 {'f', 'g', 'h', 'i', 'j', 'k', 'd', 'e'} >>> # ----------------------------- operators >>> >>> s1 ^ s2 {'c', 'b', 'a', 'h', 'i', 'j', 'k'} >>> s1 & s2 {'e', 'd', 'g', 'f'} >>> s1 | s2 {'i', 'f', 'c', 'g', 'a', 'h', 'b', 'j', 'k', 'd', 'e'} >>> >>> # ---------------------------- adding and removing >>> >>> s1.add("x") >>> s1 {'f', 'c', 'a', 'g', 'x', 'b', 'd', 'e'} >>> s3 = {'y', 'z'} >>> s1.update(s3) >>> s1 {'f', 'c', 'y', 'a', 'g', 'x', 'z', 'b', 'd', 'e'} >>> >>> s1.remove('g') >>> s1 {'f', 'c', 'y', 'a', 'x', 'z', 'b', 'd', 'e'} >>> >>> # ---------------------------- functions >>> >>> s1.union(s2) {'i', 'f', 'y', 'e', 'a', 'x', 'g', 'z', 'b', 'h', 'k', 'j', 'd', 'c'} >>> s1.intersection(s2) {'d', 'e', 'f'} >>> >>> >>> # -------------------------------- interconversion >>> >>> s1 {'f', 'c', 'y', 'a', 'x', 'z', 'b', 'd', 'e'} >>> list(s1) ['f', 'c', 'y', 'a', 'x', 'z', 'b', 'd', 'e'] >>> tuple(s1) ('f', 'c', 'y', 'a', 'x', 'z', 'b', 'd', 'e') >>>
[ "noreply@github.com" ]
Code360In.noreply@github.com
82e64f85567565fee068b5888b54eba2a79ab18e
f569978afb27e72bf6a88438aa622b8c50cbc61b
/douyin_open/EnterpriseGrouponGrouponCodeCodeDeposit/models/inline_response200.py
12e39d0314ab86197d71e68b691b7582b16b95da
[]
no_license
strangebank/swagger-petstore-perl
4834409d6225b8a09b8195128d74a9b10ef1484a
49dfc229e2e897cdb15cbf969121713162154f28
refs/heads/master
2023-01-05T10:21:33.518937
2020-11-05T04:33:16
2020-11-05T04:33:16
310,189,316
1
0
null
null
null
null
UTF-8
Python
false
false
3,756
py
# coding: utf-8 """ 自定义卷码预存 No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class InlineResponse200(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'extra': 'ExtraBody', 'data': 'InlineResponse200Data' } attribute_map = { 'extra': 'extra', 'data': 'data' } def __init__(self, extra=None, data=None): # noqa: E501 """InlineResponse200 - a model defined in Swagger""" # noqa: E501 self._extra = None self._data = None self.discriminator = None if extra is not None: self.extra = extra if data is not None: self.data = data @property def extra(self): """Gets the extra of this InlineResponse200. # noqa: E501 :return: The extra of this InlineResponse200. # noqa: E501 :rtype: ExtraBody """ return self._extra @extra.setter def extra(self, extra): """Sets the extra of this InlineResponse200. :param extra: The extra of this InlineResponse200. # noqa: E501 :type: ExtraBody """ self._extra = extra @property def data(self): """Gets the data of this InlineResponse200. # noqa: E501 :return: The data of this InlineResponse200. # noqa: E501 :rtype: InlineResponse200Data """ return self._data @data.setter def data(self, data): """Sets the data of this InlineResponse200. :param data: The data of this InlineResponse200. # noqa: E501 :type: InlineResponse200Data """ self._data = data def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(InlineResponse200, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, InlineResponse200): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "strangebank@gmail.com" ]
strangebank@gmail.com
eb99088385dfeba2cc4eaf7cfc1cec214ff6f8a1
db4add5587fbcb24bd6147a5f2cc161743553429
/venv/lib/python3.6/site-packages/sqlalchemy/dialects/mssql/pymssql.py
cfcfb4afc306ea8222d264b2f34b031b8c470614
[ "MIT" ]
permissive
DiptoChakrabarty/FlaskKube-api
38dedb5695f00f1fa0ee58af1f4b595c37f3ba0f
50bf4c226ce2ed0d544cb2eb16f5279e0fe25ca1
refs/heads/master
2022-12-25T04:08:52.669305
2020-10-01T08:42:39
2020-10-01T08:42:39
259,813,586
4
5
MIT
2020-10-01T08:42:41
2020-04-29T03:20:59
Python
UTF-8
Python
false
false
4,677
py
# mssql/pymssql.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: mssql+pymssql :name: pymssql :dbapi: pymssql :connectstring: mssql+pymssql://<username>:<password>@<freetds_name>/?charset=utf8 pymssql is a Python module that provides a Python DBAPI interface around `FreeTDS <http://www.freetds.org/>`_. Modern versions of this driver worked very well with SQL Server and FreeTDS from Linux and were highly recommended. However, pymssql is currently unmaintained and has fallen behind the progress of the Microsoft ODBC driver in its support for newer features of SQL Server. The latest official release of pymssql at the time of this document is version 2.1.4 (August, 2018) and it lacks support for: 1. table-valued parameters (TVPs), 2. ``datetimeoffset`` columns using timezone-aware ``datetime`` objects (values are sent and retrieved as strings), and 3. encrypted connections (e.g., to Azure SQL), when pymssql is installed from the pre-built wheels. Support for encrypted connections requires building pymssql from source, which can be a nuisance, especially under Windows. The above features are all supported by mssql+pyodbc when using Microsoft's ODBC Driver for SQL Server (msodbcsql), which is now available for Windows, (several flavors of) Linux, and macOS. """ # noqa import re from .base import MSDialect from .base import MSIdentifierPreparer from ... import processors from ... import types as sqltypes from ... import util class _MSNumeric_pymssql(sqltypes.Numeric): def result_processor(self, dialect, type_): if not self.asdecimal: return processors.to_float else: return sqltypes.Numeric.result_processor(self, dialect, type_) class MSIdentifierPreparer_pymssql(MSIdentifierPreparer): def __init__(self, dialect): super(MSIdentifierPreparer_pymssql, self).__init__(dialect) # pymssql has the very unusual behavior that it uses pyformat # yet does not require that percent signs be doubled self._double_percents = False class MSDialect_pymssql(MSDialect): supports_native_decimal = True driver = "pymssql" preparer = MSIdentifierPreparer_pymssql colspecs = util.update_copy( MSDialect.colspecs, {sqltypes.Numeric: _MSNumeric_pymssql, sqltypes.Float: sqltypes.Float}, ) @classmethod def dbapi(cls): module = __import__("pymssql") # pymmsql < 2.1.1 doesn't have a Binary method. we use string client_ver = tuple(int(x) for x in module.__version__.split(".")) if client_ver < (2, 1, 1): # TODO: monkeypatching here is less than ideal module.Binary = lambda x: x if hasattr(x, "decode") else str(x) if client_ver < (1,): util.warn( "The pymssql dialect expects at least " "the 1.0 series of the pymssql DBAPI." ) return module def _get_server_version_info(self, connection): vers = connection.scalar("select @@version") m = re.match(r"Microsoft .*? - (\d+).(\d+).(\d+).(\d+)", vers) if m: return tuple(int(x) for x in m.group(1, 2, 3, 4)) else: return None def create_connect_args(self, url): opts = url.translate_connect_args(username="user") opts.update(url.query) port = opts.pop("port", None) if port and "host" in opts: opts["host"] = "%s:%s" % (opts["host"], port) return [[], opts] def is_disconnect(self, e, connection, cursor): for msg in ( "Adaptive Server connection timed out", "Net-Lib error during Connection reset by peer", "message 20003", # connection timeout "Error 10054", "Not connected to any MS SQL server", "Connection is closed", "message 20006", # Write to the server failed "message 20017", # Unexpected EOF from the server "message 20047", # DBPROCESS is dead or not enabled ): if msg in str(e): return True else: return False def set_isolation_level(self, connection, level): if level == "AUTOCOMMIT": connection.autocommit(True) else: connection.autocommit(False) super(MSDialect_pymssql, self).set_isolation_level( connection, level ) dialect = MSDialect_pymssql
[ "diptochuck123@gmail.com" ]
diptochuck123@gmail.com
976b1f612310075478e65e12b9776472bcf16ee0
a6c48d5d697cd0ba48bc7c6bd64e871326ce6458
/server/libs/pyticas_noaa/test/stations.py
14a4d003b74a916682190216840fbd9e27984dac
[]
no_license
lakshmanamettu/tetres
873a878cf06b313ee26537504e63f5efdecdc98f
1acf985f378106953cbff34fb99147cac5104328
refs/heads/master
2020-06-30T19:33:44.044090
2019-08-06T16:21:18
2019-08-06T16:21:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,154
py
# -*- coding: utf-8 -*- __author__ = 'Chongmyung Park (chongmyung.park@gmail.com)' import csv import datetime class ISDStation(object): def __init__(self, row): """ :type row: list[str] """ self.usaf = None self.wban = None self.station_name = None self.city = None self.state = None self.icao = None self.lat = None self.lon = None self.elev = None self.begin = None self.end = None attrs = ['usaf', 'wban', 'station_name', 'city', 'state', 'icao', 'lat', 'lon', 'elev', 'begin', 'end'] for idx, aname in enumerate(attrs): setattr(self, aname, row[idx]) def get_date_range(self): """ :rtype: (datetime.date, datetime.date) """ return (datetime.datetime.strptime(self.begin, "%Y%m%d").date(), datetime.datetime.strptime(self.end, "%Y%m%d").date()) def is_valid(self, dt): """ :type dt: datetime.date :rtype: bool """ begin, end = self.get_date_range() return (begin <= dt <= end) def __str__(self): return '<ISDStation usaf="%s" wban="%s" name="%s" begin="%s" end="%s">' % ( self.usaf, self.wban, self.station_name, self.begin, self.end ) def load_isd_stations(filepath, state='MN', station_filter=None): """ :type filepath: str :type state: str :type station_filter: function :rtype: list[ISDStation] """ stations = [] with open(filepath, 'r') as f: cr = csv.reader(f) for idx, row in enumerate(cr): if not idx: continue if row[4] != state: continue st = ISDStation(row) if not station_filter or station_filter(st): stations.append(st) return stations DATA_FILE = 'isd-history.csv' stations = load_isd_stations(DATA_FILE, 'MN', lambda st: st.is_valid(datetime.date(2017, 1, 31))) for idx, st in enumerate(stations): print(idx, ':', st)
[ "beau1eth@tmsdev5.dot.state.mn.us" ]
beau1eth@tmsdev5.dot.state.mn.us
49582b8c6a9f659561e39a6385394b3b6f3d86f8
e23a4f57ce5474d468258e5e63b9e23fb6011188
/333_nuke/__exercises/Nuke_Scripting_for_Pipeline_TD/003_Dopolnitelnue_mareialu/module_nukescripts.py
2f0806e2df8e5772e47a542b87ed98158954dad2
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
624
py
import nuke import os import nukescripts nukescripts.autoBackdrop() def clearNodeSelection(): for n in nuke.selectedNodes(): # n['selected'].setValue(False) n.setSelected(False) nukescripts.clear_selection_recursive() nukescripts.declone(node) nukescripts.declone(nuke.selectedNode()) nukescripts.swapAB(nuke.selectedNode()) nukescripts.color_nodes() nukescripts.search_replace() nukescripts.getNukeUserFolder() # nukescripts.findNextNodeName('Read') # nuke.nodes.Read() # nuke.nodes.Read(name=nukescripts.findNextNodeName('Read')) # nuke.createNode('Read') # t = nuke.toNode('Read3') # t.setSelected(1)
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
33d7882c955e9858ee8e5d4ad0d2b2178ee13693
4c432a555bc3932880b201e0686d75bc2abd80b9
/lib/core_preprocessor.py
56b4d092df896b8852f2055515ceb0d566155b86
[ "BSD-3-Clause" ]
permissive
lmdalessio/aTRAM
3a14f08994d3ce7de692df3b90d5d7f99e8af9a8
807f43d83887dd80dea158b9a22ecb2a4e1aa220
refs/heads/master
2021-03-05T11:17:02.324817
2020-03-06T16:58:56
2020-03-06T16:58:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,987
py
""" Format the data so that atram can use it later in atram itself. It takes sequence read archive (SRA) files and converts them into coordinated blast and sqlite3 databases. """ from os.path import join, basename, splitext import sys import multiprocessing import numpy as np from Bio.SeqIO.QualityIO import FastqGeneralIterator from Bio.SeqIO.FastaIO import SimpleFastaParser from . import db from . import db_preprocessor from . import log from . import util from . import blast def preprocess(args): """Build the databases required by atram.""" log.setup(args['log_file'], args['blast_db']) with util.make_temp_dir( where=args['temp_dir'], prefix='atram_preprocessor_', keep=args['keep_temp_dir']) as temp_dir: util.update_temp_dir(temp_dir, args) with db.connect(args['blast_db'], clean=True) as cxn: db_preprocessor.create_metadata_table(cxn, args) db_preprocessor.create_sequences_table(cxn) load_seqs(args, cxn) log.info('Creating an index for the sequence table') db_preprocessor.create_sequences_index(cxn) shard_list = assign_seqs_to_shards(cxn, args['shard_count']) create_all_blast_shards(args, shard_list) def load_seqs(args, cxn): """Load sequences from a fasta/fastq files into the atram database.""" # We have to clamp the end suffix depending on the file type. for (ends, clamp) in [('mixed_ends', ''), ('end_1', '1'), ('end_2', '2'), ('single_ends', '')]: if args.get(ends): for file_name in args[ends]: load_one_file(args, cxn, file_name, ends, clamp) def load_one_file(args, cxn, file_name, ends, seq_end_clamp=''): """Load sequences from a fasta/fastq file into the atram database.""" log.info('Loading "{}" into sqlite database'.format(file_name)) parser = get_parser(args, file_name) with util.open_file(args, file_name) as sra_file: batch = [] for rec in parser(sra_file): title = rec[0].strip() seq = rec[1] seq_name, seq_end = blast.parse_fasta_title( title, ends, seq_end_clamp) batch.append((seq_name, seq_end, seq)) if len(batch) >= db.BATCH_SIZE: db_preprocessor.insert_sequences_batch(cxn, batch) batch = [] db_preprocessor.insert_sequences_batch(cxn, batch) def get_parser(args, file_name): """Get either a fasta or fastq file parser.""" is_fastq = util.is_fastq_file(args, file_name) return FastqGeneralIterator if is_fastq else SimpleFastaParser def assign_seqs_to_shards(cxn, shard_count): """Assign sequences to blast DB shards.""" log.info('Assigning sequences to shards') total = db_preprocessor.get_sequence_count(cxn) offsets = np.linspace(0, total - 1, dtype=int, num=shard_count + 1) cuts = [db_preprocessor.get_shard_cut(cxn, offset) for offset in offsets] # Make sure the last sequence gets included cuts[-1] = cuts[-1] + 'z' # Now organize the list into pairs of sequence names pairs = [(cuts[i - 1], cuts[i]) for i in range(1, len(cuts))] return pairs def create_all_blast_shards(args, shard_list): """ Assign processes to make the blast DBs. One process for each blast DB shard. """ log.info('Making blast DBs') with multiprocessing.Pool(processes=args['cpus']) as pool: results = [] for idx, shard_params in enumerate(shard_list, 1): results.append(pool.apply_async( create_one_blast_shard, (args, shard_params, idx))) all_results = [result.get() for result in results] log.info('Finished making blast all {} DBs'.format(len(all_results))) def create_one_blast_shard(args, shard_params, shard_index): """ Create a blast DB from the shard. We fill a fasta file with the appropriate sequences and hand things off to the makeblastdb program. """ shard = '{}.{:03d}.blast'.format(args['blast_db'], shard_index) exe_name, _ = splitext(basename(sys.argv[0])) fasta_name = '{}_{:03d}.fasta'.format(exe_name, shard_index) fasta_path = join(args['temp_dir'], fasta_name) fill_blast_fasta(args['blast_db'], fasta_path, shard_params) blast.create_db(args['temp_dir'], fasta_path, shard) def fill_blast_fasta(blast_db, fasta_path, shard_params): """ Fill the fasta file used as input into blast. Use sequences from the sqlite3 DB. We use the shard partitions passed in to determine which sequences to get for this shard. """ with db.connect(blast_db) as cxn: limit, offset = shard_params with open(fasta_path, 'w') as fasta_file: for row in db_preprocessor.get_sequences_in_shard( cxn, limit, offset): util.write_fasta_record(fasta_file, row[0], row[2], row[1])
[ "raphael.lafrance@gmail.com" ]
raphael.lafrance@gmail.com
3092a3b0b103669277fb6168d38c7712550116c8
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03611/s849629257.py
c22112651ffbef820aae30f404b80b8e6c08dc60
[]
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
282
py
n = int(input()) a = list(map(int, input().split())) count = [0]*(max(a)+1) for i in a: count[i]+=1 if len(count) <= 2: print(sum(count)) exit() ans = 0 for i in range(2,max(a)): if count[i-1]+count[i]+count[i+1] > ans: ans = count[i-1]+count[i]+count[i+1] print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
dafbe5e66dfcb61cad1999bdba519ec439021ce9
8d2c37a19076690dbe0f1b6c64467eeb7475b4ae
/kikoha/apps/voting/models.py
d958372da246c1e1c1c78cc1adb74b981448be92
[]
no_license
siolag161/kikoha
39fbdbc6f27337b8b84661165448d0e4a23a79d4
e8af8c7b0019faa6cc3a6821e2c04f6d8142fd08
refs/heads/master
2016-09-03T06:44:57.088649
2014-12-25T03:10:07
2014-12-25T03:10:07
25,884,164
0
0
null
null
null
null
UTF-8
Python
false
false
2,179
py
# coding: utf-8 from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.dispatch import receiver from django.db import models from core.models import OwnedModel, TimeStampedModel from .managers import VoteManager POINTS = ( (+1, '+1'), (-1, '-1'), ) ## todo: define maybe a contenttype base class @python_2_unicode_compatible class Vote(OwnedModel, TimeStampedModel, models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey('content_type', 'object_id') vote = models.SmallIntegerField(choices = POINTS ) objects = VoteManager() class Meta: db_table = 'votes' unique_together = (('author', 'content_type', 'object_id'),) def __str__(self): return '%s: %s on %s' % (self.author, self.vote, self.object) def is_upvote(self): return self.vote == 1 def is_downvote(self): return self.vote == -1 TOTAL_CHANGES = { 'CLEARED': -1, 'UPGRADED': 0, 'DOWNGRADED': 0, 'CREATED': +1 } UPVOTES_CHANGES = { 'CLEARED': 0, 'UPGRADED': +1, 'DOWNGRADED': -1, 'CREATED': +1 } import logging logger = logging.getLogger("werkzeug") class VotedModel(models.Model): upvotes = models.PositiveIntegerField(default=1) totalvotes = models.IntegerField(default=1) @property def downvotes(self): return totalvotes - upvotes @property def point(self): return 2*self.upvotes - self.totalvotes # upvotes - downvotes class Meta: abstract = True def get_point(self): return { 'point': self.point, 'num_votes': self.totalvotes } def update_vote(self, update_type, vote): if update_type and vote: self.totalvotes += TOTAL_CHANGES[update_type] self.upvotes += UPVOTES_CHANGES[update_type] if update_type == 'CLEARED' and vote.vote > 0: self.upvotes -= vote.vote if update_type == 'CREATED' and vote.vote < 0: self.upvotes += vote.vote self.save()
[ "thanh.phan@outlook.com" ]
thanh.phan@outlook.com
a5c7e9f7952089395270e27d81634bb006a7830d
0133d8d56ee611a0c65ef80693ae263692557b96
/spira/yevon/filters/layer_filter.py
4ff08772238a31e9cf4202378a362503d9cfb6d0
[ "MIT" ]
permissive
JCoetzee123/spira
e77380df2e79333b0c48953faae2d3dae50a8d27
dae08feba1578ecc8745b45109f4fb7bef374546
refs/heads/master
2021-06-25T23:32:52.289382
2019-07-17T13:25:50
2019-07-17T13:25:50
198,605,222
1
0
MIT
2019-07-24T09:42:07
2019-07-24T09:42:06
null
UTF-8
Python
false
false
1,112
py
from spira.log import SPIRA_LOG as LOG from spira.yevon.filters.filter import Filter # from spira.yevon.process.layer_list import LayerList, LayerListParameter from spira.yevon.process.gdsii_layer import LayerList, LayerListParameter __all__ = ['LayerFilterAllow', 'LayerFilterDelete'] class __LayerFilter__(Filter): layers = LayerListParameter() class LayerFilterAllow(__LayerFilter__): def __filter___LayerElement____(self, item): if item.layer in self.layers: return [item] else: LOG.debug("LayerFilterAllow is filtering out item %s" %item) return [] def __repr__(self): return "[SPiRA: LayerFilterDelete] (layer count {})".format(len(self.layers)) class LayerFilterDelete(__LayerFilter__): def __filter___LayerElement____(self, item): if item.layer in self.layers: LOG.debug("LayerFilterDelete is filtering out item %s" %item) return [] else: return [item] def __repr__(self): return "[SPiRA: LayerFilterDelete] (layer count {})".format(len(self.layers))
[ "rubenvanstaden@gmail.com" ]
rubenvanstaden@gmail.com
2b4c1b5b88e67aa6787b4704564067ebd2403069
938a496fe78d5538af94017c78a11615a8498682
/SwordRefersToOffer/11.NumberOf1.py
55ed4a03ad52b60ceb6e7472bafa3fd959ffa8fe
[]
no_license
huilizhou/Leetcode-pyhton
261280044d15d0baeb227248ade675177efdb297
6ae85bf79c5a21735e3c245c0c256f29c1c60926
refs/heads/master
2020-03-28T15:57:52.762162
2019-11-26T06:14:13
2019-11-26T06:14:13
148,644,059
8
1
null
null
null
null
UTF-8
Python
false
false
309
py
# -*- coding:utf-8 -*- # 二进制中1的个数 class Solution: def NumberOf1(self, n): # write code here count = 0 if n < 0: n = n & 0xffffffff while n: count += 1 n = n & (n - 1) return count print(Solution().NumberOf1(3))
[ "2540278344@qq.com" ]
2540278344@qq.com
34a7acd539aa930a26936a914f4e663c21da9000
73978c38ef18dd87b75d6af706de58f5633ee157
/trunk/zkomm_multiserver/src/modelo_lista_nodos.py
44435e9e08934dc9b4060a6c58be21ffdfa36e65
[]
no_license
BGCX261/zkomm-multiserv-svn-to-git
1702f2bc9ef8764dd9a35c301e9dbb362b4e2d12
830ccd1ec3a617f30450ad6d038107bf9aafa6a2
refs/heads/master
2021-01-19T08:53:11.428916
2015-08-25T15:43:46
2015-08-25T15:43:46
41,488,688
0
0
null
null
null
null
UTF-8
Python
false
false
1,116
py
#ZKOMM Multiserver #Modelos de vistas from PyQt4 import * class modelo_lista_nodos: def __init__(self, padre, lista = []): self.m = QtGui.QStandardItemModel(0, 5, padre) encabezados = QtCore.QStringList() encabezados << "Nodo (ID)" << "Nombre" << "IP" << "Puerto" << "Capacidad" << "Carga" << "Sobrecarga" << "Penalizacion" self.m.setHorizontalHeaderLabels(encabezados) self.lista_nodos = lista self.actualizar_lista(self.lista_nodos) def actualizar_lista(self,lista): self.lista_nodos=lista row = 0 self.m.setRowCount(len(self.lista_nodos)) for i in self.lista_nodos: self.m.setItem(row, 0, QtGui.QStandardItem(str(i.ident))) self.m.setItem(row, 1, QtGui.QStandardItem(str(i.nombre))) self.m.setItem(row, 2, QtGui.QStandardItem(str(i.ip))) self.m.setItem(row, 3, QtGui.QStandardItem(str(i.puerto))) self.m.setItem(row, 4, QtGui.QStandardItem(str(i.capacidad))) self.m.setItem(row, 5, QtGui.QStandardItem(str(i.carga))) self.m.setItem(row, 6, QtGui.QStandardItem(str(i.sobrecarga))) self.m.setItem(row, 7, QtGui.QStandardItem(str(i.penalizacion))) row = row + 1
[ "you@example.com" ]
you@example.com
9ba8b32ba254af1cf723aab25c9a85110c4f54b6
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/438/usersdata/348/94998/submittedfiles/pico.py
8c6e09f062dd15ec153e26731839b488ba972b38
[]
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
617
py
# -*- coding: utf-8 -*- #funçoes def crescente(lista): for i in range (n,-1,-1): if lista[0] > lista[1]: return 'N' elif (lista[i-1] < lista[i-2]) and (lista[0] < lista[1]) : return 'S' elif (lista[0] < lista[1]): return 'S' elif lista[0] < lista[1]: return 'S' i = i+1 #codigo geral n = int(input('Digite a quantidade de elementos da lista: ')) l1 = [] for i in range (0,n,1): l1.append(int(input( 'informe o %d° elemento da lista: ' %(i+1)))) print(crescente(l1))
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
0355e904e902fa6f33f696424157267e37861148
491235d50ab27bb871d58a5dfff74d6a4aa9bbe6
/pong-client/gui/__init__.py
4ac6e8ce43257509a2ebdc0c6c8e5d0bacc29e8f
[]
no_license
elgrandt/Pong-Network
768bb861757d1fb98be3b761a66ad14e632f7932
204e1c5d9fbd53eece906d56df394602bdc269b6
refs/heads/master
2022-12-06T16:12:01.506699
2020-08-18T03:27:47
2020-08-18T03:27:47
288,315,589
1
0
null
null
null
null
UTF-8
Python
false
false
281
py
from add_border import * from input_text import * from moving_bar import * from area_movil import * from server_list import * from server_connect_menu import * from surface_gf import * import add_border import input_text import moving_bar import area_movil from status_cur import *
[ "dylantasat11@gmail.com" ]
dylantasat11@gmail.com
0d608ca99a5df062161a727ba15e6c5d0d860cfa
d55f3f715c00bcbd60badb3a31696a1a629600e2
/students/maks/9/site2/page/migrations/0002_category.py
ee732793b384633ecbbe6c4b58bbd67a5b4d787d
[]
no_license
zdimon/wezom-python-course
ea0adaa54444f6deaca81ce54ee8334297f2cd1a
5b87892102e4eb77a4c12924d2d71716b9cce721
refs/heads/master
2023-01-29T02:22:54.220880
2020-12-05T11:27:48
2020-12-05T11:27:48
302,864,112
0
0
null
null
null
null
UTF-8
Python
false
false
502
py
# Generated by Django 3.1.2 on 2020-11-14 10:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('page', '0001_initial'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=250)), ], ), ]
[ "you@example.com" ]
you@example.com
205794e0f345bd8c88dca18a2b82e9f5364d5430
168556624401cd884fe0bfdac5a312adf51286a1
/CS1430/homework4_sceneclassification-Enmin/code/trial.py
ce43e58f440332e775d1492ab4a36598380a3a3c
[]
no_license
Enmin/Coursework
f39dc7b54a07b901491fbd809187fd54e96fa5a4
a17d216c37e70a8073602389924af10019cfe7de
refs/heads/master
2021-12-28T02:53:15.949547
2021-12-21T22:45:19
2021-12-21T22:45:19
179,909,211
0
0
null
null
null
null
UTF-8
Python
false
false
909
py
import numpy as np import matplotlib import time from matplotlib import pyplot as plt from helpers import progressbar from skimage import io from skimage.io import imread from skimage.color import rgb2grey from skimage.feature import hog from skimage.transform import resize from scipy.spatial.distance import cdist def get_tiny_images(image_paths): #TODO: Implement this function! output = [] for image_path in image_paths: image = imread(image_path) if len(image.shape) > 2: image = rgb2grey(image) image = resize(image, output_shape=(64, 64), anti_aliasing=True) output.append(image) return np.array(output) # res = get_tiny_images([r'..\data\train\Bedroom\image_0002.jpg']) # io.imshow(res[0]) # plt.show() def build_vocab(): num_imgs = 1000 for i in progressbar(range(num_imgs), "Loading ...", num_imgs): pass build_vocab()
[ "zhouem14@gmail.com" ]
zhouem14@gmail.com
8526bf590577cee22e9f84d173c847d4b9407e14
824f19d20cdfa26c607db1ff3cdc91f69509e590
/Array-101/5-Merge-Sorted-Array.py
e028a6ec47e16b2bddb04b2c0dac066cac1c70c2
[]
no_license
almamuncsit/LeetCode
01d7e32300eebf92ab54c983de6e183242b3c985
17aa340649574c37067ec170ceea8d9326be2d6a
refs/heads/master
2021-07-07T09:48:18.069020
2021-03-28T11:26:47
2021-03-28T11:26:47
230,956,634
4
0
null
null
null
null
UTF-8
Python
false
false
390
py
from typing import List class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: i, j, k = m - 1, n - 1, m + n - 1 while j >= 0: if nums1[i] >= nums2[j] and i >= 0: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1
[ "msarkar.cse@gmail.com" ]
msarkar.cse@gmail.com
9ab60f6818d611b38e5a018aab0b282e5e417ec6
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_bobbling.py
5754a833bc3c73ef4d8503d781013e85cd1c3248
[ "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
240
py
from xai.brain.wordbase.nouns._bobble import _BOBBLE #calss header class _BOBBLING(_BOBBLE, ): def __init__(self,): _BOBBLE.__init__(self) self.name = "BOBBLING" self.specie = 'nouns' self.basic = "bobble" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
541ff8209cf419cbd7c780213cf1f0c62b91a4d7
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_313/ch75_2020_04_07_18_04_40_887750.py
39e6ed3c06555b5fc1e686140dc5d782dadd9b6c
[]
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
500
py
def verifica_primos(l1): dicionario = {} for i in l1: if i == 0 or i == 1 or i == -1: dicionario[i] = True elif i == 2: dicionario[i] = True elif i % 2 == 0: dicionario[i] = False else: a = 3 for a in range(3,17,2): print (a) if i % a == 0: dicionario[i] = False dicionario[i] = True return dicionario
[ "you@example.com" ]
you@example.com
04b60bf68bf3570d0bc85f8a5ffe962f4f658aa1
2635c2e2c31a7badb8b188306c3cdfc61dc1ecc8
/ihm_add_fields_productos/models/add_fields_product.py
71ba7678d0edaea18b210f7f577c718ee38a5872
[]
no_license
rosalesdc/ihm_testing
ec4ebf26c3c7602267a04fd183de4064f9d16bc1
d91ebeac5504c9f29a21b2b0f05bc16ed240ff48
refs/heads/master
2020-04-17T01:21:03.214595
2019-10-29T23:05:52
2019-10-29T23:05:52
166,088,611
0
0
null
null
null
null
UTF-8
Python
false
false
7,791
py
# -*- coding: utf-8 -*- from odoo import api from odoo import fields from odoo import models from odoo.exceptions import UserError from odoo.exceptions import ValidationError import smtplib class AddProductFields(models.Model): _inherit = 'product.template' name = fields.Char('Name', index=True, required=True, translate=False) #Antes de crear un producto checa que el usuario no esté restringido @api.model def create(self, vals): producto_creado=super(AddProductFields, self).create(vals) if producto_creado.is_group_restr == True: raise ValidationError('Usuario actual no puede crear inmuebles') else: return producto_creado #Antes de actualizar el producto se verifica si el usuario es administrador # @api.multi # def write(self, vals): # print(vals) # if self.es_inmueble == True and self.is_group_admin == False: # keys=vals.keys() # if ('invoice_policy' in keys) or ('service_type' in keys) or ('estatus' in keys) or ('sale_order' in keys): # return super(AddProductFields, self).write(vals) # else: # raise ValidationError('Usuario actual no puede actualizar inmuebles') # else: # return super(AddProductFields, self).write(vals) #Antes de eliminar el producto se verifica si el usuario es administrador @api.multi def unlink(self): if self.es_inmueble == True and self.is_group_admin == False: raise ValidationError('Usuario actual no puede eliminar inmuebles') else: return super(AddProductFields, self).unlink() @api.one @api.depends('x_asignacion_ids.importe') def _compute_total_elementos(self): self.importe_total_elementos = sum(line.importe for line in self.x_asignacion_ids) @api.one def asignar_precio_inmueble(self): precio_calculado = float(self.importe_total_elementos) self.write({'list_price': precio_calculado}) @api.model def get_default_estatus(self): default_estatus = 'Disponible' return default_estatus @api.one @api.depends('estatus') def _compute_copy_estatus(self): if self.estatus != False: if self.estatus == "Disponible": self.estatus_ordenado = "01-Disponible" elif self.estatus == "Apartado": self.estatus_ordenado = "02-Apartado" elif self.estatus == "Vendido": self.estatus_ordenado = "03-Vendido" elif self.estatus == "Escriturado": self.estatus_ordenado = "04-Escriturado" elif self.estatus == "Preparacion": self.estatus_ordenado = "05-Liberado" elif self.estatus == "Entregado": self.estatus_ordenado = "06-Entregado" @api.one @api.model @api.depends('sale_order') def _obtener_referencia(self): orden = self.env['sale.order'].search([('id', '=', self.sale_order.id)]) #self.xreferencia=orden.name self.xreferencia = orden.id_numero_referencia.name #Funcion que busca al usuario en el grupo de administradores @api.one def _compute_is_group_admin(self): self.is_group_admin = self.env['res.users'].has_group('ihm_ocultar_validar.group_director') #Funcion que busca que el usuario no pertenezca al campo que puede editar/crear productos @api.one def _compute_is_group_restringido(self): self.is_group_restr = self.env['res.users'].has_group('ihm_ocultar_validar.group_no_editarcrear') #Campo para revisar si el usuario actual es un administrador is_group_admin = fields.Boolean( string='Is Admin', compute="_compute_is_group_admin", ) is_group_restr = fields.Boolean( string='Is Restringido', compute="_compute_is_group_restringido", ) #características para los productos que son inmuebles y su proyecto relacionado es_inmueble = fields.Boolean(string="Es un inmueble") caracteristicas = fields.Text(string="Características") numero = fields.Char(string="Número") estatus = fields.Selection( selection=[ ('Disponible', '01 Disponible'), ('Apartado', '02 Apartado'), ('Vendido', '03 Vendido'), ('Escriturado', '04 Escriturado'), ('Preparacion', '05 Liberado'), ('Entregado', '06 Entregado'), ], string="Estatus", copy=False, readonly=True, default=get_default_estatus, ) estatus_ordenado = fields.Char(string="Estatus ordenado", readonly=True, store=True, compute='_compute_copy_estatus', ) x_proyecto_id = fields.Many2one('project.project', string='Proyecto') x_asignacion_ids = fields.One2many( 'asignacion.elementos', #modelo al que se hace referencia 'inmueble_id', #un campo de regreso string="Asignacion elementos" ) #CAMPO PARA EL CALCULO DE TOTAL DE LOS ELEMENTOS importe_total_elementos = fields.Float(string='Importe total elementos', #store=True, readonly=True, compute='_compute_total_elementos', ) oportunidades_ids = fields.One2many( 'crm.lead', #modelo al que se hace referencia 'id_producto_inmueble', #un campo de regreso string="Oportunidad" )# cantidad_enganche = fields.Float( string="Cantidad Contrato" ) garantia_id = fields.Many2one( 'tipo.garantia', string="Tipo de garantia" ) sale_order = fields.Many2one( 'sale.order', copy=False, string="Orden de venta del" ) xreferencia = fields.Char( string='Referencia', #store=True, compute='_obtener_referencia', ) #campo que muestra la referencia en el listado de inmuebles xreferencia_texto = fields.Char( string='Referencia', #store=True, ) #https://fundamentos-de-desarrollo-en-odoo.readthedocs.io/es/latest/capitulos/modelos-estructura-datos-aplicacion.html
[ "rosales9146@gmail.com" ]
rosales9146@gmail.com
3690de3d521be3542a0c4bafc7ca2f7cdc71a149
36bdbbf1be53ba5f09b9a2b1dd15e91f8f6b0da1
/house/migrations/0004_auto_20180920_2003.py
2c799c963093e1889c416fe8249beab35804299e
[]
no_license
phufoxy/fotourNew
801ab2518424118020dc6e5f31a7ba90a654e56a
6048c24f5256c8c5a0d18dc7b38c106a7c92a29c
refs/heads/master
2023-04-13T01:34:22.510717
2018-12-26T03:46:09
2018-12-26T03:46:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
791
py
# Generated by Django 2.1 on 2018-09-20 13:03 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('house', '0003_auto_20180920_2002'), ] operations = [ migrations.RenameField( model_name='house', old_name='city', new_name='location', ), migrations.AlterField( model_name='comment_house', name='date', field=models.DateTimeField(default=datetime.datetime(2018, 9, 20, 20, 3, 15, 282441)), ), migrations.AlterField( model_name='house_tour', name='date', field=models.DateTimeField(default=datetime.datetime(2018, 9, 20, 20, 3, 15, 283439)), ), ]
[ "vanphudhsp2015@gmail.com" ]
vanphudhsp2015@gmail.com
2e2066e619ccc7d33ad5a3115a5f2d7b25804acc
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_206/1619.py
627355a3f0c5448f6788990546a6563e13a4e9b3
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
809
py
for Pr in xrange(1, input()+1): D, N=[int(x) for x in raw_input().split()] d, v=[], [] for i in xrange(N): c=[int(x) for x in raw_input().split()] d.append(c[0]) v.append(c[1]) d_sort=[k for k in d] d_sort.sort() v_sort=[] for k in d_sort: v_sort.append(v[d.index(k)]) d,v=d_sort, v_sort curv=v[0] d_ok, v_ok=[d[0]], [v[0]] for i in xrange(1, N): if v[i]<curv: d_ok.append(d[i]) v_ok.append(v[i]) curv=v[i] d, v=d_ok, v_ok N=len(d) d1, v1=d[0], v[0] T=0 for i in xrange(1, N): t=float(d1-d[i])/(v[i]-v1) dd=d1+v1*t if D<=dd: break else: d1=dd v1=v[i] T+= t T+= (D-d1)/float(v1) solve=D/T print 'Case #%d: %f'%(Pr, solve)
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
36890bb9f1effdf8395b81675dd2e0393e4a1f10
a3b0e7acb6e0d7e73f5e369a17f367ac7caf83fb
/python/Udemy/Learn_Python_Programming_StepByStep/16_Database_SQLite/pulling data.py
a908c75deb59e48146df2835e10bc32a6420b7ed
[]
no_license
jadedocelot/Bin2rong
f9d35731ca7df50cfba36141d249db2858121826
314b509f7b3b3a6a5d6ce589dbc57a2c6212b3d7
refs/heads/master
2023-03-24T14:03:32.374633
2021-03-19T00:05:24
2021-03-19T00:05:24
285,387,043
0
0
null
null
null
null
UTF-8
Python
false
false
410
py
import sqlite3 conct = sqlite3.connect("database/mydatabase.db") try: cur = conct.cursor() for records in cur.execute("SELECT * FROM student"): print(records) # cur.execute("SELECT name FROM student") # print(cur.fetchmany(3)) # print(cur.fetchall()) # print(cur.fetchone()) except Exception as err: print(err) finally: conct.close() # See CHAPTER README for notes
[ "eabelortega@gmail.com" ]
eabelortega@gmail.com
b4cc31ff92eb9ed40614c2fd26c025ec9077120f
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/387/usersdata/273/107669/submittedfiles/ep2.py
33033fb09115fd60503b0008b74f07c92d2e70db
[]
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
1,536
py
# -*- coding: utf-8 -*- ''' /**********************************************************/ /* Equipe: Fulano de Tal:Leandro Pedro de Freitas e Gustavo henrique */ /* N ́umero de matriculas:381420 e */ /* Exercicio-Programa 2 -- TEMA *Razao aurea /* ECI0007 ou EM0006 (EC/EM) -- 2017 -- Professor: Rafael perazzo */ /* Interpretador: Python vers~ao 3 */ /********************************************************** ''' #COMECE SEU CODIGO NA LINHA ABAIXO. def calcula_valor_absoluto (x): x=((x**2)**0.5) def calcula_pi(m): for i in range(1,m,1): pi0=0 a=2 b=3 c=4 if ((i%2)==0): pi=pi0-(4/(a*b*c)) else: pi=pi0+(4/(a*b*c)) a=a+2 b=b+2 c=c+2 valordopi=pi+3 return(valordopi) def calcula_co_seno(z): for z in range(1,z,1): a=2 deno=2 cosseno=0 if (z%2)==0: while (deno>0): produto=((calcula_valor_absoluto)/(deno)) deno=deno-1 cosseno=cosseno-produto else: while (deno>0): produto=((calcula_valor_absoluto)/(deno)) deno=deno-1 cosseno=cosseno+produto deno=deno+2 a=a+2 cosseno_real=cosseno+1 return(cosseno_real)
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
fbf3c62c164a93fa9c4828bcb8325e94ed813e75
9e65e409106aad6339424a1afac3e75e15b4f488
/0x11-python-network_1/6-post_email.py
69b2654e635444013e91f5cd6642ffd28af4f413
[]
no_license
jfbm74/holbertonschool-higher_level_programming
63fe8e35c94454896324791585fe7b8e01e1c67d
609f18ef7a479fb5dcf1825333df542fc99cec7b
refs/heads/master
2023-03-05T20:44:05.700354
2021-02-10T00:21:54
2021-02-10T00:21:54
259,452,209
0
0
null
null
null
null
UTF-8
Python
false
false
326
py
#!/usr/bin/python3 """ Python script that takes in a URL and an email address, sends a POST request to the passed URL with the email as a parameter """ import requests from sys import argv if __name__ == '__main__': url = argv[1] email = {'email': argv[2]} req = requests.post(url, email) print(req.text)
[ "jfbm74@gmail.com" ]
jfbm74@gmail.com
9151b1b46f2c5b5e9581951a8af9df5a3f4f1f95
b844c72c394b13d9ed4f73222a934f962d6ff187
/src/matching_counts.py
118790fdedcd4c34ee60aad44942be3563c04bce
[]
no_license
curtisbright/sagesat
b9b4c9180c75ce8574217058ffa4e121163ccf36
8fe52609ab6479d9b98a1e6cf2199a4f12c27777
refs/heads/master
2021-01-01T17:52:01.288449
2015-08-19T18:14:26
2015-08-19T18:14:26
41,425,883
0
0
null
null
null
null
UTF-8
Python
false
false
762
py
''' Created on Sep 20, 2014 @author: ezulkosk ''' from common.common import Options from main import run if __name__ == '__main__': TEST_DIR = "../test/matching_counts/" options = Options() options.SHARPSAT=True print("Obtaining counts for hypercube matchings.") for d in range(2,6): d_dir = TEST_DIR + "d" + str(d) + "/" print("Dimension "+ str(d)) spec = d_dir + "matchings" print("\tmatchings: " + str(run(spec, options))) spec = d_dir + "forbidden_matchings" print("\tforbidden matchings: " + str(run(spec, options))) spec = d_dir + "maximal_forbidden_matchings" print("\tmaximal forbidden matchings: " + str(run(spec, options)))
[ "ezulkosk@gsd.uwaterloo.ca" ]
ezulkosk@gsd.uwaterloo.ca
e598bbc2a1a04dda520a9ae42d5eb12de22c2eea
78980891d3137810bf3a3c1bb229966b7f49f0dd
/interestings/asyncio_demos/coro10.py
6c8cc07ed8e8518539a71a7fd1e9aa82e39641db
[]
no_license
miniyk2012/leetcode
204927d3aefc9746070c1bf13abde517c6c16dc0
91ca9cd0df3c88fc7ef3c829dacd4d13f6b71ab1
refs/heads/master
2021-06-17T21:50:31.001111
2021-03-10T11:36:23
2021-03-10T11:36:23
185,042,818
1
0
null
null
null
null
UTF-8
Python
false
false
476
py
import asyncio import time from contextlib import contextmanager async def a(): await asyncio.sleep(3) return 'A' async def b(): await asyncio.sleep(1) return 'B' async def s1(): return await asyncio.gather(a(), b()) @contextmanager def timed(func): start = time.perf_counter() yield asyncio.run(func()) print(f'Cost: {time.perf_counter() - start}') if __name__ == '__main__': with timed(s1) as rv: print(f'Result: {rv}')
[ "yk_ecust_2007@163.com" ]
yk_ecust_2007@163.com
14cfc235ea57ad8c87158c3a105277b32dd89e0b
f3b233e5053e28fa95c549017bd75a30456eb50c
/p38a_input/L3FN/3FN-2I_wat_20Abox/set_1.py
a66fca767f59717be304bfaf4b0ba3facedc7df3
[]
no_license
AnguseZhang/Input_TI
ddf2ed40ff1c0aa24eea3275b83d4d405b50b820
50ada0833890be9e261c967d00948f998313cb60
refs/heads/master
2021-05-25T15:02:38.858785
2020-02-18T16:57:04
2020-02-18T16:57:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
740
py
import os dir = '/mnt/scratch/songlin3/run/p38a/L3FN/wat_20Abox/ti_one-step/3FN_2I/' filesdir = dir + 'files/' temp_prodin = filesdir + 'temp_prod_1.in' temp_pbs = filesdir + 'temp_1.pbs' lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078] for j in lambd: os.chdir("%6.5f" %(j)) workdir = dir + "%6.5f" %(j) + '/' #prodin prodin = workdir + "%6.5f_prod_1.in" %(j) os.system("cp %s %s" %(temp_prodin, prodin)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, prodin)) #PBS pbs = workdir + "%6.5f_1.pbs" %(j) os.system("cp %s %s" %(temp_pbs, pbs)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs)) #submit pbs #os.system("qsub %s" %(pbs)) os.chdir(dir)
[ "songlin3@msu.edu" ]
songlin3@msu.edu
b964a72f0dbb3381a2b723bbe70654e1d5ab14b1
8ca19f1a31070738b376c0370c4bebf6b7efcb43
/office365/directory/protection/riskyusers/activity.py
f84b5aacfd83351b65aacf60389d622975b7a493
[ "MIT" ]
permissive
vgrem/Office365-REST-Python-Client
2ef153d737c6ed5445ba1e446aeaec39c4ef4ed3
cbd245d1af8d69e013c469cfc2a9851f51c91417
refs/heads/master
2023-09-02T14:20:40.109462
2023-08-31T19:14:05
2023-08-31T19:14:05
51,305,798
1,006
326
MIT
2023-08-28T05:38:02
2016-02-08T15:24:51
Python
UTF-8
Python
false
false
201
py
from office365.runtime.client_value import ClientValue class RiskUserActivity(ClientValue): """Represents the risk activites of an Azure AD user as determined by Azure AD Identity Protection."""
[ "vvgrem@gmail.com" ]
vvgrem@gmail.com
af6acf69a5f749171c212ccadb2286cebe501086
1dacbf90eeb384455ab84a8cf63d16e2c9680a90
/Examples/bokeh/plotting/file/bollinger.py
95cb41a56fde8c6e8db94b100473937ab032ef56
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
permissive
wangyum/Anaconda
ac7229b21815dd92b0bd1c8b7ec4e85c013b8994
2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6
refs/heads/master
2022-10-21T15:14:23.464126
2022-10-05T12:10:31
2022-10-05T12:10:31
76,526,728
11
10
Apache-2.0
2022-10-05T12:10:32
2016-12-15T05:26:12
Python
UTF-8
Python
false
false
591
py
import numpy as np from bokeh.plotting import figure, show, output_file # Define Bollinger Bands. upperband = np.random.random_integers(100, 150, size=100) lowerband = upperband - 100 x_data = np.arange(1, 101) # Bollinger shading glyph: band_x = np.append(x_data, x_data[::-1]) band_y = np.append(lowerband, upperband[::-1]) output_file('bollinger.html', title='Bollinger bands (file)') p = figure(x_axis_type='datetime') p.patch(band_x, band_y, color='#7570B3', fill_alpha=0.2) p.title = 'Bollinger Bands' p.plot_height = 600 p.plot_width = 800 p.grid.grid_line_alpha = 0.4 show(p)
[ "wgyumg@mgail.com" ]
wgyumg@mgail.com
3dc9c0e03163ba648da6dd6492a03da3e5d66cb0
824ccee9f5c27f5b3fec0dff710e9c4a181a9747
/atlas_coords/all_sky_phot.py
71562becbd41c1ca68d871cc16caa871a6a2114f
[]
no_license
yoachim/ScratchStuff
1450a2a785c28c209121600072e7ccb2ba47af08
10c490dd1f3c574738ff4ecb71e135180df4724e
refs/heads/master
2020-04-04T07:31:17.017542
2019-07-02T16:51:12
2019-07-02T16:51:12
35,652,984
1
3
null
null
null
null
UTF-8
Python
false
false
2,223
py
import numpy as np import astropy from astropy.io import fits import matplotlib.pylab as plt from astropy.stats import sigma_clipped_stats from photutils import DAOStarFinder, aperture_photometry, CircularAperture, CircularAnnulus # Need to pick up photutils # conda install -c astropy photutils # Following example from http://photutils.readthedocs.io/en/stable/photutils/aperture.html # Let's do an example of generating a catalog of stars from an all-sky image # Collect relevant kwargs # FWHM of stars fwhm = 1.5 # how many sigma above background threshold = 5. # Radius for stellar aperture r_star = 4. # For sky anulus r_in = 6. r_out = 8. # Load up an image and a few header values hdulist = fits.open('02k57699o0526w.fits.fz') mjd = hdulist[1].header['MJD-OBS'] + 0 exptime = hdulist[1].header['EXPTIME'] + 0 image = hdulist[1].data + 0. try: hdulist.close() except: hdulist.close() # crop down image for easy example image = image[500:1000, 1000:1500] # Simple stats of the image maskval = image[0, 0] good = np.where(image != maskval) mean, median, std = sigma_clipped_stats(image[good], sigma=3.0, iters=5) # include a mask mask = np.zeros_like(image, dtype=bool) mask[np.where(image == maskval)] = True # fwhm in pixels, find sources daofind = DAOStarFinder(fwhm=fwhm, threshold=threshold*std) sources = daofind(image - median) # Do aperature phot positions = (sources['xcentroid'], sources['ycentroid']) # aperture for stars apertures = CircularAperture(positions, r=r_star) # sky background anulus annulus_apertures = CircularAnnulus(positions, r_in=r_in, r_out=r_out) apers = [apertures, annulus_apertures] phot_table = aperture_photometry(image, apers, mask=mask) bkg_mean = phot_table['aperture_sum_1'] / annulus_apertures.area() bkg_sum = bkg_mean * apertures.area() final_sum = phot_table['aperture_sum_0'] - bkg_sum phot_table['residual_aperture_sum'] = final_sum from astropy.visualization import SqrtStretch from astropy.visualization.mpl_normalize import ImageNormalize norm = ImageNormalize(stretch=SqrtStretch(), vmin=0, vmax=100) plt.imshow(image, cmap='Greys', origin='lower', norm=norm) apertures.plot(color='blue', lw=1.5, alpha=0.5) plt.savefig('phot_example.png')
[ "yoachim@uw.edu" ]
yoachim@uw.edu
ce0c15a0ad0f852b7ae51ff9ad8119b7ad6c0b84
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2737/8160/259430.py
84b3baed41127949fbe85e854b03ddcffde98b5d
[]
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
183
py
import collections def majorityElement(nums): return [key for key, val in collections.Counter(nums).items() if val > len(nums) // 3] nums = input() print(majorityElement(nums))
[ "1069583789@qq.com" ]
1069583789@qq.com
f895c9359552253b5b8147d97aa07c1c39c028c4
fb28175748fdb497f23e71e9a11c89fdf41b8a11
/level.py
99b3afb2cfe14c3e237dd56e741ad2fd48a74604
[]
no_license
daeken/ygritte
40f571505a7a77769a98c18c45f8793cf87faa4d
0f8bf75f761b40a6c863d589dfe44f189d22ea7e
refs/heads/master
2020-05-20T02:08:31.671031
2011-04-10T21:45:42
2011-04-10T21:45:42
1,563,991
3
1
null
null
null
null
UTF-8
Python
false
false
788
py
from asset import Asset grid = Asset.load('layer0') stars = Asset.load('layer1') class Level(object): levels = {} def __init__(self, game): self.game = game self.bg = Asset.load('layer2_outline', mask='layer2_mask')# % self.levelNumber) stars.maskOff(self.bg) self.i = 0 @staticmethod def spawn(game, number, *args, **kwargs): return Level.levels[number](game, *args, **kwargs) @staticmethod def register(level): Level.levels[level.levelNumber] = level def draw(self, surface): grid.draw(surface, (0, 0), center=False) stars.draw(surface, self.game.worldOff, center=True) self.bg.draw(surface, self.game.worldOff, center=True) self.i += 1 @Level.register class LevelZero(Level): levelNumber = 0 def __init__(self, game): Level.__init__(self, game)
[ "cody.brocious@gmail.com" ]
cody.brocious@gmail.com
7cd0a6131a02f20edef1352a07bec29cbd8a381e
0c98ca0ca250d0dc815813287d732c48c70aa12a
/EXP/run_bar_framed_rectangle_from_scratch.py
becb6e7809018ef3e95c4275f7f7fd715685c547
[]
no_license
AswinVasudevan21/perception
8f00479870ee767963767fc621325c1a96249196
7a6522fdfbb26ec56a682a4cdf41102cbfd6731a
refs/heads/master
2020-07-14T13:54:10.923781
2019-07-23T11:21:23
2019-07-23T11:21:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,937
py
from keras import models from keras import layers from keras import optimizers import keras.applications import keras.callbacks from keras import backend as K from keras.utils.np_utils import to_categorical import sklearn.metrics import cPickle as pickle import numpy as np import os import sys import time import ClevelandMcGill as C EXPERIMENT = sys.argv[1] # f.e. C.Figure12.data_to_framed_rectangles CLASSIFIER = sys.argv[2] # 'LeNet' NOISE = sys.argv[3] # True JOB_INDEX = int(sys.argv[4]) # # # print 'Running', EXPERIMENT, 'with', CLASSIFIER, 'Noise:', NOISE, 'Job Index', JOB_INDEX # # # PROCESS SOME FLAGS # # SUFFIX = '.' if NOISE == 'True': NOISE = True SUFFIX = '_noise.' else: NOISE = False DATATYPE = eval(EXPERIMENT) if os.path.abspath('~').startswith('/n/'): # we are on the cluster PREFIX = '/n/regal/pfister_lab/PERCEPTION/' else: PREFIX = '/home/d/PERCEPTION/' RESULTS_DIR = PREFIX + 'RESULTS_FROM_SCRATCH/' OUTPUT_DIR = RESULTS_DIR + EXPERIMENT + '/' + CLASSIFIER + '/' if not os.path.exists(OUTPUT_DIR): # here can be a race condition try: os.makedirs(OUTPUT_DIR) except: print 'Race condition!', os.path.exists(OUTPUT_DIR) STATSFILE = OUTPUT_DIR + str(JOB_INDEX).zfill(2) + SUFFIX + 'p' MODELFILE = OUTPUT_DIR + str(JOB_INDEX).zfill(2) + SUFFIX + 'h5' print 'Working in', OUTPUT_DIR print 'Storing', STATSFILE print 'Storing', MODELFILE if os.path.exists(STATSFILE) and os.path.exists(MODELFILE): print 'WAIT A MINUTE!! WE HAVE DONE THIS ONE BEFORE!' sys.exit(0) # # # DATA GENERATION # # train_counter = 0 val_counter = 0 test_counter = 0 train_target = 60000 val_target = 20000 test_target = 20000 train_labels = [] val_labels = [] test_labels = [] X_train = np.zeros((train_target, 100, 100), dtype=np.float32) y_train = np.zeros((train_target, 2), dtype=np.float32) X_val = np.zeros((val_target, 100, 100), dtype=np.float32) y_val = np.zeros((val_target, 2), dtype=np.float32) X_test = np.zeros((test_target, 100, 100), dtype=np.float32) y_test = np.zeros((test_target, 2), dtype=np.float32) t0 = time.time() all_counter = 0 while train_counter < train_target or val_counter < val_target or test_counter < test_target: all_counter += 1 data, label, parameters = C.Figure12.generate_datapoint() pot = np.random.choice(3) # sometimes we know which pot is right if label in train_labels: pot = 0 if label in val_labels: pot = 1 if label in test_labels: pot = 2 if pot == 0 and train_counter < train_target: if label not in train_labels: train_labels.append(label) # image = DATATYPE(data) image = image.astype(np.float32) # add noise? if NOISE: image += np.random.uniform(0, 0.05,(100,100)) # safe to add to training X_train[train_counter] = image y_train[train_counter] = label train_counter += 1 elif pot == 1 and val_counter < val_target: if label not in val_labels: val_labels.append(label) image = DATATYPE(data) image = image.astype(np.float32) # add noise? if NOISE: image += np.random.uniform(0, 0.05,(100,100)) # safe to add to training X_val[val_counter] = image y_val[val_counter] = label val_counter += 1 elif pot == 2 and test_counter < test_target: if label not in test_labels: test_labels.append(label) image = DATATYPE(data) image = image.astype(np.float32) # add noise? if NOISE: image += np.random.uniform(0, 0.05,(100,100)) # safe to add to training X_test[test_counter] = image y_test[test_counter] = label test_counter += 1 print 'Done', time.time()-t0, 'seconds (', all_counter, 'iterations)' # # # # # # NORMALIZE DATA IN-PLACE (BUT SEPERATELY) # # X_min = X_train.min() X_max = X_train.max() y_min = y_train.min() y_max = y_train.max() # scale in place X_train -= X_min X_train /= (X_max - X_min) y_train -= y_min y_train /= (y_max - y_min) X_val -= X_min X_val /= (X_max - X_min) y_val -= y_min y_val /= (y_max - y_min) X_test -= X_min X_test /= (X_max - X_min) y_test -= y_min y_test /= (y_max - y_min) # normalize to -.5 .. .5 X_train -= .5 X_val -= .5 X_test -= .5 print 'memory usage', (X_train.nbytes + X_val.nbytes + X_test.nbytes + y_train.nbytes + y_val.nbytes + y_test.nbytes) / 1000000., 'MB' # # # # # # FEATURE GENERATION # # feature_time = 0 if CLASSIFIER == 'VGG19' or CLASSIFIER == 'XCEPTION': X_train_3D = np.stack((X_train,)*3, -1) X_val_3D = np.stack((X_val,)*3, -1) X_test_3D = np.stack((X_test,)*3, -1) print 'memory usage', (X_train_3D.nbytes + X_val_3D.nbytes + X_test_3D.nbytes) / 1000000., 'MB' if CLASSIFIER == 'VGG19': feature_generator = keras.applications.VGG19(include_top=False, input_shape=(100,100,3)) elif CLASSIFIER == 'XCEPTION': feature_generator = keras.applications.Xception(include_top=False, input_shape=(100,100,3)) elif CLASSIFIER == 'RESNET50': print 'Not yet - we need some padding and so on!!!' sys.exit(1) t0 = time.time() # # THE MLP # # MLP = models.Sequential() MLP.add(layers.Flatten(input_shape=feature_generator.output_shape[1:])) MLP.add(layers.Dense(256, activation='relu', input_dim=(100,100,3))) MLP.add(layers.Dropout(0.5)) MLP.add(layers.Dense(2, activation='linear')) # REGRESSION model = keras.Model(inputs=feature_generator.input, outputs=MLP(feature_generator.output)) sgd = optimizers.SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd, metrics=['mse', 'mae']) # MSE for regression # # # TRAINING # # t0 = time.time() callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=0, mode='auto'), \ keras.callbacks.ModelCheckpoint(MODELFILE, monitor='val_loss', verbose=1, save_best_only=True, mode='min')] history = model.fit(X_train_3D, \ y_train, \ epochs=1000, \ batch_size=32, \ validation_data=(X_val_3D, y_val), callbacks=callbacks, verbose=True) fit_time = time.time()-t0 print 'Fitting done', time.time()-t0 # # # PREDICTION # # y_pred = model.predict(X_test_3D) # # # CLEVELAND MCGILL ERROR # MEANS OF LOG ABSOLUTE ERRORS (MLAEs) # MLAE = np.log2(sklearn.metrics.mean_absolute_error(y_pred*100, y_test*100)+.125) # # # STORE # (THE NETWORK IS ALREADY STORED BASED ON THE CALLBACK FROM ABOVE!) # stats = dict(history.history) # 1. the training history # 2. the y_pred and y_test values # 3. the MLAE stats['time'] = feature_time + fit_time stats['y_test'] = y_test stats['y_pred'] = y_pred stats['MLAE'] = MLAE with open(STATSFILE, 'w') as f: pickle.dump(stats, f) print 'MLAE', MLAE print 'Written', STATSFILE print 'Written', MODELFILE print 'Sayonara! All done here.'
[ "haehn@seas.harvard.edu" ]
haehn@seas.harvard.edu
ad8d2f89fbfbfa9db5342a0c79f661cc9644b2d1
bbcaed21db23d08ebf11fabe0c6b8d0ee551a749
/q2_dummy_types/__init__.py
ccc172e8439e27f14d38fa77465ecbed5345f16f
[]
no_license
ebolyen/q2-dummy-types
c34707e2a3e7ef1ad6abf76b1b9fabbf9c7d7222
3ac8f643e5f88a6de2413bebf8fb16c1b3168e4b
refs/heads/master
2021-01-10T22:47:04.455265
2016-10-08T19:20:40
2016-10-08T19:20:40
70,352,411
0
0
null
2016-10-08T19:17:24
2016-10-08T19:17:23
null
UTF-8
Python
false
false
667
py
# ---------------------------------------------------------------------------- # Copyright (c) 2016--, QIIME development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- __version__ = "0.0.1" # noqa # Make the types defined in this plugin importable from the top-level package # so they can be easily imported by other plugins relying on these types. from ._int_sequence import IntSequence1, IntSequence2 from ._mapping import Mapping __all__ = ['IntSequence1', 'IntSequence2', 'Mapping']
[ "jai.rideout@gmail.com" ]
jai.rideout@gmail.com
d39b69be8e6d36394558c1b41133aa034318b78c
9d735842aa4ae0d65b33cd71994142ea80792af5
/scrape_ebi_iedb_input.py
54acc58345dc44c5eb8ac2e69a7d2fc6e40df78b
[]
no_license
saketkc/scrape_ebi
9b5179c9cc45f6e4519732feec9bfaa34126538c
ffe451453bedd9b1aced1bd515bfe3993283809a
refs/heads/master
2021-01-15T12:16:09.599217
2012-05-25T09:13:03
2012-05-25T09:13:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,562
py
from mechanize import Browser, _http from BeautifulSoup import BeautifulSoup import sys import os def get_data_from_ebi(*arg): br = Browser() args = arg[0] filename = args[0] br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.open('http://iedb.ebi.ac.uk/tools/ElliPro/iedb_input') br.select_form(name='predictionForm') br.form['protein_type'] = ['structure',] if os.path.exists(filename): br.form.add_file(open(filename), 'text/plain', filename) else: br.form['pdbId'] = filename.split('.')[0] submit_response = br.submit(name='Submit', label='Submit') html = submit_response.read() soup = BeautifulSoup(html) all_tables = soup.findAll("table",cellspacing=1) if len(all_tables) == 1: table = soup.find("table",cellspacing=1) all_protein_chains = {} for row in table.findAll('tr')[1:-1]: columns = row.findAll('td') number = columns[1] chain = columns[2] number_of_residues = columns[3] all_protein_chains[number.string] = chain.string br.select_form(name='selectChainForm') br.form['chainIndex'] = [None] * (len(args)-1) for index,seqchoice in enumerate(args[1:]): for k,v in all_protein_chains.iteritems(): if str(v) == str(seqchoice): choice = k br.form['chainIndex'][index] = (str(int(choice)-1)) submit_response = br.submit().read() soup = BeautifulSoup(submit_response) for index,tables in enumerate(soup.findAll("table",cellspacing=1)[1:3]): if index == 0: print "Predicted Linear Epitope(s): " for row in tables.findAll('tr'): columns = row.findAll('td') output = "" for column in columns[:-1]: output += column.string + " " print output if index == 1: print "Predicted Discontinous Epitope(s): " for row in tables.findAll('tr')[1:]: columns = row.findAll('td') output = "" for column in columns[:-1]: if column.string == None: column = column.find('div') output += column.string + " " print output if __name__ == "__main__": get_data_from_ebi(sys.argv[1:])
[ "saketkc@gmail.com" ]
saketkc@gmail.com
ff4d51fae8a38111bc47df0a15cfa915e98ddaff
02e23da0431623db86c8138bda350a1d526d4185
/Archivos Python Documentos/Graficas/.history/TRABAJO_SPT_v3_20200223200731.py
e172ba3b981e7ffe2cd9bfa36a01f100e4a315d1
[]
no_license
Jaamunozr/Archivos-python
d9996d3d10ff8429cd1b4c2b396016a3a5482889
1f0af9ba08f12ac27e111fcceed49bbcf3b39657
refs/heads/master
2022-08-05T14:49:45.178561
2022-07-13T13:44:39
2022-07-13T13:44:39
244,073,267
0
0
null
null
null
null
UTF-8
Python
false
false
5,247
py
import os import pylab as pl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np #------------ #from mpl_toolkits.mplot3d.axes3d import get_test_data #------------- os.system("clear") fig = pl.figure() axx = Axes3D(fig) raiz=np.sqrt ln=np.log puntoX=float(0) puntoY=float(0) #puntoX=float(input("Seleccione la coordenada en X donde desea calcular el potencial: ")) #puntoY=float(input("Seleccione la coordenada en Y donde desea calcular el potencial: ")) print("Calculando ...") #------------------------------------------------------------------------------ Xa = np.arange(-10, 10, 0.1) #Rango de coordenadas de X Ya = np.arange(-10, 10, 0.1) #Rango de coordenadas de Y l = 2 #Longitud del electrodo [m] rho= 100 #Resistividad de terrreno [Ohm/m] Ik=200 #Corriente de falla [A] (Total) Rad=0.01 #Radio del electrodo [m] Electrodos=8 #Número de electrodos Pos1=4 #Posición 1 en Y para analisis de grafica 2D Pos2=0 #Posición 2 en Y para analisis de grafica 2D #Posición de los electrodos P=np.array([ [-4,-4], #Electrodo A [0,-4], #Electrodo B [4,-4], #Electrodo C [-4,0], #Electrodo D [4,0], #Electrodo E [-4,4], #Electrodo F [0,4], #Electrodo G [4,4] #Electrodo H ]) #------------------------------------------------------------------------------ E=Electrodos-1 ik=Ik/Electrodos Vt=np.zeros((np.count_nonzero(Xa),np.count_nonzero(Ya))) m=np.zeros((Electrodos,1)) V=np.zeros((Electrodos,1)) k=0 m2=np.zeros((Electrodos,1)) V2=np.zeros((Electrodos,1)) #------------------------------------------------------------------------------ #Cálculo del punto ingresado i=0 while i<=E: m2[i][0] =round(raiz((((P[i][0])-puntoX)**2)+(((P[i][1])-puntoY)**2)),4) o,u=((P[i][0])-puntoX),((P[i][1])-puntoY) if ((o ==0) and (u==0)) or (m2[i][0]==0): #print("Elementos de matriz",k,t, "x,y",P[i][0],P[i][1],"punto de eje",X,Y ) m2[i][0]=Rad V2[i][0] =ln((l+raiz((m2[i][0])**2+l**2))/(m2[i][0])) i += 1 Vt2=(np.sum(V2)*(rho*ik))/(2*np.pi*l) print("El potencial en el punto (",puntoX,",",puntoY,"), es de",round(Vt2,3),"[V]") print("Calculando el resto de operaciones..") #------------------------------------------------------------------------------ #Cálculo de la mall Vxy = [0] * (np.count_nonzero(Ya)) while k<np.count_nonzero(Ya): Y=round(Ya[k],3) t=0 while t<np.count_nonzero(Xa): X=round(Xa[t],3) i=0 while i<=E: m[i][0] =round(raiz((((P[i][0])-X)**2)+(((P[i][1])-Y)**2)),4) o,u=((P[i][0])-X),((P[i][1])-Y) if ((o ==0) and (u==0)) or (m[i][0]==0): #print("Elementos de matriz",k,t, "x,y",P[i][0],P[i][1],"punto de eje",X,Y ) m[i][0]=Rad V[i][0] =ln((l+raiz((m[i][0])**2+l**2))/(m[i][0])) i += 1 Vt[k][t]=np.sum(V) if Y==Pos1: Vxa=Vt[k] if Y==Pos2: Vxb=Vt[k] if Y==X: Vxy.insert(k,Vt[k][t]) t +=1 k +=1 Vtt=(Vt*(rho*ik))/(2*np.pi*l) Vxa=(Vxa*(rho*ik))/(2*np.pi*l) Vxb=(Vxb*(rho*ik))/(2*np.pi*l) print ("Número de elementos por eje:",np.count_nonzero(Xa)) aa=np.where(np.amax(Vtt) == Vtt) print ("Valor máximo de tensión:",round(Vtt[::].max(),3),"[V], en posición: (",round(Xa[aa[0][0]],2),",",round(Ya[aa[1][0]],2),")") bb=np.where(np.amin(Vtt) == Vtt) print ("Valor mínimo de tensión:",round(Vtt[::].min(),3),"[V], en posición: (",round(Xa[bb[0][0]],2),",",round(Ya[bb[1][0]],2),")") print ("Número de elemmentos de Vt:",np.count_nonzero(Vtt)) print ("Elementos de Xa al cuadrado:",np.count_nonzero(Xa)**2) X, Y = np.meshgrid(Xa, Ya) print ("Nuevo número de elementos de X y Y:",np.count_nonzero(X)) #------------------------------------------------------------------------------ # GRAFICAS # configurar una figura dos veces más alta que ancha fig = plt.figure(figsize=plt.figaspect(0.5)) # Primera imagen a imprimir ax1 = fig.add_subplot(1, 2, 1, projection='3d') surf = ax1.plot_surface(X, Y, Vtt, cmap = cm.get_cmap("Spectral"))#, antialiased=False) # Customize the z axis. ax1.set_zlim(300, 1800) fig.colorbar(surf) #------------------------------------------------------------------------------ #Graficas en 2D #------------------------------------------------------------------------------ #Eje X1: # Second subplot ax2 = fig.add_subplot(1, 2, 2) x1=Xa ax2.title.set_text('Curvas de Nivel.') ax2.plot(x1, Vxa, color="blue", linewidth=1.0, linestyle="-") ax2.plot(x1, Vxb, color="red", linewidth=1.0, linestyle="-") ax2.plot(x1, Vxy, color="green", linewidth=1.0, linestyle="-") plt.show() """ pl.figure(figsize=(16, 8), dpi=100) pl.subplot(1, 1, 1) pl.plot(x1, Vxa, color="blue", linewidth=1.0, linestyle="-") pl.plot(x1, Vxb, color="green", linewidth=1.0, linestyle="-") pl.xlim(-10, 10) pl.xticks(np.linspace(-10, 10, 17, endpoint=True)) pl.ylim(200.0, 1700.0) pl.yticks(np.linspace(200, 1700, 5, endpoint=True)) #pl.pause(100) """
[ "jaamunozr@gmail.com" ]
jaamunozr@gmail.com
938f1654252a9fbc25a0c686035dd7efd7cbc660
2d4380518d9c591b6b6c09ea51e28a34381fc80c
/CIM16/IEC61970/Protection/RecloseSequence.py
549c094a7cdff30fe983ecb50cfff2a768e9c918
[ "MIT" ]
permissive
fran-jo/PyCIM
355e36ae14d1b64b01e752c5acd5395bf88cd949
de942633d966bdf2bd76d680ecb20517fc873281
refs/heads/master
2021-01-20T03:00:41.186556
2017-09-19T14:15:33
2017-09-19T14:15:33
89,480,767
0
1
null
2017-04-26T12:57:44
2017-04-26T12:57:44
null
UTF-8
Python
false
false
3,250
py
# Copyright (C) 2010-2011 Richard Lincoln # # 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 CIM16.IEC61970.Core.IdentifiedObject import IdentifiedObject class RecloseSequence(IdentifiedObject): """A reclose sequence (open and close) is defined for each possible reclosure of a breaker.A reclose sequence (open and close) is defined for each possible reclosure of a breaker. """ def __init__(self, recloseStep=0, recloseDelay=0.0, ProtectedSwitch=None, *args, **kw_args): """Initialises a new 'RecloseSequence' instance. @param recloseStep: Indicates the ordinal position of the reclose step relative to other steps in the sequence. @param recloseDelay: Indicates the time lapse before the reclose step will execute a reclose. @param ProtectedSwitch: A breaker may have zero or more automatic reclosures after a trip occurs. """ #: Indicates the ordinal position of the reclose step relative to other steps in the sequence. self.recloseStep = recloseStep #: Indicates the time lapse before the reclose step will execute a reclose. self.recloseDelay = recloseDelay self._ProtectedSwitch = None self.ProtectedSwitch = ProtectedSwitch super(RecloseSequence, self).__init__(*args, **kw_args) _attrs = ["recloseStep", "recloseDelay"] _attr_types = {"recloseStep": int, "recloseDelay": float} _defaults = {"recloseStep": 0, "recloseDelay": 0.0} _enums = {} _refs = ["ProtectedSwitch"] _many_refs = [] def getProtectedSwitch(self): """A breaker may have zero or more automatic reclosures after a trip occurs. """ return self._ProtectedSwitch def setProtectedSwitch(self, value): if self._ProtectedSwitch is not None: filtered = [x for x in self.ProtectedSwitch.RecloseSequences if x != self] self._ProtectedSwitch._RecloseSequences = filtered self._ProtectedSwitch = value if self._ProtectedSwitch is not None: if self not in self._ProtectedSwitch._RecloseSequences: self._ProtectedSwitch._RecloseSequences.append(self) ProtectedSwitch = property(getProtectedSwitch, setProtectedSwitch)
[ "fran_jo@hotmail.com" ]
fran_jo@hotmail.com
0aa2a6a5d89aa348a47de4346965acb29112a90e
0dcce6da7adc3df08038fba39ec663aa2d6d62ab
/ch2-library-app-and-api/api/views.py
128114ffe645895bd9ad2f34635d9ae726974476
[ "MIT" ]
permissive
anectto/apidjangostudy
1e82e1dc8a7775ad18841372cfdad8d0408ad83f
c8636d54b65e3fbd74e4b3949951cc8a5d681870
refs/heads/master
2023-05-29T04:58:54.884817
2023-03-15T23:06:48
2023-03-15T23:06:48
167,802,649
0
0
MIT
2023-05-22T21:47:50
2019-01-27T11:47:31
Python
UTF-8
Python
false
false
221
py
from rest_framework import generics from books.models import Book from .serializers import BookSerializer class BookAPIView(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer
[ "will@wsvincent.com" ]
will@wsvincent.com
f4f635b18dc05411dfc2d9abc7e11b209f9c777c
ef998914b19f34f8f85cd784b6470147d73a93e0
/job_task/Value_Pitch_Assingment/scrapy-selenium-splash-python/SCI/spiders/scrapy_sel.py
95feaebe678a6566ab3909da624ae97e22af5941
[]
no_license
dilipksahu/Web_Scraping_Using_Python
9f586704a779fda551c5e3d15902591648663870
e6d3031f89b1b5d4bfa0377c11e87037772c460d
refs/heads/master
2023-01-30T14:36:00.702440
2020-12-17T16:10:25
2020-12-17T16:10:25
316,200,913
1
0
null
null
null
null
UTF-8
Python
false
false
2,433
py
# -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector from selenium import webdriver from selenium.webdriver.chrome.options import Options from shutil import which class CoinSpiderSelenium(scrapy.Spider): name = 'case_status' allowed_domains = ['www.main.sci.gov.in'] start_urls = [ 'http://main.sci.gov.in/case-status' ] def __init__(self): chrome_options = Options() chrome_options.add_argument('--headless') chrome_path = which("chromedriver") driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options) driver.set_window_size(1920, 1080) driver.implicitly_wait(0.5) driver.get("https://main.sci.gov.in/case-status") captcha_text = driver.find_element_by_xpath("(//font)[4]").text print("Captcha===========>",captcha_text) captcha_input = driver.find_element_by_id("ansCaptcha") captcha_input.send_keys(captcha_text) diary_input = driver.find_element_by_xpath("//input[@id='CaseDiaryNumber']") diary_input.send_keys("1") year_input = driver.find_element_by_xpath("//select[@id='CaseDiaryYear']") year_input.send_keys(f"2020") submit_btn = driver.find_element_by_xpath("//input[@id='getCaseDiary']") submit_btn.click() self.html = driver.page_source driver.close() def parse(self, response): resp = Selector(text=self.html) print(resp) case_details = resp.xpath("(//table)[3]/tbody/tr") for case_detail in case_details: print(case_detail) yield { 'Diary No.': case_detail.xpath(".//td[2]/div/font/text()").get(), 'Case No.': case_detail.xpath(".//td[2]/div/text()").get(), 'Present/Last Listed On': case_detail.xpath(".//td[2]/b/font/text()").get(), 'Status/Stage': case_detail.xpath(".//td[2]/font/text()").get(), 'Category': case_detail.xpath(".//td[2]/text()").get(), 'Act': case_detail.xpath(".//td[2]/text()").get(), 'Petitioner(s)': case_detail.xpath(".//td[2]/p/text()").get(), 'Respondent(s)': case_detail.xpath(".//td[2]/p/text()").get(), 'Pet. Advocate(s)': case_detail.xpath(".//td[2]/p/text()").get(), }
[ "sahud048@gmail.com" ]
sahud048@gmail.com
ff10e9f2710cb3dc53121976e7b8d53856854d66
3784495ba55d26e22302a803861c4ba197fd82c7
/venv/lib/python3.6/site-packages/nltk/ccg/logic.py
b89bea9d8a08b7fccd7c58dfcdcb431f27dcecea
[ "MIT" ]
permissive
databill86/HyperFoods
cf7c31f5a6eb5c0d0ddb250fd045ca68eb5e0789
9267937c8c70fd84017c0f153c241d2686a356dd
refs/heads/master
2021-01-06T17:08:48.736498
2020-02-11T05:02:18
2020-02-11T05:02:18
241,407,659
3
0
MIT
2020-02-18T16:15:48
2020-02-18T16:15:47
null
UTF-8
Python
false
false
1,806
py
# Natural Language Toolkit: Combinatory Categorial Grammar # # Copyright (C) 2001-2019 NLTK Project # Author: Tanin Na Nakorn (@tanin) # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Helper functions for CCG semantics computation """ from nltk.sem.logic import * def compute_type_raised_semantics(semantics): core = semantics parent = None while isinstance(core, LambdaExpression): parent = core core = core.term var = Variable("F") while var in core.free(): var = unique_variable(pattern=var) core = ApplicationExpression(FunctionVariableExpression(var), core) if parent is not None: parent.term = core else: semantics = core return LambdaExpression(var, semantics) def compute_function_semantics(function, argument): return ApplicationExpression(function, argument).simplify() def compute_composition_semantics(function, argument): assert isinstance(argument, LambdaExpression), ( "`" + str(argument) + "` must be a lambda expression" ) return LambdaExpression( argument.variable, ApplicationExpression(function, argument.term).simplify() ) def compute_substitution_semantics(function, argument): assert isinstance(function, LambdaExpression) and isinstance( function.term, LambdaExpression ), ("`" + str(function) + "` must be a lambda expression with 2 arguments") assert isinstance(argument, LambdaExpression), ( "`" + str(argument) + "` must be a lambda expression" ) new_argument = ApplicationExpression( argument, VariableExpression(function.variable) ).simplify() new_term = ApplicationExpression(function.term, new_argument).simplify() return LambdaExpression(function.variable, new_term)
[ "luis20dr@gmail.com" ]
luis20dr@gmail.com
c128b869ed0e8a8ddf5844d2ad95701ad963f881
8090fe014aad86878636a6d8a1ccc59a81d5d6d0
/EPROM_Emulator/directory_node.py
7ecec3164461e4eaf8db92ae08b089e586c381d8
[ "MIT" ]
permissive
hubs2545/Adafruit_Learning_System_Guides
ad5593027a9403f48c3b9fc820ba73e7ea2bd5af
1f743401b2dc18724d867a31aaf49273abd5ec0d
refs/heads/master
2020-03-18T17:11:40.107775
2018-05-25T20:14:02
2018-05-25T20:14:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,330
py
""" The MIT License (MIT) Copyright (c) 2018 Dave Astels 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. -------------------------------------------------------------------------------- Manage a directory in the file system. """ import os class DirectoryNode(object): """Display and navigate the SD card contents""" def __init__(self, display, parent=None, name="/"): """Initialize a new instance. :param adafruit_ssd1306.SSD1306 on: the OLED instance to display on :param DirectoryNode below: optional parent directory node :param string named: the optional name of the new node """ self.display = display self.parent = parent self.name = name self.files = [] self.top_offset = 0 self.old_top_offset = -1 self.selected_offset = 0 self.old_selected_offset = -1 def __cleanup(self): """Dereference things for speedy gc.""" self.display = None self.parent = None self.name = None self.files = None return self def __is_dir(self, path): """Determine whether a path identifies a machine code bin file. :param string path: path of the file to check """ if path[-2:] == "..": return False try: os.listdir(path) return True except OSError: return False def __sanitize(self, name): """Nondestructively strip off a trailing slash, if any, and return the result. :param string name: the filename """ if name[-1] == "/": return name[:-1] return name def __path(self): """Return the result of recursively follow the parent links, building a full path to this directory.""" if self.parent: return self.parent.__path() + os.sep + self.__sanitize(self.name) return self.__sanitize(self.name) def __make_path(self, filename): """Return a full path to the specified file in this directory. :param string filename: the name of the file in this directory """ return self.__path() + os.sep + filename def __number_of_files(self): """The number of files in this directory, including the ".." for the parent directory if this isn't the top directory on the SD card.""" self.__get_files() return len(self.files) def __get_files(self): """Return a list of the files in this directory. If this is not the top directory on the SD card, a ".." entry is the first element. Any directories have a slash appended to their name.""" if len(self.files) == 0: self.files = os.listdir(self.__path()) self.files.sort() if self.parent: self.files.insert(0, "..") for index, name in enumerate(self.files, start=1): if self.__is_dir(self.__make_path(name)): self.files[index] = name + "/" def __update_display(self): """Update the displayed list of files if required.""" if self.top_offset != self.old_top_offset: self.__get_files() self.display.fill(0) for i in range(self.top_offset, min(self.top_offset + 4, self.__number_of_files())): self.display.text(self.files[i], 10, (i - self.top_offset) * 8) self.display.show() self.old_top_offset = self.top_offset def __update_selection(self): """Update the selected file lighlight if required.""" if self.selected_offset != self.old_selected_offset: if self.old_selected_offset > -1: self.display.text(">", 0, (self.old_selected_offset - self.top_offset) * 8, 0) self.display.text(">", 0, (self.selected_offset - self.top_offset) * 8, 1) self.display.show() self.old_selected_offset = self.selected_offset def __is_directory_name(self, filename): """Is a filename the name of a directory. :param string filename: the name of the file """ return filename[-1] == '/' @property def selected_filename(self): """The name of the currently selected file in this directory.""" self.__get_files() return self.files[self.selected_offset] @property def selected_filepath(self): """The full path of the currently selected file in this directory.""" return self.__make_path(self.selected_filename) def force_update(self): """Force an update of the file list and selected file highlight.""" self.old_selected_offset = -1 self.old_top_offset = -1 self.__update_display() self.__update_selection() def down(self): """Move down in the file list if possible, adjusting the selected file indicator and scrolling the display as required.""" if self.selected_offset < self.__number_of_files() - 1: self.selected_offset += 1 if self.selected_offset == self.top_offset + 4: self.top_offset += 1 self.__update_display() self.__update_selection() def up(self): """Move up in the file list if possible, adjusting the selected file indicator and scrolling the display as required.""" if self.selected_offset > 0: self.selected_offset -= 1 if self.selected_offset < self.top_offset: self.top_offset -= 1 self.__update_display() self.__update_selection() def click(self): """Handle a selection and return the new current directory. If the selected file is the parent, i.e. "..", return to the parent directory. If the selected file is a directory, go into it.""" if self.selected_filename == "..": if self.parent: p = self.parent p.force_update() self.__cleanup() return p elif self.__is_directory_name(self.selected_filename): new_node = DirectoryNode(self.display, self, self.selected_filename) new_node.force_update() return new_node return self
[ "dastels@daveastels.com" ]
dastels@daveastels.com
7ec35b7afd7de673969f2d0e09a32e4e2ed7e5be
ceead28beb1ea6cb56a2bb4472bc1d2396b39e6f
/gen_basis_helpers/lammps_interface/unit_tests/utests_misc_objs.py
3b444bb7d9e73c210ba707c582f3bce01cb96999
[]
no_license
RFogarty1/plato_gen_basis_helpers
9df975d4198bff7bef80316527a8086b6819d8ab
8469a51c1580b923ca35a56811e92c065b424d68
refs/heads/master
2022-06-02T11:01:37.759276
2022-05-11T12:57:40
2022-05-11T12:57:40
192,934,403
3
0
null
null
null
null
UTF-8
Python
false
false
5,448
py
import collections import unittest import unittest.mock as mock import gen_basis_helpers.lammps_interface.misc_objs as tCode class TestNVTEnsemble(unittest.TestCase): def setUp(self): self.startTemp = 300 self.finalTemp = 500 self.dampTime = 200 self.thermostat = "Nose-Hoover" self.numbFmt = "{:.1f}" self.createTestObjs() def createTestObjs(self): currKwargs = {"thermostat":self.thermostat, "endTemp":self.finalTemp, "dampTime":self.dampTime, "numbFmt":self.numbFmt} self.testObjA = tCode.NVTEnsemble(self.startTemp, **currKwargs) def testExpStrFromSimpleOptsA(self): expStr = "all nvt temp 300.0 500.0 200.0" actStr = self.testObjA.fixStr self.assertEqual(expStr, actStr) def testRaisesIfDampTimeNotSet(self): self.dampTime = None self.createTestObjs() with self.assertRaises(ValueError): self.testObjA.fixStr class TestNPTEnsemble(unittest.TestCase): def setUp(self): self.startTemp = 300 self.finalTemp = 500 self.dampTimeTemp = 200 self.pressureDims = "z" self.startPressure = 10 self.endPressure = 20 self.dampTimePressure = 2000 self.numbFmtTemp = "{:.2f}" self.numbFmtPressure = "{:.2f}" self.numbFmtTime = "{:.2f}" self.numbFmtAll = "{:.2f}" self.createTestObjs() def createTestObjs(self): kwargDict = {"pressureDims":self.pressureDims, "endTemp":self.finalTemp, "endPressure":self.endPressure, "dampTimeTemp":self.dampTimeTemp, "dampTimePressure":self.dampTimePressure, "numbFmtTime":self.numbFmtTime, "numbFmtPressure":self.numbFmtPressure, "numbFmtTemp":self.numbFmtTemp} self.testObjA = tCode.NPTEnsembleNoseHooverStandard(self.startTemp, self.startPressure, **kwargDict) def testExpStrFromSimpleOptsA(self): expStr = "all npt temp 300.00 500.00 200.00 z 10.00 20.00 2000.00" actStr = self.testObjA.fixStr self.assertEqual(expStr, actStr) def testRaiseIfPressureDampTimeNotSet(self): self.dampTimePressure = None self.createTestObjs() with self.assertRaises(ValueError): self.testObjA.fixStr def testRaisesIfTempDampTimeNotSet(self): self.dampTimeTemp = None self.createTestObjs() with self.assertRaises(ValueError): self.testObjA.fixStr class TestVelocityRescalingObj(unittest.TestCase): def setUp(self): self.groupId = "groupA" self.nEvery = 5 self.tempStart = 340 self.tempEnd = None self.maxDeviation = 50 self.fraction = 1 self.createTestObjs() def createTestObjs(self): currKwargs = {"groupId":self.groupId, "nEvery":self.nEvery, "tempStart":self.tempStart, "tempEnd":self.tempEnd, "maxDeviation":self.maxDeviation, "fraction":self.fraction} self.testObjA = tCode.RescaleVelocitiesSimple(**currKwargs) def testExpectedA(self): expStr = "groupA temp/rescale 5 340.00 340.00 50.00 1.00" actStr = self.testObjA.fixStr self.assertEqual(expStr, actStr) class TestCombChargeEquilibrationObj(unittest.TestCase): def setUp(self): self.groupId = "Mg" self.nEvery = 75 self.precision = 1e-3 self.createTestObjs() def createTestObjs(self): kwargDict = {"groupId":self.groupId, "nEvery":self.nEvery, "precision":self.precision} self.testObjA = tCode.CombChargeNeutralisationOpts(**kwargDict) def testExpStrFromSimpleOptsA(self): expStr = "Mg qeq/comb 75 0.00100" actStr = self.testObjA.fixStr self.assertEqual(expStr,actStr) class TestAtomGroupByTypesObj(unittest.TestCase): def setUp(self): self.groupId = "water" self.atomTypes = [1,2] self.createTestObjs() def createTestObjs(self): currArgs = [self.groupId, self.atomTypes] self.testObjA = tCode.AtomGroupByType(*currArgs) def testExpStrFromSimpleOptsA(self): expStr = "water type 1 2" actStr = self.testObjA.groupStr self.assertEqual(expStr,actStr) class TestCreateVelocityObj(unittest.TestCase): def setUp(self): self.temp = 400 self.seed = 300 self.dist = "fake_dist" self.group = "fake_group" self.createTestObjs() def createTestObjs(self): currKwargs = {"seed":self.seed, "group":self.group, "dist":self.dist} self.testObjA = tCode.VelocityCreateCommObj(self.temp, **currKwargs) def testExpectedStrFromSimpleOptsA(self): expStr = "fake_group create 400.0 300 dist fake_dist" actStr = self.testObjA.commandStr self.assertEqual(expStr,actStr) class TestDumpObjStandard(unittest.TestCase): def setUp(self): self.everyNSteps = 30 self.groupId = "fake_group" self.dumpType = "atom" self.fileExt = "lammpstrj" self.scale = True self.createTestObjs() def createTestObjs(self): currKwargs = {"groupId":self.groupId, "dumpType":self.dumpType, "fileExt":self.fileExt, "scale":self.scale} self.testObjA = tCode.DumpCommObjStandard(self.everyNSteps, **currKwargs) def testExpectedDictFromSimpleOptsA(self): currArgs = [ ["dump","myDump fake_group atom 30 dump.lammpstrj"], ["dump_modify", "myDump scale yes"] ] expDict = collections.OrderedDict(currArgs) actDict = self.testObjA.commandDict self.assertEqual(expDict,actDict) class TestReflectiveWallFaceObj(unittest.TestCase): def setUp(self): self.face = "xlo" self.groupId = "fake_group" self.createTestObjs() def createTestObjs(self): self.testObjA = tCode.ReflectiveWallFace(self.face, groupId=self.groupId) def testExpectedFixCommandFromDictA(self): expStr = "fake_group wall/reflect xlo EDGE" actStr = self.testObjA.fixStr self.assertEqual(expStr,actStr)
[ "richard.m.fogarty@gmail.com" ]
richard.m.fogarty@gmail.com
6aab3ee55ffd45abd7f2608eec839c1371b7d460
a702fb476539272b78328f64a3a49c1012ac3ed4
/django_slack/utils.py
ee02e313e45081ff2fab63a801ba9d3356d3ca78
[ "BSD-3-Clause" ]
permissive
lamby/django-slack
7f8dea40e5b3cad93f2e207b2815327993743774
5b92410fadc1a91b9415c0991f0ff2547cd633c7
refs/heads/master
2023-03-10T23:54:17.789584
2023-03-02T08:07:43
2023-03-02T08:07:43
27,838,503
250
88
BSD-3-Clause
2023-03-01T15:08:41
2014-12-10T20:34:18
Python
UTF-8
Python
false
false
1,626
py
import json from django.utils.module_loading import import_string from .exceptions import LABEL_TO_EXCEPTION, SlackException from .app_settings import app_settings class Backend(object): def send(self, url, message_data): raise NotImplementedError() def validate(self, content_type, content, message_data): if content_type.startswith('application/json'): result = json.loads(content) if not result['ok']: klass = LABEL_TO_EXCEPTION.get(result['error'], SlackException) raise klass(result['error'], message_data) return result elif content != 'ok': raise SlackException(content, message_data) return content def get_backend(name=None): """ Wrap the backend in a function to not load it at import time. ``get_backend()`` caches the backend on first call. :param name: optional string name for backend, otherwise take from settings :type name: str or unicode or None """ # Function's backend is initially NoneType on module import (see below) loaded_backend = get_backend.backend # Load the backend if we have a provided name, or if this function's # backend is still NoneType if name or not loaded_backend: loaded_backend = import_string(name or app_settings.BACKEND)() # If the backend hasn't been cached yet, and we didn't get a custom # name passed in, cache the backend if not (get_backend.backend or name): get_backend.backend = loaded_backend return loaded_backend get_backend.backend = None
[ "chris@chris-lamb.co.uk" ]
chris@chris-lamb.co.uk
4b921124dd541cdc0e677d64df53898e563848b5
00fe1823bbadc9300e4fec42ca1d12dfbd4bcde9
/Dictionary/11.py
d7986a4e30747730ee497810d2d9c9568de2029b
[]
no_license
monteua/Python
6b36eb01959f34ccaa2bb9044e2e660383ed7695
64b6154d9f59e1e2dbe033e5b9f246734b7d4064
refs/heads/master
2020-07-05T07:29:51.250343
2018-02-09T11:09:51
2018-02-09T11:09:51
74,122,698
3
0
null
null
null
null
UTF-8
Python
false
false
258
py
''' Write a Python program to multiply all the items in a dictionary. ''' dict1 = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49} print ("Old dictionary:", dict1) for key, value in dict1.items(): dict1[key] = value * 10 print ("New dictionary:", dict1)
[ "arximed.monte@gmail.com" ]
arximed.monte@gmail.com
ce50ec568accdb678d6f38382a3e15cb9984e4ee
fc678a0a5ede80f593a29ea8f43911236ed1b862
/380-InsertDeleteGetRandomO(1).py
7f654b9e925fa8143a6b015241c31f51b8b8f50a
[]
no_license
dq-code/leetcode
4be0b1b154f8467aa0c07e08b5e0b6bd93863e62
14dcf9029486283b5e4685d95ebfe9979ade03c3
refs/heads/master
2020-12-13T15:57:30.171516
2017-11-07T17:43:19
2017-11-07T17:43:19
35,846,262
0
0
null
null
null
null
UTF-8
Python
false
false
1,224
py
import random class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.map = dict() self.size = 0 def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool """ if val not in self.map: self.size += 1 map[val] = self.size return True return False def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ if val in self.map: del self.map[val] self.size -= 1 return True return False def getRandom(self): """ Get a random element from the set. :rtype: int """ return random.choice(self.map.keys()) # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
[ "dengqianwork@gmail.com" ]
dengqianwork@gmail.com
766be0bacab93658e605892e12eb75d5ac244ee7
0c656371d4d38b435afb7e870c719fe8bed63764
/levels/migrations/0003_space_variety.py
1efda5ef876ba0f4c06e864425969a5e529e9b6e
[]
no_license
enias-oliveira/parking-lot
cfbe5ca91dcb949e60f04cd26137260f5a9dba36
a54f5ca7b7d78bfc1a9b3c389729da14899d4048
refs/heads/master
2023-05-07T08:48:59.288672
2021-05-18T19:52:46
2021-05-18T19:52:46
369,363,475
0
0
null
null
null
null
UTF-8
Python
false
false
521
py
# Generated by Django 3.2.2 on 2021-05-13 21:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('levels', '0002_rename_motorcylce_spaces_level_motorcycle_spaces'), ] operations = [ migrations.AddField( model_name='space', name='variety', field=models.CharField(choices=[('car', 'car'), ('motorcycle', 'motorcycle')], default='car', max_length=255), preserve_default=False, ), ]
[ "eniasoliveira27@gmail.com" ]
eniasoliveira27@gmail.com
424ca5b9877e60a4512eeca85195255714fa43eb
bc6b561958649c391c159d4dd3363c60eeabc7e4
/mayan/apps/documents/migrations/0051_documentpage_enabled.py
5835be769bcd26e022c28f01b95c5af6790dcfc5
[ "Apache-2.0" ]
permissive
chrisranjana/Mayan-EDMS
37deb105cda268768fea502491ae875ff905e0e9
34b414ce49a2eb156e27dc1a2915e52121c9d1b7
refs/heads/master
2020-12-22T13:50:41.263625
2020-01-28T18:45:24
2020-01-28T18:45:24
236,804,825
0
1
NOASSERTION
2020-01-28T18:12:53
2020-01-28T18:12:52
null
UTF-8
Python
false
false
411
py
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0050_auto_20190725_0451'), ] operations = [ migrations.AddField( model_name='documentpage', name='enabled', field=models.BooleanField(default=True, verbose_name='Enabled'), ), ]
[ "roberto.rosario@mayan-edms.com" ]
roberto.rosario@mayan-edms.com
277ea298bd69c7999327b07b0015aa1e11d93b0e
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03402/s642521958.py
7fcbd198121b2c295ef6f8a6e34080150121ad63
[]
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
372
py
a,b = map(int, input().split()) ans = [['.' for i in range(50)]+['#' for i in range(50)]for j in range(100)] x,y = 0,51 while a>1: ans[x][y] = '.' y+=2 if y>99: x+=2 y=51 a-=1 x,y = 0,0 while b>1: ans[x][y] = '#' y+=2 if y>48: x+=2 y=0 b-=1 print(100,100) for i in range(100): print(''.join(ans[i]))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
840e0ebac008e76101216598b6ca7a9eb40a58eb
76f59c245744e468577a293a0b9b078f064acf07
/287.find-the-duplicate-number.py
0d410826d8b60f50737d2b511468b0a6a9a88f79
[]
no_license
satoshun-algorithm-example/leetcode
c3774f07e653cf58640a6e7239705e58c5abde82
16b39e903755dea86f9a4f16df187bb8bbf835c5
refs/heads/master
2020-07-01T10:24:05.343283
2020-01-13T03:27:27
2020-01-13T03:27:27
201,144,558
0
0
null
null
null
null
UTF-8
Python
false
false
566
py
# # @lc app=leetcode id=287 lang=python3 # # [287] Find the Duplicate Number # from typing import List class Solution: def findDuplicate(self, nums: List[int]) -> int: low = 0 high = len(nums) - 1 mid = (high + low) // 2 while high - low > 1: count = 0 for num in nums: if mid < num <= high: count += 1 if high - mid >= count: high = mid else: low = mid mid = (high + low) // 2 return high
[ "shun.sato1@gmail.com" ]
shun.sato1@gmail.com
05cd52ca349b42d73c8bb6552629c6c5a911bb15
20044db9ab2c773cc80caa4a5a1175ee8148269d
/test/test_rma_nb.py
3498e98c2a687e11e0ac02e8076670280d7038cf
[]
no_license
senganal/mpi4py
a4e5dbf2d7e6cf9b6eb783f1e5f1c523326d667f
28a2e95506844a32efb6b14238ca60173fe7c5a2
refs/heads/master
2021-01-13T08:02:43.439643
2017-06-16T15:03:44
2017-06-16T15:03:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,219
py
from mpi4py import MPI import mpiunittest as unittest import arrayimpl def mkzeros(n): import sys if not hasattr(sys, 'pypy_version_info'): return bytearray(n) return b'\0' * n def memzero(m): try: m[:] = 0 except IndexError: # cffi buffer m[0:len(m)] = b'\0'*len(m) class BaseTestRMA(object): COMM = MPI.COMM_NULL INFO = MPI.INFO_NULL COUNT_MIN = 0 def setUp(self): nbytes = 100*MPI.DOUBLE.size try: self.mpi_memory = MPI.Alloc_mem(nbytes) self.memory = self.mpi_memory memzero(self.memory) except MPI.Exception: from array import array self.mpi_memory = None self.memory = array('B',[0]*nbytes) self.WIN = MPI.Win.Create(self.memory, 1, self.INFO, self.COMM) def tearDown(self): self.WIN.Free() if self.mpi_memory: MPI.Free_mem(self.mpi_memory) def testPutGet(self): group = self.WIN.Get_group() size = group.Get_size() group.Free() for array in arrayimpl.ArrayTypes: for typecode in arrayimpl.TypeMap: for count in range(self.COUNT_MIN, 10): for rank in range(size): sbuf = array([rank]*count, typecode) rbuf = array(-1, typecode, count+1) self.WIN.Fence() self.WIN.Lock(rank) r = self.WIN.Rput(sbuf.as_mpi(), rank) r.Wait() self.WIN.Flush(rank) r = self.WIN.Rget(rbuf.as_mpi_c(count), rank) r.Wait() self.WIN.Unlock(rank) for i in range(count): self.assertEqual(sbuf[i], rank) self.assertEqual(rbuf[i], rank) self.assertEqual(rbuf[-1], -1) def testAccumulate(self): group = self.WIN.Get_group() size = group.Get_size() group.Free() for array in arrayimpl.ArrayTypes: for typecode in arrayimpl.TypeMap: for count in range(self.COUNT_MIN, 10): for rank in range(size): ones = array([1]*count, typecode) sbuf = array(range(count), typecode) rbuf = array(-1, typecode, count+1) for op in (MPI.SUM, MPI.PROD, MPI.MAX, MPI.MIN, MPI.REPLACE): self.WIN.Lock(rank) self.WIN.Put(ones.as_mpi(), rank) self.WIN.Flush(rank) r = self.WIN.Raccumulate(sbuf.as_mpi(), rank, op=op) r.Wait() self.WIN.Flush(rank) r = self.WIN.Rget(rbuf.as_mpi_c(count), rank) r.Wait() self.WIN.Unlock(rank) # for i in range(count): self.assertEqual(sbuf[i], i) self.assertEqual(rbuf[i], op(1, i)) self.assertEqual(rbuf[-1], -1) def testGetAccumulate(self): group = self.WIN.Get_group() size = group.Get_size() group.Free() for array in arrayimpl.ArrayTypes: for typecode in arrayimpl.TypeMap: for count in range(self.COUNT_MIN, 10): for rank in range(size): ones = array([1]*count, typecode) sbuf = array(range(count), typecode) rbuf = array(-1, typecode, count+1) gbuf = array(-1, typecode, count+1) for op in (MPI.SUM, MPI.PROD, MPI.MAX, MPI.MIN, MPI.REPLACE, MPI.NO_OP): self.WIN.Lock(rank) self.WIN.Put(ones.as_mpi(), rank) self.WIN.Flush(rank) r = self.WIN.Rget_accumulate(sbuf.as_mpi(), rbuf.as_mpi_c(count), rank, op=op) r.Wait() self.WIN.Flush(rank) r = self.WIN.Rget(gbuf.as_mpi_c(count), rank) r.Wait() self.WIN.Unlock(rank) # for i in range(count): self.assertEqual(sbuf[i], i) self.assertEqual(rbuf[i], 1) self.assertEqual(gbuf[i], op(1, i)) self.assertEqual(rbuf[-1], -1) self.assertEqual(gbuf[-1], -1) def testPutProcNull(self): rank = self.COMM.Get_rank() self.WIN.Lock(rank) r = self.WIN.Rput(None, MPI.PROC_NULL, None) r.Wait() self.WIN.Unlock(rank) def testGetProcNull(self): rank = self.COMM.Get_rank() self.WIN.Lock(rank) r = self.WIN.Rget(None, MPI.PROC_NULL, None) r.Wait() self.WIN.Unlock(rank) def testAccumulateProcNullReplace(self): rank = self.COMM.Get_rank() zeros = mkzeros(8) self.WIN.Lock(rank) r = self.WIN.Raccumulate([zeros, MPI.INT], MPI.PROC_NULL, None, MPI.REPLACE) r.Wait() r = self.WIN.Raccumulate([zeros, MPI.INT], MPI.PROC_NULL, None, MPI.REPLACE) r.Wait() self.WIN.Unlock(rank) def testAccumulateProcNullSum(self): rank = self.COMM.Get_rank() zeros = mkzeros(8) self.WIN.Lock(rank) r = self.WIN.Raccumulate([zeros, MPI.INT], MPI.PROC_NULL, None, MPI.SUM) r.Wait() r = self.WIN.Raccumulate([None, MPI.INT], MPI.PROC_NULL, None, MPI.SUM) r.Wait() self.WIN.Unlock(rank) class TestRMASelf(BaseTestRMA, unittest.TestCase): COMM = MPI.COMM_SELF class TestRMAWorld(BaseTestRMA, unittest.TestCase): COMM = MPI.COMM_WORLD try: MPI.Win.Create(None, 1, MPI.INFO_NULL, MPI.COMM_SELF).Free() except NotImplementedError: del TestRMASelf, TestRMAWorld else: name, version = MPI.get_vendor() if name == 'Open MPI': if version[:2] == (1,10): def SKIP(*t, **k): pass TestRMAWorld.testAccumulate = SKIP TestRMAWorld.testGetAccumulate = SKIP if version < (1,8,1): del TestRMASelf, TestRMAWorld elif name == 'MPICH2': if version < (1,5,0): del TestRMASelf, TestRMAWorld elif version >= (2,0,0) and MPI.VERSION < 3: # Intel MPI del TestRMASelf, TestRMAWorld elif MPI.Get_version() < (3,0): del TestRMASelf, TestRMAWorld if __name__ == '__main__': unittest.main()
[ "dalcinl@gmail.com" ]
dalcinl@gmail.com
df01f0fb63ebfc8068c07b21de2c887bd683c017
d697c1d45e96bd440be9c17ab14243a5882b1f52
/qianfeng/常用模块/urllib/4-goujianheader.py
3b39a5b80031109ac0fc8fb0b27c5a333fcabcab
[]
no_license
ithjl521/python
9eeda2e60dda97ee36e8764c06400eb12818689f
f4fe50799501c483cb64445fd05ee0f30f56576c
refs/heads/master
2020-07-12T23:10:53.608276
2019-11-08T08:59:35
2019-11-08T08:59:35
204,931,359
0
0
null
null
null
null
UTF-8
Python
false
false
486
py
import urllib.request import urllib.parse url = 'http://www.baidu.com' # response = urllib.request.urlopen(url) # print(response.read().decode()) # 自己伪装头部 headers = { "User-Agnet":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" } # 构建请求对象 request = urllib.request.Request(url=url,headers=headers) # 发送请求 response = urllib.request.urlopen(request) print(response.read())
[ "it_hjl@163.com" ]
it_hjl@163.com
c2e5409388839109b35e896d83768e706bc1fbb0
84c36e9067476a730d88f5ec799deabd5a46a44d
/XXXXXXXXX/PyQt5-Mini-Projects-master/TextBook/Checkboxes/mainUi.py
5d2a7f141613b3abcba677e9b3e6e424e146addf
[]
no_license
AGou-ops/myPyQT5-StudyNote
8bbce76b778a55c31773313d137682c77d246aad
7e5eb426b6f30c301d040f6bc08f8a3c41d4a232
refs/heads/master
2022-11-06T00:05:25.603798
2020-06-20T01:59:45
2020-06-20T01:59:45
261,099,203
0
0
null
null
null
null
UTF-8
Python
false
false
4,545
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(584, 511) self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(230, 30, 91, 16)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(70, 110, 51, 16)) self.label_2.setObjectName("label_2") self.brisk = QtWidgets.QCheckBox(Dialog) self.brisk.setGeometry(QtCore.QRect(370, 110, 70, 17)) self.brisk.setObjectName("brisk") self.appertizers = QtWidgets.QButtonGroup(Dialog) self.appertizers.setObjectName("appertizers") self.appertizers.addButton(self.brisk) self.stoup = QtWidgets.QCheckBox(Dialog) self.stoup.setGeometry(QtCore.QRect(370, 140, 70, 17)) self.stoup.setObjectName("stoup") self.appertizers.addButton(self.stoup) self.rochin = QtWidgets.QCheckBox(Dialog) self.rochin.setGeometry(QtCore.QRect(370, 170, 70, 17)) self.rochin.setObjectName("rochin") self.appertizers.addButton(self.rochin) self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setGeometry(QtCore.QRect(70, 240, 71, 16)) self.label_3.setObjectName("label_3") self.label_4 = QtWidgets.QLabel(Dialog) self.label_4.setGeometry(QtCore.QRect(70, 350, 47, 13)) self.label_4.setObjectName("label_4") self.label_5 = QtWidgets.QLabel(Dialog) self.label_5.setGeometry(QtCore.QRect(80, 450, 47, 13)) self.label_5.setObjectName("label_5") self.chicken = QtWidgets.QCheckBox(Dialog) self.chicken.setGeometry(QtCore.QRect(370, 240, 211, 17)) self.chicken.setObjectName("chicken") self.main = QtWidgets.QButtonGroup(Dialog) self.main.setObjectName("main") self.main.addButton(self.chicken) self.rice = QtWidgets.QCheckBox(Dialog) self.rice.setGeometry(QtCore.QRect(370, 270, 141, 17)) self.rice.setObjectName("rice") self.main.addButton(self.rice) self.potato = QtWidgets.QCheckBox(Dialog) self.potato.setGeometry(QtCore.QRect(370, 300, 161, 17)) self.potato.setObjectName("potato") self.main.addButton(self.potato) self.cake = QtWidgets.QCheckBox(Dialog) self.cake.setGeometry(QtCore.QRect(370, 350, 70, 17)) self.cake.setObjectName("cake") self.Dessert = QtWidgets.QButtonGroup(Dialog) self.Dessert.setObjectName("Dessert") self.Dessert.addButton(self.cake) self.ice_cream = QtWidgets.QCheckBox(Dialog) self.ice_cream.setGeometry(QtCore.QRect(370, 380, 91, 17)) self.ice_cream.setObjectName("ice_cream") self.Dessert.addButton(self.ice_cream) self.pie = QtWidgets.QCheckBox(Dialog) self.pie.setGeometry(QtCore.QRect(370, 410, 70, 17)) self.pie.setObjectName("pie") self.Dessert.addButton(self.pie) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.label.setText(_translate("Dialog", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt; font-weight:600;\">Menu</span></p></body></html>")) self.label_2.setText(_translate("Dialog", "Appertizer")) self.brisk.setText(_translate("Dialog", "$12 brisk")) self.stoup.setText(_translate("Dialog", "$10 stoup")) self.rochin.setText(_translate("Dialog", "$11 rochin")) self.label_3.setText(_translate("Dialog", "Main Course")) self.label_4.setText(_translate("Dialog", "Dessert")) self.label_5.setText(_translate("Dialog", "Bill: ")) self.chicken.setText(_translate("Dialog", "$32 Chicken soup with plantain freckles")) self.rice.setText(_translate("Dialog", "$26 Fried rice and Brisket")) self.potato.setText(_translate("Dialog", "$20 Potatoe soup and steak")) self.cake.setText(_translate("Dialog", "$5 Cake")) self.ice_cream.setText(_translate("Dialog", "$6 Ice Cream")) self.pie.setText(_translate("Dialog", "$5 Pie"))
[ "suofeiyaxx@gmail.com" ]
suofeiyaxx@gmail.com
29919d9fb02730fee196407970876918996c26db
5c94e032b2d43ac347f6383d0a8f0c03ec3a0485
/MiniLab_mkII/__init__.py
92e7d550c23bd2cf4b051b5bcc8d23df5cbf1906
[]
no_license
Elton47/Ableton-MRS-10.1.13
997f99a51157bd2a2bd1d2dc303e76b45b1eb93d
54bb64ba5e6be52dd6b9f87678ee3462cc224c8a
refs/heads/master
2022-07-04T01:35:27.447979
2020-05-14T19:02:09
2020-05-14T19:02:09
263,990,585
0
0
null
2020-05-14T18:12:04
2020-05-14T18:12:03
null
UTF-8
Python
false
false
916
py
# uncompyle6 version 3.6.7 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.17 (default, Dec 23 2019, 21:25:33) # [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.16)] # Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/MiniLab_mkII/__init__.py # Compiled at: 2020-01-09 15:21:34 from __future__ import absolute_import, print_function, unicode_literals import _Framework.Capabilities as caps from .MiniLabMk2 import MiniLabMk2 def get_capabilities(): return {caps.CONTROLLER_ID_KEY: caps.controller_id(vendor_id=7285, product_ids=[649], model_name=['Arturia MiniLab mkII']), caps.PORTS_KEY: [ caps.inport(props=[caps.NOTES_CC, caps.SCRIPT, caps.REMOTE]), caps.outport(props=[caps.SCRIPT])]} def create_instance(c_instance): return MiniLabMk2(c_instance=c_instance)
[ "ahmed.emerah@icloud.com" ]
ahmed.emerah@icloud.com
e488b3d086433aa8834313e177c946dd9b0641b3
da2d53e8021b539db006fa31f02d1c2ae46bed3b
/March Long Challenge 2021/8. Consecutive Adding.py
e2e92af1f63e5d65d0a481da2b09867f3e03e022
[]
no_license
srajsonu/CodeChef
0723ee4975808e2f4d101d2034771d868ae3b7f7
a39cd5886a5f108dcd46f70922d5637dd29849ce
refs/heads/main
2023-04-22T08:33:06.376698
2021-05-16T05:48:17
2021-05-16T05:48:17
327,030,437
0
1
null
null
null
null
UTF-8
Python
false
false
2,397
py
from collections import deque class Solution: def isValid(self, A, i, j): if i < 0 or i >= len(A) or j < 0 or j >= len(A[0]): return False return True def dfs(self, A, B, i, j, vis): vis.add(i, j) row = [-1, 0, 1, 0] col = [0, -1, 0, 1] for r, c in zip(row, col): nRow = i + r nCol = j + c if self.isValid(A, nRow, nCol) and (nRow, nCol) not in vis: self.dfs(A, B, nRow, nCol, vis) def bfs(self, A, B, X, i, j, vis): q = deque() q.append((i, j, B[i][j] - A[i][j])) row = [-1, 0, 1, 0] col = [0, -1, 0, 1] while q: i, j, v = q.popleft() A[i][j] += v for r, c in zip(row, col): nRow = i + r nCol = j + c if self.isValid(A, nRow, nCol) and A[nRow][nCol] != B[nRow][nCol]: while self.isValid(A, nRow, nCol): A[nRow][nCol] += v nRow += r nCol += c X -= 1 # print(nRow-r, nCol-c, A) if self.isValid(A, nRow - r, nCol - c) and A[nRow - r][nCol - c] != B[nRow - r][nCol - c] and ( nRow - r, nCol - c) not in vis and X > 0: #print(nRow - r, nCol - c, A, v) vis.add((nRow - r, nCol - c)) v = B[nRow - r][nCol - c] - A[nRow - r][nCol - c] q.append((nRow - r, nCol - c, v)) if X <= 0: break def solve(self, A, B, R, C, X): vis = set() for i in range(R): for j in range(C): if A[i][j] != B[i][j] and (i, j) not in vis: self.bfs(A, B, X, i, j, vis) for i in range(R): for j in range(C): if A[i][j] != B[i][j]: return 'No' return A if __name__ == '__main__': S = Solution() T = int(input()) for _ in range(T): R, C, X = map(int, input().split()) A = [] for _ in range(R): row = list(map(int, input().split())) A.append(row) B = [] for _ in range(R): row = list(map(int, input().split())) B.append(row) print(S.solve(A, B, R, C, X))
[ "srajsonu02@gmail.com" ]
srajsonu02@gmail.com
10cbdbc9540fe4bef60a125001d0fa4cbad72202
86393bd0d16c69363aa1afb4c4841fff6314493c
/examples/models/azure_aks_deep_mnist/DeepMnist.py
0e45b33d8653c9f0dd43b7961eecc19e3f48cda6
[ "Apache-2.0" ]
permissive
SeldonIO/seldon-core
0179fc490c439dbc04f2b8e6157f39291cb11aac
6652d080ea10cfca082be7090d12b9e776d96d7a
refs/heads/master
2023-08-19T08:32:10.714354
2023-08-15T12:55:57
2023-08-15T12:55:57
114,898,943
3,947
885
Apache-2.0
2023-09-13T11:29:37
2017-12-20T14:51:54
HTML
UTF-8
Python
false
false
641
py
import tensorflow as tf import numpy as np class DeepMnist(object): def __init__(self): self.class_names = ["class:{}".format(str(i)) for i in range(10)] self.sess = tf.Session() saver = tf.train.import_meta_graph("model/deep_mnist_model.meta") saver.restore(self.sess,tf.train.latest_checkpoint("./model/")) graph = tf.get_default_graph() self.x = graph.get_tensor_by_name("x:0") self.y = graph.get_tensor_by_name("y:0") def predict(self,X,feature_names): predictions = self.sess.run(self.y,feed_dict={self.x:X}) return predictions.astype(np.float64)
[ "axsauze@gmail.com" ]
axsauze@gmail.com
26327b7c71992dbaeac22e71ebb678a503d4dd13
acff427a36d6340486ff747ae9e52f05a4b027f2
/main/desktop/font/amiri-fonts/actions.py
8bd7964bbed99a2bbd3ba4b3361b254a7b92e377
[]
no_license
jeremie1112/pisilinux
8f5a03212de0c1b2453132dd879d8c1556bb4ff7
d0643b537d78208174a4eeb5effeb9cb63c2ef4f
refs/heads/master
2020-03-31T10:12:21.253540
2018-10-08T18:53:50
2018-10-08T18:53:50
152,126,584
2
1
null
2018-10-08T18:24:17
2018-10-08T18:24:17
null
UTF-8
Python
false
false
391
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 3. # See the file http://www.gnu.org/licenses/gpl.txt from pisi.actionsapi import pisitools def install(): pisitools.insinto("/usr/share/fonts/amiri", "Amiri*.ttf") pisitools.dodoc("OFL.txt", "README-Arabic", "README", ) pisitools.insinto("/usr/share/amiri-fonts", "*.pdf")
[ "erkanisik@yahoo.com" ]
erkanisik@yahoo.com
39b66b351172d94092faf826e4ea94d4c0bf074a
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/R/ronanmchugh/get_loc_relator_codes.py
4c12ef47be97a8541377ce37e91bef4939da90fa
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,080
py
import scraperwiki import lxml.html # Blank Python html = scraperwiki.scrape("http://www.loc.gov/marc/relators/relaterm.html") root = lxml.html.fromstring(html) authorizedList = root.find_class("authorized") codeList = root.find_class('relator-code') codeDict = dict() for i in range(len(authorizedList)): codeDict = { 'type' : authorizedList[i].text_content().lower(), 'code' : codeList[i].text_content().replace('[','').replace(']','') } scraperwiki.sqlite.save(unique_keys=['code'], data=codeDict) import scraperwiki import lxml.html # Blank Python html = scraperwiki.scrape("http://www.loc.gov/marc/relators/relaterm.html") root = lxml.html.fromstring(html) authorizedList = root.find_class("authorized") codeList = root.find_class('relator-code') codeDict = dict() for i in range(len(authorizedList)): codeDict = { 'type' : authorizedList[i].text_content().lower(), 'code' : codeList[i].text_content().replace('[','').replace(']','') } scraperwiki.sqlite.save(unique_keys=['code'], data=codeDict)
[ "pallih@kaninka.net" ]
pallih@kaninka.net
eef7f6927ab37c17b81eb7c3eadc5d6378468186
b1bf615bfa1ee2065e3adfe90310814c3b27c61d
/2020-12-24/maximum-size-subarray-sum-equals-k.py
0a1d2dff638d1ae034e5195d35def2cc9ce245b9
[]
no_license
Huajiecheng/leetcode
73b09a88e61ea3b16ca3bf440fadd1470652ccf2
4becf814a2a06611ee909ec700380ab83ac8ab99
refs/heads/main
2023-03-19T21:54:20.952909
2021-03-06T03:34:52
2021-03-06T03:34:52
320,959,720
0
0
null
null
null
null
UTF-8
Python
false
false
435
py
class Solution: def maxSubArrayLen(self, nums: List[int], k: int) -> int: pref = {0:-1} result = 0 temp = 0 for i in range(len(nums)): temp = temp + nums[i] if (temp - k) in pref: if result < (i - pref[temp - k]): result = i - pref[temp - k] if temp not in pref: pref[temp] = i return result
[ "chenghuajie1998@gmail.com" ]
chenghuajie1998@gmail.com
8a4135a1f95afd0a5df5a1771cda5e752d1d4c71
bec68f492fbc6d08e16d1cfd3fb115b5e3348271
/apps/core/utils.py
b5d48ef009d264528fe414a4609e1fc05c1a2516
[ "Apache-2.0" ]
permissive
vitorh45/avaliacao
c6c88c31ed5a7d9ec7ca3d66c80735a0ec0a9774
0ea5405c559b657e1d8cd11d51455295993e1f99
refs/heads/master
2021-01-25T05:22:04.421851
2015-07-24T19:07:02
2015-07-24T19:07:02
39,533,627
0
0
null
null
null
null
UTF-8
Python
false
false
1,103
py
__author__ = 'vitor' from django.conf import settings from django.core.mail import send_mail from collections import defaultdict import string def enviar_email(obj): email_assunto = settings.EMAIL_SUBJECT habilidades = get_usuario_habilidades(obj) if habilidades: for habilidade in habilidades: mensagem = get_mensagem(habilidade=habilidade) send_mail(email_assunto, mensagem, settings.EMAIL_HOST_USER, [obj.email,]) else: mensagem = get_mensagem() send_mail(email_assunto, mensagem, settings.EMAIL_HOST_USER, [obj.email,]) def get_usuario_habilidades(obj): habilidades = [] if obj.html_c > 6 and obj.css_c > 6 and obj.javascript_c > 6: habilidades.append('Front End ') if obj.python_c > 6 and obj.django_c > 6: habilidades.append('Back End ') if obj.ios_c > 6 and obj.android_c > 6: habilidades.append('Mobile ') return habilidades def get_mensagem(**kwargs): return string.Formatter().vformat(settings.EMAIL_MESSAGE, (), defaultdict(str, **kwargs))
[ "vitorh45@gmail.com" ]
vitorh45@gmail.com
a09d4120f937f3d55f8f5d3b7dab9cc02428ff45
4b0f97f809d7126e9fb846c3182d978f7f9cf975
/web_dynamic/2-hbnb.py
cabcee7a77eec28f2055f632e0bd769a6e9401c3
[ "LicenseRef-scancode-public-domain" ]
permissive
sebastianchc/AirBnB_clone_v4
9778d09cfa96a722e94da4c3dd8037aeb5c9463b
ebc862eece3f3ee809e8ecf7c4f7057b5f819aed
refs/heads/master
2022-08-14T17:54:31.326916
2020-05-22T18:21:42
2020-05-22T18:21:42
265,034,384
0
0
null
null
null
null
UTF-8
Python
false
false
1,310
py
#!/usr/bin/python3 """ Starts a Flash Web Application """ from models import storage from models.state import State from models.city import City from models.amenity import Amenity from models.place import Place from os import environ from flask import Flask, render_template from uuid import uuid4 app = Flask(__name__) # app.jinja_env.trim_blocks = True # app.jinja_env.lstrip_blocks = True @app.teardown_appcontext def close_db(error): """ Remove the current SQLAlchemy Session """ storage.close() @app.route('/2-hbnb', strict_slashes=False) def hbnb(): """ HBNB is alive! """ states = storage.all(State).values() states = sorted(states, key=lambda k: k.name) st_ct = [] for state in states: st_ct.append([state, sorted(state.cities, key=lambda k: k.name)]) amenities = storage.all(Amenity).values() amenities = sorted(amenities, key=lambda k: k.name) places = storage.all(Place).values() places = sorted(places, key=lambda k: k.name) return render_template('2-hbnb.html', states=st_ct, amenities=amenities, places=places, cache_id=uuid4()) if __name__ == "__main__": """ Main Function """ app.run(host='0.0.0.0', port=5000)
[ "nicolico99@hotmail.com" ]
nicolico99@hotmail.com
4b44111f4094084a912b33a69846ba0791ca3bf2
07d707328cd2a641a68bd508f3f4d2ca8fb7cdef
/games/connectx/util/base64_file.py
63b97e575d5a79d741c82ef92587245540a215ee
[]
no_license
JamesMcGuigan/ai-games
8ba8af30f58519081bef973d428694f1a40dfea2
eac436d23e03624c2245838138e9608cb13d2f1f
refs/heads/master
2023-07-17T11:02:02.062853
2021-02-01T23:03:45
2021-02-01T23:03:45
271,096,829
19
2
null
null
null
null
UTF-8
Python
false
false
4,017
py
import base64 import gzip import os import re import time from typing import Any from typing import Union import dill import humanize # _base64_file__test_base64_static_import = """ # H4sIAPx9LF8C/2tgri1k0IjgYGBgKCxNLS7JzM8rZIwtZNLwZvBm8mYEkjAI4jFB2KkRbED1iXnF # 5alFhczeWqV6AEGfwmBHAAAA # """ def base64_file_varname(filename: str) -> str: # ../data/AntColonyTreeSearchNode.dill.zip.base64 -> _base64_file__AntColonyTreeSearchNode__dill__zip__base64 varname = re.sub(r'^.*/', '', filename) # remove directories varname = re.sub(r'[.\W]+', '__', varname) # convert dots and non-ascii to __ varname = f"_base64_file__{varname}" return varname def base64_file_var_wrap(base64_data: Union[str,bytes], varname: str) -> str: return f'{varname} = """\n{base64_data.strip()}\n"""' # add varname = """\n\n""" wrapper def base64_file_var_unwrap(base64_data: str) -> str: output = base64_data.strip() output = re.sub(r'^\w+ = """|"""$', '', output) # remove varname = """ """ wrapper output = output.strip() return output def base64_file_encode(data: Any) -> str: encoded = dill.dumps(data) encoded = gzip.compress(encoded) encoded = base64.encodebytes(encoded).decode('utf8').strip() return encoded def base64_file_decode(encoded: str) -> Any: data = base64.b64decode(encoded) data = gzip.decompress(data) data = dill.loads(data) return data def base64_file_save(data: Any, filename: str, vebose=True) -> float: """ Saves a base64 encoded version of data into filename, with a varname wrapper for importing via kaggle_compile.py # Doesn't create/update global variable. Returns filesize in bytes """ varname = base64_file_varname(filename) start_time = time.perf_counter() try: os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, 'wb') as file: encoded = base64_file_encode(data) output = base64_file_var_wrap(encoded, varname) output = output.encode('utf8') file.write(output) file.close() if varname in globals(): globals()[varname] = encoded # globals not shared between modules, but update for saftey filesize = os.path.getsize(filename) if vebose: time_taken = time.perf_counter() - start_time print(f"base64_file_save(): {filename:40s} | {humanize.naturalsize(filesize)} in {time_taken:4.1f}s") return filesize except Exception as exception: pass return 0.0 def base64_file_load(filename: str, vebose=True) -> Union[Any,None]: """ Performs a lookup to see if the global variable for this file alread exists If not, reads the base64 encoded file from filename, with an optional varname wrapper # Doesn't create/update global variable. Returns decoded data """ varname = base64_file_varname(filename) start_time = time.perf_counter() try: # Hard-coding PyTorch weights into a script - https://www.kaggle.com/c/connectx/discussion/126678 encoded = None if varname in globals(): encoded = globals()[varname] if encoded is None and os.path.exists(filename): with open(filename, 'rb') as file: encoded = file.read().decode('utf8') encoded = base64_file_var_unwrap(encoded) # globals()[varname] = encoded # globals are not shared between modules if encoded is not None: data = base64_file_decode(encoded) if vebose: filesize = os.path.getsize(filename) time_taken = time.perf_counter() - start_time print(f"base64_file_load(): {filename:40s} | {humanize.naturalsize(filesize)} in {time_taken:4.1f}s") return data except Exception as exception: print(f'base64_file_load({filename}): Exception:', exception) return None
[ "james.mcguigan.github@gmail.com" ]
james.mcguigan.github@gmail.com
242dd82bd73845a1ef827e319a1c6f19081e8c3e
4a43dc3e8465c66dcce55027586f0b1fe1e74c99
/service/generated_flatbuffers/tflite/LessEqualOptions.py
cbc0cce9823e58843efe49a3acf6d471818a5c11
[ "Apache-2.0" ]
permissive
stewartmiles/falken
e1613d0d83edfd4485c1b78f54734e9b33b51fa5
26ab377a6853463b2efce40970e54d44b91e79ca
refs/heads/main
2023-06-05T12:01:13.099531
2021-06-17T22:22:16
2021-06-17T22:22:16
377,912,626
1
0
Apache-2.0
2021-06-17T17:34:21
2021-06-17T17:34:20
null
UTF-8
Python
false
false
2,218
py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, 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. # # automatically generated by the FlatBuffers compiler, do not modify # namespace: tflite import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class LessEqualOptions(object): __slots__ = ['_tab'] @classmethod def GetRootAsLessEqualOptions(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = LessEqualOptions() x.Init(buf, n + offset) return x @classmethod def LessEqualOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) # LessEqualOptions def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) def LessEqualOptionsStart(builder): builder.StartObject(0) def LessEqualOptionsEnd(builder): return builder.EndObject() class LessEqualOptionsT(object): # LessEqualOptionsT def __init__(self): pass @classmethod def InitFromBuf(cls, buf, pos): lessEqualOptions = LessEqualOptions() lessEqualOptions.Init(buf, pos) return cls.InitFromObj(lessEqualOptions) @classmethod def InitFromObj(cls, lessEqualOptions): x = LessEqualOptionsT() x._UnPack(lessEqualOptions) return x # LessEqualOptionsT def _UnPack(self, lessEqualOptions): if lessEqualOptions is None: return # LessEqualOptionsT def Pack(self, builder): LessEqualOptionsStart(builder) lessEqualOptions = LessEqualOptionsEnd(builder) return lessEqualOptions
[ "copybara-worker@google.com" ]
copybara-worker@google.com
d6961a6e25812611eee3434fa89c418a921d2b98
88ba19b3303c112a424720106a7f7fde615757b5
/02-intermediate_python/3-logic,_control_flow_and_filtering/driving_right.py
bb18e3df827cb3ebe9735bc5cdc9b4b32fe54d56
[]
no_license
mitchisrael88/Data_Camp
4100f5904c62055f619281a424a580b5b2b0cbc1
14356e221f614424a332bbc46459917bb6f99d8a
refs/heads/master
2022-10-22T18:35:39.163613
2020-06-16T23:37:41
2020-06-16T23:37:41
263,859,926
0
0
null
null
null
null
UTF-8
Python
false
false
225
py
# Import cars data import pandas as pd cars = pd.read_csv('cars.csv', index_col = 0) # Extract drives_right column as Series: dr dr = cars["drives_right"] # Use dr to subset cars: sel sel = cars[dr] # Print sel print(sel)
[ "noreply@github.com" ]
mitchisrael88.noreply@github.com
f100f3909357cdaf2a274f0fea14ca8c993114f0
f620403443b2c0affaed53505c002f35dc68020c
/DCTM/GetClusterNumber.py
9de8d61d5fc44f32a00a8dfec12c3d9bfaf62ec5
[]
no_license
ZhuJiahui/CTMTS
c552b3026deb47879f9aa5bde4b002cf6283858d
9f8981f6e61900a68a38ae0392e01771beee9651
refs/heads/master
2021-01-12T10:18:27.579697
2016-12-14T02:23:29
2016-12-14T02:23:29
76,416,453
0
0
null
null
null
null
UTF-8
Python
false
false
1,478
py
# -*- coding: utf-8 -*- ''' Created on 2014年7月27日 @author: ZhuJiahui506 ''' import os import numpy as np import time def get_cluster_number(X): ''' 估计聚类个数 :param X: 数据之间的相似度矩阵 维度小于1000 ''' D = np.zeros((len(X), len(X))) for i in range(len(X)): D[i, i] = 1.0 / np.sqrt(np.sum(X[i])) L = np.dot(np.dot(D, X), D) eigen_values, eigen_vectors = np.linalg.eig(L) # 按特征值降序排序 idx = eigen_values.argsort() idx = idx[::-1] eigen_values = eigen_values[idx] tao = 0.55 container = np.sum(eigen_values) * tao now_sum = 0.0 cluster_number = 0 for i in range(len(eigen_values)): now_sum += eigen_values[i] cluster_number += 1 if now_sum > container: break return cluster_number if __name__ == '__main__': start = time.clock() data = np.array([[1, 2.1, 0, 3],\ [1, 1.9, 0.1, 3],\ [4, 7, 3.1, 9.2],\ [3.8, 7, 3.0, 9.1],\ [0.9, 2.0, 0.01, 2.9]]) w = np.zeros((len(data), len(data))) for i in range(len(data)): for j in range(len(data)): w[i, j] = 1.0 / (np.sum(np.abs(data[i] - data[j])) + 1.0) c = get_cluster_number(w) print c print 'Total time %f seconds' % (time.clock() - start) print 'Complete !!!'
[ "zhujiahui@outlook.com" ]
zhujiahui@outlook.com
dfbdd01c48a73c2922ac083707b410cead8ef229
3bfa43cd86d1fb3780f594c181debc65708af2b8
/algorithms/graph/dfs.py
f74044082f578bb19ff5cc62766b874fe92a2fb0
[]
no_license
ninjaboynaru/my-python-demo
2fdb6e75c88e07519d91ee8b0e650fed4a2f9a1d
d679a06a72e6dc18aed95c7e79e25de87e9c18c2
refs/heads/master
2022-11-06T14:05:14.848259
2020-06-21T20:10:05
2020-06-21T20:10:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
646
py
from graph import digraph_from_file def dfs(g, order="post"): marked = set() def dfs_preorder(node): marked.add(node) print(node) for child in g[node]: if child not in marked: dfs_preorder(child) def dfs_postorder(node): marked.add(node) for child in g[node]: if child not in marked: dfs_postorder(child) print(node) for node in g.keys(): if node not in marked: # dfs_preorder(node) dfs_postorder(node) if __name__ == "__main__": g = digraph_from_file("input/alpha1.txt") dfs(g)
[ "wangxin19930411@163.com" ]
wangxin19930411@163.com
d3a316737b9c8b52b38e553c6ea66c0df60eb492
2ef35e0cd06653435fea8ab27d0b7db475bdb6d9
/serial_publish_local.py
18bcfc79c27bc3bc8e8f80cf7ba7925034526239
[]
no_license
navalkishoreb/Project_Mqtt
a9d438a2a1c79f662cb6b751f9c2c593989c58f2
989a491505a972a54eaf1599f95f6de9562b7e4c
refs/heads/master
2021-01-23T16:35:38.765479
2016-09-16T10:28:52
2016-09-16T10:28:52
68,371,468
0
0
null
null
null
null
UTF-8
Python
false
false
1,616
py
#!/usr/bin/python import time import serial import sys import paho.mqtt.client as mqtt """usb = serial.Serial( port='/dev/ttyACM0',\ baudrate=115200,\ parity=serial.PARITY_NONE,\ stopbits=serial.STOPBITS_ONE,\ bytesize=serial.EIGHTBITS,\ timeout=0) """ ser = serial.Serial( port='/dev/ttyAMA0', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0 ) ser.open() newLine = None def on_connect(client, userdata, flags,resultCode): print("Connected with result code "+str(resultCode)) client.publish("room/temperature/status","online",2,True) def on_message(client, userdata, messsage): print(message.topic+" : "+str(message.payload)) client = mqtt.Client('',True,None,mqtt.MQTTv311,"tcp") client.on_connect = on_connect client.on_message = on_message client.connect("172.29.4.96") client.loop_start() def printInHexFormat(binData): for ch in binData: print '0x%0*X'%(2,ord(ch)), print("\n") return; def sendTemperatureToServer(temp): r=requests.get("http://api.thingspeak.com/update?key=9W55W474GLEBNBLC&field1="+str(ord(temp))) print 'sending...'+ str(r.status_code) +" -- "+ str(r.json()) def publishTemperature(temp): client.publish("room/temperature",str(ord(temp))) while 1: data= ser.readline() if(data != '') and (data !="\n") and len(data)==8: printInHexFormat(data) printInHexFormat(data[-1:]) # sendTemperatureToServer(data[-1:]) publishTemperature(data[-1:]) newLine = True; elif(data == '\n'): print ('') else: if newLine: newLine = False;
[ "root@raspberrypi.(none)" ]
root@raspberrypi.(none)
970362856f0861f077e65c4cb8ec252123e9f29a
aa7ba8ca76bc012d5d7418b0961208be72af71d0
/glasses/models/classification/resnetxt/__init__.py
3ff55e57f37fe798fc4d1bd9252deaa651481a18
[ "MIT" ]
permissive
wiesmanyaroo/glasses
3f8bc67021ad1e7abf84965847beebc6145b2fbb
2e4bb979e3637d77f9dbec79462dc92f56d3bc27
refs/heads/master
2023-02-09T22:59:46.463233
2020-12-26T16:04:24
2020-12-26T16:04:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,607
py
from __future__ import annotations from torch import nn from torch import Tensor from glasses.nn.blocks.residuals import ResidualAdd from glasses.nn.blocks import Conv2dPad from collections import OrderedDict from typing import List from functools import partial from ..resnet import ResNet, ResNetBottleneckBlock from glasses.utils.PretrainedWeightsProvider import Config, pretrained ReLUInPlace = partial(nn.ReLU, inplace=True) class ResNetXtBottleNeckBlock(ResNetBottleneckBlock): def __init__(self, in_features: int, out_features: int, groups: int = 32, base_width: int = 4, reduction: int = 4, **kwargs): """Basic ResNetXt block build on top of ResNetBottleneckBlock. It uses `base_width` to compute the inner features of the 3x3 conv. Args: in_features (int): [description] out_features (int): [description] groups (int, optional): [description]. Defaults to 32. base_width (int, optional): width factor uses to compute the inner features in the 3x3 conv. Defaults to 4. """ features = (int(out_features * (base_width / 64) / reduction) * groups) super().__init__(in_features, out_features, features=features, groups=groups, reduction=reduction, **kwargs) class ResNetXt(ResNet): """Implementation of ResNetXt proposed in `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_ Create a default model Examples: >>> ResNetXt.resnext50_32x4d() >>> ResNetXt.resnext101_32x8d() >>> # create a resnetxt18_32x4d >>> ResNetXt.resnet18(block=ResNetXtBottleNeckBlock, groups=32, base_width=4) Customization You can easily customize your model Examples: >>> # change activation >>> ResNetXt.resnext50_32x4d(activation = nn.SELU) >>> # change number of classes (default is 1000 ) >>> ResNetXt.resnext50_32x4d(n_classes=100) >>> # pass a different block >>> ResNetXt.resnext50_32x4d(block=SENetBasicBlock) >>> # change the initial convolution >>> model = ResNetXt.resnext50_32x4d >>> model.encoder.gate.conv1 = nn.Conv2d(3, 64, kernel_size=3) >>> # store each feature >>> x = torch.rand((1, 3, 224, 224)) >>> model = ResNetXt.resnext50_32x4d() >>> features = [] >>> x = model.encoder.gate(x) >>> for block in model.encoder.layers: >>> x = block(x) >>> features.append(x) >>> print([x.shape for x in features]) >>> # [torch.Size([1, 64, 56, 56]), torch.Size([1, 128, 28, 28]), torch.Size([1, 256, 14, 14]), torch.Size([1, 512, 7, 7])] Args: in_channels (int, optional): Number of channels in the input Image (3 for RGB and 1 for Gray). Defaults to 3. n_classes (int, optional): Number of classes. Defaults to 1000. """ @classmethod @pretrained('resnext50_32x4d') def resnext50_32x4d(cls, *args, **kwargs) -> ResNetXt: """Creates a resnext50_32x4d model Returns: ResNet: A resnext50_32x4d model """ return cls.resnet50(*args, block=ResNetXtBottleNeckBlock, **kwargs) @classmethod @pretrained('resnext101_32x8d') def resnext101_32x8d(cls, *args, **kwargs) -> ResNetXt: """Creates a resnext101_32x8d model Returns: ResNet: A resnext101_32x8d model """ return cls.resnet101(*args, **kwargs, block=ResNetXtBottleNeckBlock, groups=32, base_width=8) @classmethod # @pretrained('resnext101_32x16d') def resnext101_32x16d(cls, *args, **kwargs) -> ResNetXt: """Creates a resnext101_32x16d model Returns: ResNet: A resnext101_32x16d model """ return cls.resnet101(*args, **kwargs, block=ResNetXtBottleNeckBlock, groups=32, base_width=16) @classmethod # @pretrained('resnext101_32x32d') def resnext101_32x32d(cls, *args, **kwargs) -> ResNetXt: """Creates a resnext101_32x32d model Returns: ResNet: A resnext101_32x32d model """ return cls.resnet101(*args, **kwargs, block=ResNetXtBottleNeckBlock, groups=32, base_width=32) @classmethod # @pretrained('resnext101_32x48d') def resnext101_32x48d(cls, *args, **kwargs) -> ResNetXt: """Creates a resnext101_32x48d model Returns: ResNet: A resnext101_32x48d model """ return cls.resnet101(*args, **kwargs, block=ResNetXtBottleNeckBlock, groups=32, base_width=48)
[ "zuppif@usi.ch" ]
zuppif@usi.ch
91be8127886dde63063fbf3920ba80ccc6c6a210
c4b636a2fffbf8ef3096e4de9de61b30ea3df72a
/hackerrank/zeros_and_ones.py
f921a5eca2e28ee22afd295077ac7f7b55287364
[ "MIT" ]
permissive
FelixTheC/hackerrank_exercises
f63fbbc55a783ee4cecfa04302301a0fb66d45fe
24eedbedebd122c53fd2cb6018cc3535d0d4c6a0
refs/heads/master
2021-01-04T22:10:47.538372
2020-11-01T15:57:20
2020-11-01T15:57:20
240,779,506
0
0
null
null
null
null
UTF-8
Python
false
false
296
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @created: 01.12.19 @author: felix """ import numpy as np if __name__ == '__main__': shape = tuple([int(i) for i in input() if i != ' ']) dtype = np.int print(np.zeros((shape), dtype=dtype)) print(np.ones((shape), dtype=dtype))
[ "felixeisenmenger@gmx.net" ]
felixeisenmenger@gmx.net
9573e87de4ee288a11c0c1bbe28099c89eed4022
e2bf489830e55a57945b8e696f8e2d6acefeb560
/04-系统编程-1/test/33-带有返回值的函数.py
dce5eb1489db919c3f703b6cd4598d2a3f9af0aa
[]
no_license
taizilinger123/pythonjichu
e713de06fb050943a8a1e0256ccba8dea40a411d
5ee896e92edbac55d02aa63965d896200b8c2623
refs/heads/master
2023-04-01T02:00:37.557667
2023-03-31T05:08:40
2023-03-31T05:08:40
148,663,792
0
0
null
null
null
null
UTF-8
Python
false
false
1,050
py
#!/usr/bin/env python # -*- coding:utf-8 -*- def get_wendu(): wendu = 22 print("当前的室温是:%d"%wendu) return wendu def get_wendu_huashi(wendu): print("--------4-------") wendu = wendu + 3 print("--------5-------") print("当前的温度(华氏)是:%d"%wendu) print("--------6-------") print("--------1-------") result = get_wendu() print("--------2-------") get_wendu_huashi(result) print("--------3-------") # E:\python35\python35.exe E:/pythonjichu/33-带有返回值的函数.py # Traceback (most recent call last): # File "E:/pythonjichu/33-带有返回值的函数.py", line 17, in <module> # get_wendu_huashi() # File "E:/pythonjichu/33-带有返回值的函数.py", line 9, in get_wendu_huashi #报错看最后一个行数字,其他不用看 # wendu = wendu + 3 # UnboundLocalError: local variable 'wendu' referenced before assignment # --------1------- # 当前的室温是:22 # --------2------- #二分法定位错误在哪更快 # --------4-------
[ "837337164@qq.com" ]
837337164@qq.com
8e7daff6d28883da7ddcc1f86aaf973d0b0bcb0a
5e73d9b32657539a680bad7269594f32fd1940b1
/Basic Data Structures/week4_binary_search_trees/2_is_bst/is_bst.py
82698ce5d8a6d075f2a2f42cec6ff691028925ff
[]
no_license
harshdonga/Data_Structures_Algorithms
c9b9f721996366b903182f519dd421bfbe599d3b
f3a94910e4d50ea29c906029bd0081d37cf25652
refs/heads/master
2022-11-05T08:33:00.340043
2020-06-13T18:13:52
2020-06-13T18:13:52
262,765,860
0
0
null
null
null
null
UTF-8
Python
false
false
999
py
#!/usr/bin/python3 import sys, threading, math sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**25) # new thread will get stack of such size def inOrder(tree): result = [] def inOrderRec(i,result): if tree[i][1] != -1: inOrderRec(tree[i][1], result) result.append(tree[i][0]) if tree[i][2] != -1: inOrderRec(tree[i][2], result) inOrderRec(0, result) return result def IsBinarySearchTree(tree, stree): traversed = inOrder(tree) if traversed == stree: return True else: return False def main(): nodes = int(input().strip()) if nodes == 0: print('CORRECT') exit() tree = [] for i in range(nodes): tree.append(list(map(int,input().strip().split()))) stree = sorted([x[0] for x in tree]) if IsBinarySearchTree(tree, stree): print("CORRECT") else: print("INCORRECT") threading.Thread(target=main).start()
[ "harshdonga99@gmail.com" ]
harshdonga99@gmail.com
00bc4046a8127e8a550dec3729cff87516823ed7
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/F64txHnfYj4e4MpAN_22.py
990afa3ea17171f39d83618e1ee743fb5c150d57
[]
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
208
py
def schoty(frame): sum = 0 index = 0 conversion = [1000000, 100000, 10000, 1000, 100, 10, 1] for line in frame: sum = sum + conversion[index] * line.find("-") index = index + 1 return sum
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
1a7495f69555d27d90cb00ae511930e9f61dffd6
2fd627a9cfdf5c2190fa3018055cf1b643fc55a0
/6. Union-Intersection/6. union-and-intersection.py
54669d150694720e7d50cdbcc5ae184bc7947777
[]
no_license
josancamon19/show-me-data-structures
d17981443abd12252555581909ff8bd904c582ea
5e8b8135e113aec7424ab79040afc6ff1d71f3fc
refs/heads/master
2020-08-29T02:38:36.731375
2019-11-04T19:37:32
2019-11-04T19:37:32
217,897,486
0
2
null
null
null
null
UTF-8
Python
false
false
5,661
py
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head if cur_head is None: return "-- Empty --" out_string = "" while cur_head: out_string += str(cur_head.value) + " -> " cur_head = cur_head.next return out_string def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def size(self): size = 0 node = self.head while node: size += 1 node = node.next return size def union(list1, list2): # Your Solution Here if list1 is None or type(list1) is not LinkedList or list2 is None or type(list2) is not LinkedList: print("Invalid Arguments, lists cannot be None") return LinkedList() if list1.head is None: return list2 new_linked_list = LinkedList() current_l1 = list1.head while current_l1: new_linked_list.append(current_l1.value) current_l1 = current_l1.next current_l2 = list2.head while current_l2: new_linked_list.append(current_l2.value) current_l2 = current_l2.next return new_linked_list def intersection(list1, list2): # Your Solution Here if list1 is None or type(list1) is not LinkedList or list2 is None or type(list2) is not LinkedList: print("Invalid Arguments, lists cannot be None") return LinkedList() intersected_linked_list = LinkedList() s = set() current_l1 = list1.head while current_l1: s.add(current_l1.value) current_l1 = current_l1.next current_l2 = list2.head while current_l2: if current_l2.value in s: intersected_linked_list.append(current_l2.value) s.remove(current_l2.value) current_l2 = current_l2.next return intersected_linked_list # def intersection2(list1, list2): # # Your Solution Here # # if list1 is None or type(list1) is not LinkedList or list2 is None or type(list2) is not LinkedList: # print("Invalid Arguments, lists cannot be None") # return LinkedList() # # intersected_linked_list = LinkedList() # s = set() # # current_l1 = list1.head # while current_l1: # # current_l2 = list2.head # while current_l2: # # if current_l2.value == current_l1.value: # # print(current_l1, current_l2) # # already_intersected = False # current_intersected = intersected_linked_list.head # # while current_intersected: # if current_intersected.value == current_l1.value: # already_intersected = True # break # current_intersected = current_intersected.next # # if not already_intersected: # intersected_linked_list.append(current_l1.value) # # current_l2 = current_l2.next # # current_l1 = current_l1.next # # return intersected_linked_list if __name__ == '__main__': # Test case 1 linked_list_1 = LinkedList() linked_list_2 = LinkedList() element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 21] element_2 = [6, 32, 4, 9, 6, 1, 11, 21, 1] for i in element_1: linked_list_1.append(i) for i in element_2: linked_list_2.append(i) # Union operation returns element_1 + element_2 print('\nUnion operation: ', union(linked_list_1, linked_list_2)) # Intersection operation returns set(element_1).intersection(set(element_2)) print('Intersection operation: ', intersection(linked_list_1, linked_list_2)) # Test case 2 linked_list_3 = LinkedList() linked_list_4 = LinkedList() element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 23] element_2 = [1, 7, 8, 9, 11, 21, 1] for i in element_1: linked_list_3.append(i) for i in element_2: linked_list_4.append(i) # Union operation returns element_1 + element_2 print('\nUnion operation: ', union(linked_list_3, linked_list_4)) # element_1 and element_2 are all different --> 0 intersections print('Intersection operation: ', intersection(linked_list_3, linked_list_4)) # Test case 3 linked_list_5 = LinkedList() linked_list_6 = LinkedList() element_1 = [] element_2 = [1, 7, 8, 9, 11, 21, 1] for i in element_1: linked_list_5.append(i) for i in element_2: linked_list_6.append(i) # Union operation element_1 is empty so return element_2 [1, 7, 8, 9, 11, 21, 1] print('\nUnion operation: ', union(linked_list_5, linked_list_6)) # Intersection operation element_1 is empty so 0 intersections print('Intersection operation: ', intersection(linked_list_5, linked_list_6)) print('\n\n--- Invalid Operations ---') # all will return empty LinkedList() and print a message Invalid Arguments, lists cannot be None print('\nUnion operation: ', union(linked_list_5, None)) print('Intersection operation: ', intersection(linked_list_5, None)) print('\nUnion operation: ', union(None, linked_list_6)) print('Intersection operation: ', intersection(None, linked_list_6)) print('\nUnion operation: ', union(None, None)) print('Intersection operation: ', intersection(None, None))
[ "joan.santiago.cabezas@gmail.com" ]
joan.santiago.cabezas@gmail.com
6515a2df2bf4a4bd4429023d4103b0f228db4d78
afba8aa70edb5cdfe3b38e451330deac72e4eee1
/aldryn_installer/__init__.py
fbaee6c565f0968a47cd72a0c07b3cc7e54e188a
[]
no_license
jqb/aldryn-installer
b148c920866c86de9399b27a9d9c5e8118c31953
e960a9f38a85886255f84379808c7495bd3e90b8
refs/heads/master
2021-01-15T09:37:44.006606
2013-11-04T12:52:37
2013-11-04T12:52:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
137
py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Iacopo Spalletti' __email__ = 'i.spalletti@nephila.it' __version__ = '0.1.1'
[ "i.spalletti@nephila.it" ]
i.spalletti@nephila.it
5627eb5d6cb9e3ef58e936d11ea044945069c613
00f3f038313e4334ebab171e0133fce63fdba0f0
/authentication/tests.py
03bee37ed6b69c09333697c4b4ba788a8ccbf5c0
[]
no_license
DarishkaAMS/Dj_Projects-Author_Blog
57a94aaa16d87bfd19dc2ab99e37c5710abcfd0e
ae634c80107e96bba8e0ef6d8e56e83a588e9e0b
refs/heads/main
2023-01-21T06:17:34.078609
2020-11-29T18:06:26
2020-11-29T18:06:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
694
py
from django.test import TestCase from django.urls import reverse # Create your tests here. from authentication.models import UserManager, User import requests class TestUser(TestCase): def setUp(self): email = "d@gmail.com" password = "abc" username = "HELLO" self.user = User.objects.create_user(email=email, password=password, username=username) self.user.save() def test_user_view(self): email = "d@gmail.com" password = "abc" username = "HELLO" resp = self.client.post(reverse('login'), data={'username': email, 'password': password, 'username': username}) self.assertEqual(resp.status_code, 200)
[ "d.nikolaienko@yahoo.co.uk" ]
d.nikolaienko@yahoo.co.uk
c1208a7a966e17598df2c6f7d583240b0aa57882
ae6f2b9d4c0cfd43411eadc942292439367e8bbc
/PYTHON/Teach_Your_Kids_to_Code_program_files/ch02_turtle/Challenge1_ColorSpiral10.py
ad792179745996a9ccec72d9ecb776bfd32cc884
[]
no_license
rao003/StartProgramming
6e68786b55adfad94d0601e516576bcedac290dd
341739f99bf3684a57b84c8942b85dcfc2e6bc4b
refs/heads/master
2022-11-20T22:14:10.447618
2022-11-04T07:07:33
2022-11-04T07:07:33
215,080,140
2
1
null
null
null
null
UTF-8
Python
false
false
387
py
# ColorSpiral10.py import turtle t=turtle.Pen() turtle.bgcolor('black') # You can change sides between 2 and 10 for some cool shapes! sides=10 colors=['red', 'yellow', 'blue', 'orange', 'green', 'purple', 'gray', 'white', 'pink', 'light blue'] for x in range(360): t.pencolor(colors[x%sides]) t.forward(x * 3/sides + x) t.left(360/sides + 1) t.width(x*sides/200)
[ "49493736+rao003@users.noreply.github.com" ]
49493736+rao003@users.noreply.github.com
2c1a8a260380f4fbb5f4a6d579bbb14b54ab8431
1adc05008f0caa9a81cc4fc3a737fcbcebb68995
/hardhat/recipes/swig.py
cf9658b1333900ab306a92e5b5dd4a98914a2309
[ "MIT", "BSD-3-Clause" ]
permissive
stangelandcl/hardhat
4aa995518697d19b179c64751108963fa656cfca
1ad0c5dec16728c0243023acb9594f435ef18f9c
refs/heads/master
2021-01-11T17:19:41.988477
2019-03-22T22:18:44
2019-03-22T22:18:52
79,742,340
0
0
null
null
null
null
UTF-8
Python
false
false
534
py
from .base import GnuRecipe class SwigRecipe(GnuRecipe): def __init__(self, *args, **kwargs): super(SwigRecipe, self).__init__(*args, **kwargs) self.sha256 = '7cf9f447ae7ed1c51722efc45e7f1441' \ '8d15d7a1e143ac9f09a668999f4fc94d' self.name = 'swig' self.depends = ['pcre'] self.version = '3.0.12' self.version_url = 'http://www.swig.org/download.html' self.url = 'http://prdownloads.sourceforge.net/swig/' \ 'swig-$version.tar.gz'
[ "clayton.stangeland@gmail.com" ]
clayton.stangeland@gmail.com
9c880d5f6dd983881bf0c236a6ec98537306e6a0
a4d98e9422993b4f2d977eeaf78fcf6bc8c86c10
/dfvfs/compression/zlib_decompressor.py
3269e02ffc9538aff3613266951bac81a773f71b
[ "Apache-2.0" ]
permissive
dc3-plaso/dfvfs
c3fc80c28a5054f764979e024957c724f9b774e4
06b3625426dbf1cc2ac5a8ce09303d0822625937
refs/heads/master
2020-04-04T21:15:42.815618
2017-07-15T05:27:58
2017-07-15T05:27:58
39,035,966
0
0
null
2015-07-13T20:36:59
2015-07-13T20:36:59
null
UTF-8
Python
false
false
2,038
py
# -*- coding: utf-8 -*- """The zlib and DEFLATE decompressor object implementations.""" import zlib from dfvfs.compression import decompressor from dfvfs.compression import manager from dfvfs.lib import definitions from dfvfs.lib import errors class ZlibDecompressor(decompressor.Decompressor): """Class that implements a "zlib DEFLATE" decompressor using zlib.""" COMPRESSION_METHOD = definitions.COMPRESSION_METHOD_ZLIB def __init__(self, window_size=zlib.MAX_WBITS): """Initializes the decompressor object. Args: window_size (Optional[int]): base two logarithm of the size of the compression history buffer (aka window size). When the value is negative, the standard zlib data header is suppressed. """ super(ZlibDecompressor, self).__init__() self._zlib_decompressor = zlib.decompressobj(window_size) def Decompress(self, compressed_data): """Decompresses the compressed data. Args: compressed_data (bytes): compressed data. Returns: tuple(bytes, bytes): uncompressed data and remaining compressed data. Raises: BackEndError: if the zlib compressed stream cannot be decompressed. """ try: uncompressed_data = self._zlib_decompressor.decompress(compressed_data) remaining_compressed_data = getattr( self._zlib_decompressor, u'unused_data', b'') except zlib.error as exception: raise errors.BackEndError(( u'Unable to decompress zlib compressed stream with error: ' u'{0!s}.').format(exception)) return uncompressed_data, remaining_compressed_data class DeflateDecompressor(ZlibDecompressor): """Class that implements a "raw DEFLATE" decompressor using zlib.""" COMPRESSION_METHOD = definitions.COMPRESSION_METHOD_DEFLATE def __init__(self): """Initializes the decompressor object.""" super(DeflateDecompressor, self).__init__(window_size=-zlib.MAX_WBITS) manager.CompressionManager.RegisterDecompressors([ DeflateDecompressor, ZlibDecompressor])
[ "joachim.metz@gmail.com" ]
joachim.metz@gmail.com
48a50b6f83025bcf4428123353dd477bdc0e98c6
3bcc247a2bc1e0720f0344c96f17aa50d4bcdf2d
/第四阶段/爬虫/day03pm/gouliang.py
64e4b1d4ff3399235f1cf55b272bbbf4f6d7ae33
[]
no_license
qianpeng-shen/Study_notes
6f77f21a53266476c3c81c9cf4762b2efbf821fa
28fb9a1434899efc2d817ae47e94c31e40723d9c
refs/heads/master
2021-08-16T19:12:57.926127
2021-07-06T03:22:05
2021-07-06T03:22:05
181,856,924
0
0
null
null
null
null
UTF-8
Python
false
false
1,708
py
import requests import re import json from multiprocessing import Pool from multiprocessing import Manager import time import functools #函数的包装器 def get_one_page(url): ua_header = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)"} response = requests.get(url, headers=ua_header) if response.status_code == 200:#OK return response.text return None #<em class="num"[\s\S]*?</b>([\s\S]*?)</em>[\s\S]*?</p>[\s\S]*?</style>[\s\S]*?</a> def parse_one_page(html): pattern = re.compile('<em class="num"[\s\S]*?</b>([\s\S]*?)</em>[\s\S]*?<a title="([\s\S]*?)"[\s\S]*?>') items = re.findall(pattern, html) print(items) for item in items: yield{ "名称":item[1].strip(), "价格":item[0].strip(), } def write_to_file(item): with open("DogFood.txt", 'a', encoding="utf-8") as f: f.write(json.dumps(item, ensure_ascii=False)+'\n') def CrawlPage(lock, offset): url = "https://search.yhd.com/c0-0/k力狼狗粮?cu=true&utm_source=baidu-nks&utm_medium=cpc&utm_campaign=t_262767352_baidunks&utm_term=86895147209_0_20fdeec883c64f14b0df6ea2d4e2966a#page="+str(offset)+"&sort=1" html = get_one_page(url) for item in parse_one_page(html): lock.acquire() write_to_file(item) lock.release() time.sleep(1) if __name__ == "__main__": manager = Manager() lock = manager.Lock() newCrawlPage = functools.partial(CrawlPage, lock) pool = Pool() pool.map(newCrawlPage, [i for i in range(1,11)]) pool.close() pool.join()
[ "shenqianpeng@chengfayun.com" ]
shenqianpeng@chengfayun.com
040e7ecc3fdeb537a0cd06265eed1edd420344b0
85bad96f0c53edcda738f42b4afe742eed9865c3
/TD/cliffwalking.py
571983e0c03b35368ba3be22b2c4ce80e503f039
[]
no_license
shirsho-12/RL
9fc6e0d4de18cb68a15052d1aec28417e9215862
ef94bffc80c0a5f83543cba170415d85c27ca0a9
refs/heads/main
2023-06-24T13:26:56.449898
2021-07-13T08:44:20
2021-07-13T08:44:20
368,197,497
0
0
null
null
null
null
UTF-8
Python
false
false
640
py
# If imports do not work, add a TD. to each of the files import gym from td_algos import q_learning from helper import gen_eps_greedy_policy, plot_rate env = gym.make("CliffWalking-v0") num_states, num_actions = env.observation_space.n, env.action_space.n print(num_states, num_actions) gamma = 1 num_episodes = 500 alpha = 0.4 epsilon = 0.1 behaviour_policy = gen_eps_greedy_policy(env.action_space.n, epsilon) optimal_Q, optimal_policy, info = q_learning(env, behaviour_policy, gamma, num_episodes, alpha) print("\nQ-Learning Optimal policy: \n", optimal_policy) plot_rate(info["length"], info["rewards"], "Cliff Walking: Q-Learning")
[ "shirshajit@gmail.com" ]
shirshajit@gmail.com
a44d0e7c13bbd2a1c8970b880c482d88ea0b1c02
08d54785e1266b46912e64a51054fbef80d41629
/Basic Python Programs/34.GetFileProperties.py
0bc4d4ff2f529437d2abcc6b2072d21d2827b221
[]
no_license
Wolvarun9295/BasicPython
95231fa3b47a28129de69c56c3f7b02204487005
722d36692724d1e24022405269b3efb922630c0e
refs/heads/master
2022-11-04T12:29:54.191632
2020-06-15T17:31:45
2020-06-15T17:31:45
272,414,700
0
0
null
null
null
null
UTF-8
Python
false
false
362
py
# Imported path and time modules. from os import path import time fileName = __file__ print(f'File: {fileName}') print(f'Last access time: {time.ctime(path.getatime(fileName))}') print(f'Last modified time: {time.ctime(path.getmtime(fileName))}') print(f'Last changed time: {time.ctime(path.getctime(fileName))}') print(f'Size: {path.getsize(fileName)} bytes')
[ "varun.nagrare@gmail.com" ]
varun.nagrare@gmail.com
e8ddc926d4457abb6650f3823d8b8df1fc9e24dd
9a3803ba18a88a6a172ac3fb11411ee47adc2108
/Object.py
0db2728e02ac085aca36818b3f9257c59e4510da
[]
no_license
jeffreyzhang2012/Village_Simulator_Game
6efe9197aef982da6008295e5a2b2acab51ebbdc
9bffabfd8a84980612eab5d4dd18d13d018bc5ad
refs/heads/master
2023-03-05T04:31:54.883003
2021-02-19T06:45:04
2021-02-19T06:45:04
340,277,469
0
0
null
null
null
null
UTF-8
Python
false
false
171
py
class JK(object): def __init__(self,x): self.x = x def fuck(self,d): return d.y * 3 def calc(self,d): return JK.fuck(self,d) * self.x
[ "--global" ]
--global
93ba818fa2d05a5cd078637f250e3a78c6085fc1
097b2c588b4695f3ab96c85fd4cda1ce271a7cda
/models/ssd/layers/modules/multibox_loss.py
591df6efed02fd540a39af14223c826fe2ec9238
[ "Apache-2.0" ]
permissive
qinzhengmei/silco
628422a05841287c2a5159772121e3e2b5c9b72d
18872c4c31a79aa1bac489096fd8f5c99b4380cf
refs/heads/master
2022-12-15T16:37:33.367354
2020-08-24T21:49:23
2020-08-24T21:49:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,225
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from data import v from ..box_utils import match, log_sum_exp class MultiBoxLoss(nn.Module): """SSD Weighted Loss Function Compute Targets: 1) Produce Confidence Target Indices by matching ground truth boxes with (default) 'priorboxes' that have jaccard index > threshold parameter (default threshold: 0.5). 2) Produce localization target by 'encoding' variance into offsets of ground truth boxes and their matched 'priorboxes'. 3) Hard negative mining to filter the excessive number of negative examples that comes with using a large number of default bounding boxes. (default negative:positive ratio 3:1) Objective Loss: Args: c: class confidences, l: predicted boxes, g: ground truth boxes N: number of matched default boxes See: https://arxiv.org/pdf/1512.02325.pdf for more details. """ def __init__( self, num_classes, size, overlap_thresh, prior_for_matching, bkg_label, neg_mining, neg_pos, neg_overlap, encode_target, use_gpu=True, ): super(MultiBoxLoss, self).__init__() self.use_gpu = use_gpu self.num_classes = num_classes self.threshold = overlap_thresh self.background_label = bkg_label self.encode_target = encode_target self.use_prior_for_matching = prior_for_matching self.do_neg_mining = neg_mining self.negpos_ratio = neg_pos self.neg_overlap = neg_overlap cfg = v[str(size)] self.variance = cfg["variance"] def forward(self, predictions, targets): """Multibox Loss Args: predictions (tuple): A tuple containing loc preds, conf preds, and prior boxes from SSD net. conf shape: torch.size(batch_size,num_priors,num_classes) loc shape: torch.size(batch_size,num_priors,4) priors shape: torch.size(num_priors,4) ground_truth (tensor): Ground truth boxes and labels for a batch, shape: [batch_size,num_objs,5] (last idx is the label). """ loc_data, conf_data, priors = predictions # batch_size num = loc_data.size(0) # image number priors = priors[: loc_data.size(1), :] num_priors = priors.size(0) num_classes = self.num_classes # match priors (default boxes) and ground truth boxes loc_t = torch.Tensor(num, num_priors, 4) conf_t = torch.LongTensor(num, num_priors) for idx in range(num): truths = targets[idx][:, :-1].data labels = targets[idx][:, -1].data defaults = priors.data match( self.threshold, truths, defaults, self.variance, labels, loc_t, conf_t, idx, ) if self.use_gpu: loc_t = loc_t.cuda() conf_t = conf_t.cuda() # wrap targets loc_t = Variable(loc_t, requires_grad=False) # [8,8732,4] conf_t = Variable(conf_t, requires_grad=False) # [8,8732] pos = conf_t > 0 # [8, 8732] # num_pos = pos.sum(keepdim=True) # Localization Loss (Smooth L1) # Shape: [batch,num_priors,4] pos_idx = pos.unsqueeze(pos.dim()).expand_as(loc_data) # [8, 8732, 4] loc_p = loc_data[pos_idx].view(-1, 4) # [85, 4] loc_t = loc_t[pos_idx].view(-1, 4) # [85, 4] loss_l = F.smooth_l1_loss(loc_p, loc_t, reduction="sum") # [1,1] # Compute max conf across batch for hard negative mining batch_conf = conf_data.view(-1, self.num_classes) # (140256, 2) loss_c = log_sum_exp(batch_conf) - batch_conf.gather( 1, conf_t.view(-1, 1) ) # ???? # Hard Negative Mining loss_c = loss_c.view( pos.size()[0], pos.size()[1] ) # add line,https://github.com/amdegroot/ssd.pytorch/issues/173#issuecomment-424949873 loss_c[pos] = 0 # filter out pos boxes for now loss_c = loss_c.view(num, -1) _, loss_idx = loss_c.sort(1, descending=True) _, idx_rank = loss_idx.sort(1) num_pos = pos.long().sum(1, keepdim=True) num_neg = torch.clamp(self.negpos_ratio * num_pos, max=pos.size(1) - 1) neg = idx_rank < num_neg.expand_as(idx_rank) # Confidence Loss Including Positive and Negative Examples pos_idx = pos.unsqueeze(2).expand_as(conf_data) neg_idx = neg.unsqueeze(2).expand_as(conf_data) conf_p = conf_data[(pos_idx + neg_idx).gt(0)].view(-1, self.num_classes) targets_weighted = conf_t[(pos + neg).gt(0)] loss_c = F.cross_entropy(conf_p, targets_weighted, reduction="sum") N = num_pos.data.sum().double() loss_l = loss_l.double() loss_c = loss_c.double() loss_l = loss_l / N loss_c = loss_c / N return loss_l, loss_c
[ "taohu620@gmail.com" ]
taohu620@gmail.com
c622453419c1ddf1477163422f79dfcf2d99cf19
18b977dccd70e9e5a1b553b28ab0413fb3f54f4b
/SoftUni/Python Developmen/Python-Advanced/Multidimensional-Lists/Exercises/example.py
963a83307987d5f35cf913dde2136caaa9b7d16e
[]
no_license
stevalang/Coding-Lessons
7203e3a18b20e33e8d596e3dfb58d26c50b74530
2d0060c2268ad966efdcae4e6e994ac15e57243a
refs/heads/master
2023-06-05T08:28:33.290530
2021-06-16T19:37:29
2021-06-16T19:37:29
284,852,565
1
0
null
null
null
null
UTF-8
Python
false
false
1,162
py
rows, cols = tuple(map(int, input().split())) matrix = [] player_position = [] for i in range(rows): row = [x for x in list(input())] matrix.append(row) for c in row: if 'P' == c: player_position = [i, row.index('P')] commands = list(input()) for command in commands: next_player_position = [] temp_position = [] if command == 'U': next_player_position = [player_position[0] - 1, player_position[1]] next_position = matrix[[next_player_position[0]][next_player_position[1]]] current_position = matrix[player_position[0]][player_position[1]] if next_position == ".": next_player_position = 'P' current_position = '.' elif command == 'D': next_player_position = [player_position[0] + 1, player_position[1]] elif command == 'L': next_player_position = [player_position[0], [player_position[1]-1]] elif command == 'R': next_player_position = [player_position[0], [player_position[1]+1]] for row in matrix: commands for element in row: if element == '.': print(matrix) print(commands) print(player_position)
[ "rbeecommerce@gmail.com" ]
rbeecommerce@gmail.com
316f6adc9ec6ba64bd822c35e138ec8b81898db6
d79c152d072edd6631e22f886c8beaafe45aab04
/nicolock/products/migrations/0003_auto_20161207_0642.py
843f5b50c6fa3ce6ec3d0db7e5dfa6cc8f2289ee
[]
no_license
kabroncelli/Nicolock
764364de8aa146721b2678c14be808a452d7a363
4c4343a9117b7eba8cf1daf7241de549b9a1be3b
refs/heads/master
2020-03-11T11:02:43.074373
2018-04-18T17:38:33
2018-04-18T17:38:33
129,959,455
0
0
null
null
null
null
UTF-8
Python
false
false
1,440
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-07 06:42 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('products', '0002_initialize_categories'), ] operations = [ migrations.AlterModelOptions( name='color', options={'ordering': ['order', 'modified'], 'verbose_name': 'color', 'verbose_name_plural': 'colors'}, ), migrations.AlterModelOptions( name='file', options={'ordering': ['order', 'modified'], 'verbose_name': 'file', 'verbose_name_plural': 'files'}, ), migrations.AlterModelOptions( name='image', options={'ordering': ['order', 'modified'], 'verbose_name': 'image', 'verbose_name_plural': 'images'}, ), migrations.AlterModelOptions( name='pattern', options={'ordering': ['order', 'modified'], 'verbose_name': 'pattern', 'verbose_name_plural': 'patterns'}, ), migrations.AlterModelOptions( name='product', options={'ordering': ['order', 'modified'], 'verbose_name': 'product', 'verbose_name_plural': 'products'}, ), migrations.AlterModelOptions( name='spec', options={'ordering': ['order', 'modified'], 'verbose_name': 'spec', 'verbose_name_plural': 'specs'}, ), ]
[ "brennen@lightningkite.com" ]
brennen@lightningkite.com
fb38d5f52a8030341505bcd5f75290e71fc7c05e
2e935ca936976d2d2bd4e785e2f3f29c63771542
/ExPy10301.py
8da6aad45cc4ef8ef45343a9670f7847b3834cb8
[]
no_license
zoro6908/PY_acamedy
4a370e866fef19f6d2e7697eb809352b6ac703f5
460d26639f7bd8cf2486950dc70feae6a2959ca0
refs/heads/master
2023-04-26T18:10:44.691326
2021-05-25T00:11:02
2021-05-25T00:11:02
298,425,369
0
0
null
null
null
null
UTF-8
Python
false
false
521
py
# 파이썬 기초부터 활용까지 (2020.09) # [3과] 연산문 # 1. 수치연산 print(398**2) #지수 a = 55.6; b = 7 c = a + b # 실수와 정수의 덧셈 print(c, type(c)) # 결과는 실수 s = int(c) # int() 함수 사용 print(s) k = s - 900 print(k) k2 = abs(k) # 절대치 함수 print(k2) p = (10, 20, 90, 70, 8) # 튜플 자료형 print(p) print(max(p)) # 최대치 함수 print(min(p)) # 최소치 함수 print(sum(p)) # 합계 함수
[ "zoro6908@naver.com" ]
zoro6908@naver.com
ef8f956403d0202e9fb20059973bea3abe472964
26d6c34df00a229dc85ad7326de6cb5672be7acc
/msgraph-cli-extensions/beta/education_beta/azext_education_beta/vendored_sdks/education/aio/operations/_education_schools_users_operations.py
e8c69dfc0b8242740273af02b2c355cc271fe2cb
[ "MIT" ]
permissive
BrianTJackett/msgraph-cli
87f92471f68f85e44872939d876b9ff5f0ae6b2c
78a4b1c73a23b85c070fed2fbca93758733f620e
refs/heads/main
2023-06-23T21:31:53.306655
2021-07-09T07:58:56
2021-07-09T07:58:56
386,993,555
0
0
NOASSERTION
2021-07-17T16:56:05
2021-07-17T16:56:05
null
UTF-8
Python
false
false
4,183
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class EducationSchoolsUsersOperations: """EducationSchoolsUsersOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~education.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def delta( self, education_school_id: str, **kwargs ) -> List["models.MicrosoftGraphEducationUser"]: """Invoke function delta. Invoke function delta. :param education_school_id: key: id of educationSchool. :type education_school_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: list of MicrosoftGraphEducationUser, or the result of cls(response) :rtype: list[~education.models.MicrosoftGraphEducationUser] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[List["models.MicrosoftGraphEducationUser"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) accept = "application/json" # Construct URL url = self.delta.metadata['url'] # type: ignore path_format_arguments = { 'educationSchool-id': self._serialize.url("education_school_id", education_school_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.OdataError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('[MicrosoftGraphEducationUser]', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delta.metadata = {'url': '/education/schools/{educationSchool-id}/users/microsoft.graph.delta()'} # type: ignore
[ "japhethobalak@gmail.com" ]
japhethobalak@gmail.com
b807d74a03dd5f1381c42a92a7cb6c9e30bac800
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03370/s840732194.py
0eb0e9c767f212efcb5084f1fc3f3b2db6f627d9
[]
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
252
py
[N,X] = list(map(int,input().split())) m = [] for i in range(N): m.append(int(input())) # print('m:',m) amari = X - sum(m) # print('amari:',amari) i=0 while True: if amari<min(m)*i: ans = len(m) + i-1 break i+=1 print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
30c14a07c174d1205e1cfe1466811eedb9f4a091
e7df6d41d7e04dc1c4f4ed169bf530a8a89ff17c
/Bindings/Python/tests/test_simulation_utilities.py
cfc1e5913bbeb73b03ab8a056978b8cf24909949
[ "Apache-2.0" ]
permissive
opensim-org/opensim-core
2ba11c815df3072166644af2f34770162d8fc467
aeaaf93b052d598247dd7d7922fdf8f2f2f4c0bb
refs/heads/main
2023-09-04T05:50:54.783630
2023-09-01T22:44:04
2023-09-01T22:44:04
20,775,600
701
328
Apache-2.0
2023-09-14T17:45:19
2014-06-12T16:57:56
C++
UTF-8
Python
false
false
598
py
import os import unittest import opensim as osim test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)), 'tests') class TestSimulationUtilities(unittest.TestCase): def test_update_kinematics(self): model = osim.Model( os.path.join(test_dir, 'gait10dof18musc_subject01.osim')) kinematics_file = os.path.join(test_dir, 'std_subject01_walk1_ik.mot') # updatePre40KinematicsStorageFor40MotionType() is not wrapped. osim.updatePre40KinematicsFilesFor40MotionType(model, [kinematics_file])
[ "cld72@cornell.edu" ]
cld72@cornell.edu
a0ac77d6f01d6b6ed6363565b4d311164ca4e6a6
5d178ff8ae636123147b15fa530dba3aff0ff786
/fsb/tariff/urls.py
0154607fd51a330b569b2943ff03d0f91b991d3f
[]
no_license
grengojbo/fsb
70d054388e75e2e3d62aa4dbf80679ccd7213c50
75a222dda323edb5a5407ffc89071a48ed0628aa
refs/heads/master
2021-01-10T20:29:22.965848
2011-04-07T16:27:38
2011-04-07T16:27:38
561,853
5
3
null
null
null
null
UTF-8
Python
false
false
745
py
# -*- mode: python; coding: utf-8; -*- from django.conf.urls.defaults import * from django.conf import settings #from django.utils.translation import ugettext_lazy as _ __author__ = '$Author:$' __revision__ = '$Revision:$' # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/(.*)', admin.site.root), )
[ "oleg.dolya@gmail.com" ]
oleg.dolya@gmail.com
aeed7aa47de82741ebdc77756df68ce3e9a6f0d3
8993f017079fd4c8329b37ddb663b28b54be1586
/LatitudeProfile.py
f013f2db4c433bcb565eabb110ec36f87452c5e6
[ "MIT" ]
permissive
nithinsivadas/IRI2016
74f7ec3bb39b4b55c6368085dd1fcbfee8cab20c
16f383e6666dfff2938019d49b411ec23b8f18c0
refs/heads/master
2020-07-15T01:13:34.167868
2019-08-29T19:53:59
2019-08-29T19:53:59
205,445,491
0
0
MIT
2019-08-30T19:33:21
2019-08-30T19:33:21
null
UTF-8
Python
false
false
917
py
#!/usr/bin/env python import iri2016 as iri from argparse import ArgumentParser from matplotlib.pyplot import show from pathlib import Path import iri2016.plots as piri def main(): p = ArgumentParser() p.add_argument("glon", help="geodetic longitude (degrees)", type=float) p.add_argument( "-glat", help="geodetic latitude START STOP STEP (degrees)", type=float, nargs=3, default=(-60, 60, 2.0), ) p.add_argument("-alt_km", help="altitude (km)", type=float, default=300.0) p.add_argument("-o", "--outfn", help="write data to file") P = p.parse_args() iono = iri.geoprofile(latrange=P.glat, glon=P.glon, altkm=P.alt_km, time="2004-01-01T17") if P.outfn: outfn = Path(P.outfn).expanduser() print("writing", outfn) iono.to_netcdf(outfn) piri.latprofile(iono) show() if __name__ == "__main__": main()
[ "scivision@users.noreply.github.com" ]
scivision@users.noreply.github.com
7c66b48eb66db52f012546f32ea940d5909ce431
4262dcafe190db05852c7e1cfafc687031d23367
/src/Employee/migrations/0007_employee_emp_password.py
6e60f91162e7e4865e7ee9cc97e6bc670c43ef68
[]
no_license
ShunnoSaiful/JobPortal
b39930fcdb1bc30567f8a2c91d80786ab497afd5
c8f3064b87c5d967b8f415fc5f080e167fc0c77d
refs/heads/main
2023-01-07T02:44:33.831589
2020-11-11T11:47:46
2020-11-11T11:47:46
308,109,029
0
0
null
null
null
null
UTF-8
Python
false
false
441
py
# Generated by Django 2.2 on 2020-11-03 16:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Employee', '0006_employee_is_employee'), ] operations = [ migrations.AddField( model_name='employee', name='emp_password', field=models.CharField(default=1, max_length=100), preserve_default=False, ), ]
[ "sunnosaiful@gmail.com" ]
sunnosaiful@gmail.com
ec5b256968bdfc9555035c60dbbede31f0403251
bdc10ba57424040129cc72ad018ff26bc8bca66a
/ConfigDefinitions/BranchAdditions/UserDefinedCollections/EScaleCollection_Embedded_2017.py
1d12d35cc1372cf62acdb235a5cb627116ff5069
[]
no_license
aloeliger/Jesterworks
61e0ac38ca325fefbbd8ccedaa8eb02d8a76ebbe
96a22bac4ce20b91aba5884eb0e5667fcea3bc9a
refs/heads/master
2021-06-09T15:39:06.976110
2021-04-23T11:25:06
2021-04-23T11:25:06
157,698,363
0
1
null
null
null
null
UTF-8
Python
false
false
1,419
py
import ConfigDefinitions.BranchAdditions.BranchDef as BranchDef import ConfigDefinitions.BranchAdditions.UserDefinedBranches.EmbeddedTES as TES import ConfigDefinitions.BranchAdditions.UserDefinedBranches.MES as MES import ConfigDefinitions.BranchAdditions.UserDefinedBranches.LLFakeES as LLFakeES EScaleCollection = BranchDef.UserBranchCollection() EScaleCollection.UserBranches = [ TES.TES_E_UP_2017Branch, TES.TES_E_DOWN_2017Branch, TES.TES_PT_UP_2017Branch, TES.TES_PT_DOWN_2017Branch, TES.TES_MET_UP_2017Branch, TES.TES_MET_DOWN_2017Branch, TES.TES_METPhi_UP_2017Branch, TES.TES_METPhi_DOWN_2017Branch, MES.muonES_E_UP_Branch, MES.muonES_E_DOWN_Branch, MES.muonES_Pt_UP_Branch, MES.muonES_Pt_DOWN_Branch, MES.muonES_MET_UP_Branch, MES.muonES_MET_DOWN_Branch, MES.muonES_METPhi_UP_Branch, MES.muonES_METPhi_DOWN_Branch, LLFakeES.EES_E_UP_Branch, LLFakeES.EES_E_DOWN_Branch, LLFakeES.EES_Pt_UP_Branch, LLFakeES.EES_Pt_DOWN_Branch, LLFakeES.EES_MET_UP_Branch, LLFakeES.EES_MET_DOWN_Branch, LLFakeES.EES_METPhi_UP_Branch, LLFakeES.EES_METPhi_DOWN_Branch, LLFakeES.MES_E_UP_Branch, LLFakeES.MES_E_DOWN_Branch, LLFakeES.MES_Pt_UP_Branch, LLFakeES.MES_Pt_DOWN_Branch, LLFakeES.MES_MET_UP_Branch, LLFakeES.MES_MET_DOWN_Branch, LLFakeES.MES_METPhi_UP_Branch, LLFakeES.MES_METPhi_DOWN_Branch, ]
[ "aloelige@cern.ch" ]
aloelige@cern.ch
812bd562a8a088516188cbf8c3f613c20f3288ef
df29840e4adbc35f40d8a05d3d887359fc7a784b
/Git Result24bd/Result24bd/Result24bd/settings.py
5b37549c35f0232f036b9cf8daca59111dcff05c
[]
no_license
mdarifulislamroni21/backupdtatahuifehi
ab796ff2b70a4614f586af29e786b085cb1ee6c1
a26ab7373ad50cb0b563a2511a7788748002884c
refs/heads/main
2023-08-17T04:53:50.262280
2021-10-06T18:10:46
2021-10-06T18:10:46
414,320,426
0
0
null
null
null
null
UTF-8
Python
false
false
4,241
py
from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent HTMLCODE_DIRS=os.path.join(BASE_DIR,'html_code') STATIC_DIRS=os.path.join(BASE_DIR,'static') MEDIA_DIRS=os.path.join(BASE_DIR,'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-v9!n=kpn3$a*4$)3-vyz@=!%!fpb$6r@9duwg371sb1*imlv*p' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['result24bd.com',] CRISPY_TEMPLATE_PACK='bootstrap4' # Application definition AUTH_USER_MODEL='User.User' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms','django_cleanup.apps.CleanupConfig', 'Post','User','ckeditor','ckeditor_uploader', ] SITE_ID=1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Result24bd.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [HTMLCODE_DIRS,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Result24bd.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'resultbd', # 'USER': 'root', # 'PASSWORD': 'Roni@gmail1', # 'HOST': 'localhost', # 'PORT': '3306', # } # } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL='/media/' # STATICFILES_DIRS=[STATIC_DIRS,] CKEDITOR_UPLOAD_PATH = 'uploads/' # MEDIA_ROOT=MEDIA_DIRS CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_JQUERY_URL = '/static/js/jquery-2.1.1.min.js' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Full', 'height': 600, 'width': 835, 'removePlugins': 'stylesheetparser', 'extraPlugins': 'codesnippet', }, } LOGIN_URL='/account/login/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
[ "mdarifulislamroni21@gmail.com" ]
mdarifulislamroni21@gmail.com
e001347036d4b1d0a8121284db7bbd21f629efb5
12a42054b156383ebbe3ccc5de4150633c66da5d
/problems/expression-add-operators/solution.py
04767fe89317c99a372a898317a522b11ece6202
[]
no_license
cfoust/leetcode-problems
93c33029f74f32c64caf8294292226d199d6e272
f5ad7866906d0a2cf2250e5972ce910bf35ce526
refs/heads/master
2020-03-16T23:05:45.123781
2018-05-11T16:41:09
2018-05-11T16:41:09
133,064,772
1
1
null
null
null
null
UTF-8
Python
false
false
179
py
class Solution: def addOperators(self, num, target): """ :type num: str :type target: int :rtype: List[str] """ """
[ "cfoust@sqweebloid.com" ]
cfoust@sqweebloid.com
0fa671abe98808969076ce0fc835334e524494f5
ed90fcbfd1112545fa742e07131159bb3a68246a
/smry/server-auth/ls/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/forwarding_rules/list.py
420747d1e4cd001700ebe47795d47ba909b0cde5
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wemanuel/smry
2588f2a2a7b7639ebb6f60b9dc2833f1b4dee563
b7f676ab7bd494d71dbb5bda1d6a9094dfaedc0a
refs/heads/master
2021-01-10T21:56:55.226753
2015-08-01T13:37:06
2015-08-01T13:37:06
40,047,329
0
1
Apache-2.0
2020-07-24T18:32:40
2015-08-01T13:26:17
Python
UTF-8
Python
false
false
662
py
# Copyright 2014 Google Inc. All Rights Reserved. """Command for listing forwarding rules.""" from googlecloudsdk.compute.lib import base_classes class List(base_classes.GlobalRegionalLister): """List forwarding rules.""" @property def global_service(self): return self.compute.globalForwardingRules @property def regional_service(self): return self.compute.forwardingRules @property def resource_type(self): return 'forwardingRules' @property def allowed_filtering_types(self): return ['globalForwardingRules', 'forwardingRules'] List.detailed_help = ( base_classes.GetGlobalRegionalListerHelp('forwarding rules'))
[ "wre@thenandchange.org" ]
wre@thenandchange.org
37ce072cd49cfa75a020424ba47b3567ee618bf6
688c226e30e9d1a9ad7ddaaec75ad456d7b4981b
/other/mokuai/zidingyimodel3.py
bc149f83381545faf60dff8bcc137cc94508e8cc
[]
no_license
imklever/pay
a465e926330f5a804d3ef1deeba4353af00fd212
26bc73d40af33d8a47993ff37e0f0daec4d15e38
refs/heads/master
2021-10-08T21:36:15.398969
2018-12-18T02:41:05
2018-12-18T02:41:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
321
py
#coding:utf-8 #引入模块 #from ...... import * 语句 #作用:把一个模块中所有的内容全部导入当前命名空间 from sunck import * #最好不要过多的使用 ''' 程序内容的函数可以将模块中的同名函数覆盖 def sayGood(): print("*********") ''' sayGood() sayNice() print(TT)
[ "yanghaotai@163.com" ]
yanghaotai@163.com
9ef7aad2085be69c81499e3e2221ebfb956da801
09c87fe780df6d1f9eb33799ed516a0bbd7ab1e3
/Research/wx doco/somelongthread1_main.py
cbb1357ac048bde246e5fe80e2ae4985131c26f3
[]
no_license
abulka/pynsource
8ad412b85dc1acaeb83d7d34af8cc033c6baba91
979436525c57fdaeaa832e960985e0406e123587
refs/heads/master
2023-04-13T12:58:02.911318
2023-04-11T09:56:32
2023-04-11T09:56:32
32,249,425
271
46
null
2022-10-10T04:36:57
2015-03-15T07:21:43
Python
UTF-8
Python
false
false
2,698
py
# simple front end to long running thread - so can have two frames at once # which is what is problematic under linux and mac os x import wx import wx.lib.ogl as ogl from somelongthread1 import MainFrame class MainHost(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(250, 150)) self.add_ogl_canvas() self.Centre() self.Show(True) wx.FutureCall(500, self.DrawLine) wx.FutureCall(1000, self.OpenSecondFrameWithThreadInside) def add_ogl_canvas(self): # Add OGL sizer = wx.BoxSizer(wx.VERTICAL) # put stuff into sizer self.canvas = canvas = ogl.ShapeCanvas(self) sizer.Add(canvas, 1, wx.GROW) canvas.SetBackgroundColour("LIGHT BLUE") # diagram = ogl.Diagram() canvas.SetDiagram(diagram) diagram.SetCanvas(canvas) def setpos(shape, x, y): width, height = shape.GetBoundingBoxMax() shape.SetX(x + width / 2) shape.SetY(y + height / 2) def getpos(shape): width, height = shape.GetBoundingBoxMax() x = shape.GetX() y = shape.GetY() return (x - width / 2, y - height / 2) shape = ogl.RectangleShape(60, 60) setpos(shape, 0, 0) canvas.AddShape(shape) shape = ogl.RectangleShape(60, 60) setpos(shape, 60, 0) canvas.AddShape(shape) shape = ogl.RectangleShape(60, 60) setpos(shape, 120, 0) canvas.AddShape(shape) # Next row shape = ogl.RectangleShape(100, 100) setpos(shape, 0, 60) canvas.AddShape(shape) shape = ogl.RectangleShape(100, 100) setpos(shape, 100, 60) canvas.AddShape(shape) print([getpos(shape) for shape in canvas.GetDiagram().GetShapeList()]) diagram.ShowAll(1) # apply sizer self.SetSizer(sizer) self.SetAutoLayout(1) # self.Show(1) def DrawLine(self): dc = wx.ClientDC(self.canvas) dc.DrawLine(50, 60, 190, 60) dc.DrawArc(50, 50, 50, 10, 20, 20) dc.DrawEllipticArc(10, 10, 50, 20, 0, 180) points = [wx.Point(10, 10), wx.Point(15, 55), wx.Point(40, 30)] dc.DrawSpline(points) def OpenSecondFrameWithThreadInside(self): # Add opening of second frame here. # f = MainFrame(self, -1) f.Show(True) # b = LayoutBlackboard(graph=self.context.model.graph, umlwin=self.context.umlwin) # f.SetBlackboardObject(b) f.OnStart(None) app = wx.App() ogl.OGLInitialize() MainHost(None, -1, "Line") app.MainLoop()
[ "abulka@gmail.com" ]
abulka@gmail.com