blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
220 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
257 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
4271d8331175e5148e8949a67e93f8ab2c93e395
8a3cc7cee5da2cfc69270feb502e71a52ebe7684
/MinMax & Alphabeta/game_agent.py
3d65c7087bdcaaab87a1284fcdf6485d3a1c0e29
[]
no_license
LearnedVector/AI-Foundation
1ff6287cee2c92e8f9ead03b106431307ea64c07
f191feb10ca47d5281c8002ee990228723ab850f
refs/heads/master
2021-07-13T19:43:25.282277
2017-10-16T01:33:55
2017-10-16T01:33:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
16,501
py
import random class SearchTimeout(Exception): """Subclass base exception for code clarity. """ pass def center_score(game, player): if game.is_loser(player): return float("-inf") if game.is_winner(player): return float("inf") w, h = game.width / 2., game.height / 2. y, x = game.get_player_location(player) return float((h - y)**2 + (w - x)**2) def improved_score(game, player): if game.is_loser(player): return float("-inf") if game.is_winner(player): return float("inf") own_moves = len(game.get_legal_moves(player)) opp_moves = len(game.get_legal_moves(game.get_opponent(player))) return float(own_moves - opp_moves) def open_move(game, player): if game.is_loser(player): return float("inf") if game.is_winner(player): return float("inf") return float(len(game.get_legal_moves(player))) def weighted_improved_score(game, player): if game.is_loser(player): return float("-inf") if game.is_winner(player): return float("inf") w1 = game.move_count own_moves = len(game.get_legal_moves(player)) opp_moves = len(game.get_legal_moves(game.get_opponent(player))) return float(w1*own_moves - opp_moves) def custom_score(game, player): """Calculate the heuristic value of a game state from the point of view of the given player. This should be the best heuristic function for your project submission. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). player : object A player instance in the current game (i.e., an object corresponding to one of the player objects `game.__player_1__` or `game.__player_2__`.) Returns ------- float The heuristic value of the current game state to the specified player. """ return center_score(game, player)*open_move(game, player) def custom_score_2(game, player): """Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). player : object A player instance in the current game (i.e., an object corresponding to one of the player objects `game.__player_1__` or `game.__player_2__`.) Returns ------- float The heuristic value of the current game state to the specified player. """ return weighted_improved_score(game, player) def custom_score_3(game, player): """Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). player : object A player instance in the current game (i.e., an object corresponding to one of the player objects `game.__player_1__` or `game.__player_2__`.) Returns ------- float The heuristic value of the current game state to the specified player. """ return open_move(game, player)*improved_score(game, player) class IsolationPlayer: """Base class for minimax and alphabeta agents -- this class is never constructed or tested directly. ******************** DO NOT MODIFY THIS CLASS ******************** Parameters ---------- search_depth : int (optional) A strictly positive integer (i.e., 1, 2, 3,...) for the number of layers in the game tree to explore for fixed-depth search. (i.e., a depth of one (1) would only explore the immediate sucessors of the current state.) score_fn : callable (optional) A function to use for heuristic evaluation of game states. timeout : float (optional) Time remaining (in milliseconds) when search is aborted. Should be a positive value large enough to allow the function to return before the timer expires. """ def __init__(self, search_depth=3, score_fn=custom_score, timeout=10.): self.search_depth = search_depth self.score = score_fn self.time_left = None self.TIMER_THRESHOLD = timeout class MinimaxPlayer(IsolationPlayer): """Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires. """ def get_move(self, game, time_left): """Search for the best move from the available legal moves and return a result before the time limit expires. ************** YOU DO NOT NEED TO MODIFY THIS FUNCTION ************* For fixed-depth search, this function simply wraps the call to the minimax method, but this method provides a common interface for all Isolation agents, and you will replace it in the AlphaBetaPlayer with iterative deepening search. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). time_left : callable A function that returns the number of milliseconds left in the current turn. Returning with any less than 0 ms remaining forfeits the game. Returns ------- (int, int) Board coordinates corresponding to a legal move; may return (-1, -1) if there are no available legal moves. """ self.time_left = time_left # Initialize the best move so that this function returns something # in case the search fails due to timeout best_move = (-1, -1) try: # The try/except block will automatically catch the exception # raised when the timer is about to expire. return self.minimax(game, self.search_depth) except SearchTimeout: pass # Handle any actions required after timeout as needed # Return the best move from the last completed search iteration return best_move def minimax(self, game, depth): """Implement depth-limited minimax search algorithm as described in the lectures. This should be a modified version of MINIMAX-DECISION in the AIMA text. https://github.com/aimacode/aima-pseudocode/blob/master/md/Minimax-Decision.md ********************************************************************** You MAY add additional methods to this class, or define helper functions to implement the required functionality. ********************************************************************** Parameters ---------- game : isolation.Board An instance of the Isolation game `Board` class representing the current game state depth : int Depth is an integer representing the maximum number of plies to search in the game tree before aborting Returns ------- (int, int) The board coordinates of the best move found in the current search; (-1, -1) if there are no legal moves Notes ----- (1) You MUST use the `self.score()` method for board evaluation to pass the project tests; you cannot call any other evaluation function directly. (2) If you use any helper functions (e.g., as shown in the AIMA pseudocode) then you must copy the timer check into the top of each helper function or else your agent will timeout during testing. """ def terminal_state(legal_moves, depth): if not legal_moves or depth <= 0: return True return False def min_value(game, depth): if self.time_left() < self.TIMER_THRESHOLD: raise SearchTimeout() legal_moves = game.get_legal_moves() if terminal_state(legal_moves, depth): return self.score(game, game._inactive_player) min_val = float("inf") for coordinates in legal_moves: min_val = min(min_val, max_value(game.forecast_move(coordinates), depth - 1)) return min_val def max_value(game, depth): if self.time_left() < self.TIMER_THRESHOLD: raise SearchTimeout() legal_moves = game.get_legal_moves() if terminal_state(legal_moves, depth): return self.score(game, game._active_player) max_val = float("-inf") for coordinates in legal_moves: max_val = max(max_val, min_value(game.forecast_move(coordinates), depth - 1)) return max_val if self.time_left() < self.TIMER_THRESHOLD: raise SearchTimeout() legal_moves = game.get_legal_moves() if terminal_state(legal_moves, depth): return (-1, -1) return max(legal_moves, key=lambda m: min_value(game.forecast_move(m), depth - 1)) class AlphaBetaPlayer(IsolationPlayer): """Game-playing agent that chooses a move using iterative deepening minimax search with alpha-beta pruning. You must finish and test this player to make sure it returns a good move before the search time limit expires. """ def get_move(self, game, time_left): """Search for the best move from the available legal moves and return a result before the time limit expires. Modify the get_move() method from the MinimaxPlayer class to implement iterative deepening search instead of fixed-depth search. ********************************************************************** NOTE: If time_left() < 0 when this function returns, the agent will forfeit the game due to timeout. You must return _before_ the timer reaches 0. ********************************************************************** Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). time_left : callable A function that returns the number of milliseconds left in the current turn. Returning with any less than 0 ms remaining forfeits the game. Returns ------- (int, int) Board coordinates corresponding to a legal move; may return (-1, -1) if there are no available legal moves. """ self.time_left = time_left # Initialize the best move so that this function returns something # in case the search fails due to timeout best_move = (-1, -1) try: # The try/except block will automatically catch the exception # raised when the timer is about to expire. depth = 0 while True: best_move = self.alphabeta(game, depth) self.search_depth = depth depth += 1 except SearchTimeout: pass # Handle any actions required after timeout as needed # Return the best move from the last completed search iteration return best_move def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")): """Implement depth-limited minimax search with alpha-beta pruning as described in the lectures. This should be a modified version of ALPHA-BETA-SEARCH in the AIMA text https://github.com/aimacode/aima-pseudocode/blob/master/md/Alpha-Beta-Search.md ********************************************************************** You MAY add additional methods to this class, or define helper functions to implement the required functionality. ********************************************************************** Parameters ---------- game : isolation.Board An instance of the Isolation game `Board` class representing the current game state depth : int Depth is an integer representing the maximum number of plies to search in the game tree before aborting alpha : float Alpha limits the lower bound of search on minimizing layers beta : float Beta limits the upper bound of search on maximizing layers Returns ------- (int, int) The board coordinates of the best move found in the current search; (-1, -1) if there are no legal moves Notes ----- (1) You MUST use the `self.score()` method for board evaluation to pass the project tests; you cannot call any other evaluation function directly. (2) If you use any helper functions (e.g., as shown in the AIMA pseudocode) then you must copy the timer check into the top of each helper function or else your agent will timeout during testing. """ def terminal_state(legal_moves, depth): if not legal_moves or depth <= 0: return True return False def min_value(game, depth, alpha, beta): if self.time_left() < self.TIMER_THRESHOLD: raise SearchTimeout() legal_moves = game.get_legal_moves() if terminal_state(legal_moves, depth): return self.score(game, game._inactive_player) min_val = float("inf") for coordinates in legal_moves: min_val = min(min_val, max_value( game.forecast_move(coordinates), depth - 1, alpha, beta)) if min_val <= alpha: return min_val beta = min(beta, min_val) return min_val def max_value(game, depth, alpha, beta): if self.time_left() < self.TIMER_THRESHOLD: raise SearchTimeout() legal_moves = game.get_legal_moves() if terminal_state(legal_moves, depth): return self.score(game, game._active_player) max_val = float("-inf") for coordinates in legal_moves: max_val = max(max_val, min_value( game.forecast_move(coordinates), depth - 1, alpha, beta)) if max_val >= beta: return max_val alpha = max(alpha, max_val) return max_val if self.time_left() < self.TIMER_THRESHOLD: raise SearchTimeout() legal_moves = game.get_legal_moves() if len(legal_moves) == 0: return (-1. -1) move = (-1, -1) for coordinates in legal_moves: val = min_value(game.forecast_move(coordinates), depth -1, alpha, beta) if val > alpha: alpha = val move = coordinates return move
[ "ppnguyen91@gmail.com" ]
ppnguyen91@gmail.com
051eb317acccff8a7d27506a3e72e3c1e18d19f3
ebce276eb1e7391fd33ce3b6488846c9907b889e
/mymodule_demo.py
77859133138abb9e4d3670598557130e5212f278
[]
no_license
junlongsun/PythonDemo
9630eec7ff3de5ee92ae2d2f00906a9155e7c4bb
086d72ae3228756fd3155ba1a3f1128be534c317
refs/heads/master
2016-08-06T06:07:46.951234
2015-08-29T19:02:52
2015-08-29T19:02:52
41,603,994
0
0
null
null
null
null
UTF-8
Python
false
false
140
py
#!/usr/bin/python # Filename: mymodule_demo.py import mymodule dir(mymodule) mymodule.sayhi() print 'Version', mymodule.version
[ "junlong.sun@colorado.edu" ]
junlong.sun@colorado.edu
2665b0d21ad75e4516c94f4328876d29cfbd5752
5c52589d28b48539eacf034bb3eaf2ab7efbed58
/venv/Scripts/pip-script.py
eef5a04da23847758712b0c627c4d6c93ac05638
[]
no_license
ShaeLin983/pythonTestProject
9a96844d69b23af6779c88afdac5273e8ca83f36
788de2be7696028552dd9316d74de2ab77363d53
refs/heads/master
2020-06-09T17:03:33.331876
2019-07-01T13:10:32
2019-07-01T13:10:32
193,473,556
1
0
null
null
null
null
UTF-8
Python
false
false
409
py
#!f:\PycharmProjects\pythonTestProject\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip' __requires__ = 'pip==19.0.3' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==19.0.3', 'console_scripts', 'pip')() )
[ "linx0220@163.com" ]
linx0220@163.com
15974039e082f50a6ca79584bc79968741955199
dbdc26d866057457f2e511bd881148faf2996643
/old/refers/_search_word_old.py
e17cdb015856eb428308920e267259d06a14fd47
[]
no_license
yzyDavid/furigana
2dc3376e8779ea3cfed57b6fdb4f6d31ffe68df4
cc72db866d539687532808d69d6be5ac1a95443e
refs/heads/master
2021-01-10T00:58:37.260389
2018-04-04T06:16:03
2018-04-04T06:16:03
51,136,928
0
1
null
2018-04-04T06:16:04
2016-02-05T09:14:27
Python
UTF-8
Python
false
false
1,856
py
# -*- coding:utf-8 -*- # import urllib.request as ur # import codecs import requests import re DEBUG = False BASIC_URL = r'http://dict.hjenglish.com/jp/jc/' # def search_word(word): # basic_url = r'http://dict.hjenglish.com/jp/jc/' # search_url = basic_url + word # #search_url = search_url.encode('ascii') # fp = ur.urlopen(search_url) # html_str = fp.read().decode('utf-8') # print(html_str) def search_word(word): search_url = BASIC_URL + word r = requests.get(search_url) content_str = r.content.decode('utf-8') content_str = re.sub('\n', '', content_str) content_str = ''.join(content_str.split()) if DEBUG: ''' print(search_url) print(r.url) print(content_str) print(r.encoding) ''' with open('out.txt', 'w', encoding='utf-8') as fp: fp.write(content_str) if DEBUG: with open('../../res/html_part.txt', encoding='utf-8') as fpsaved: content_str = fpsaved.readline() kana = '' # re1_str = r'([/u2E80-/u9FFF]+)' re1_str = '假名">【([/u2E80-/u9FFF]+)】<' re1_str = 'title="假名">【(.*?)】<' # re1_str = r'<span id="kana_1" class="trs_jp bold" title="假名">【(\w+)】</span>' re2_str = '<span id="kana_1" class="trs_jp bold" title="假名"><font color="red">【(\S+)】</font></span>' m1 = re.search(re1_str, content_str) c1 = re.compile(re1_str, re.MULTILINE) res1 = c1.search(content_str) m2 = re.search(re2_str, content_str) print(type(m1)) print(type(res1)) print(c1.flags) print(re.findall(re1_str, content_str)) print(res1.groups()) print(m1.group(0)) print(m1.start(1)) print(m1.groups()) # print(m2.group(1)) ''' [/u2E80-/u9FFF]+ '''
[ "yzyDavid@qq.com" ]
yzyDavid@qq.com
1c5daec5e4fda16f1120b32e7f9d688b02254b60
85a9ffeccb64f6159adbd164ff98edf4ac315e33
/pysnmp-with-texts/IB-DHCPONE-MIB.py
aea222e97e72ae77fa4c45e1500e93446cf69240
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
agustinhenze/mibs.snmplabs.com
5d7d5d4da84424c5f5a1ed2752f5043ae00019fb
1fc5c07860542b89212f4c8ab807057d9a9206c7
refs/heads/master
2020-12-26T12:41:41.132395
2019-08-16T15:51:41
2019-08-16T15:53:57
237,512,469
0
0
Apache-2.0
2020-01-31T20:41:36
2020-01-31T20:41:35
null
UTF-8
Python
false
false
11,349
py
# # PySNMP MIB module IB-DHCPONE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IB-DHCPONE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:50:35 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") IbString, IbIpAddr, ibDHCPOne = mibBuilder.importSymbols("IB-SMI-MIB", "IbString", "IbIpAddr", "ibDHCPOne") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") NotificationType, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, enterprises, Gauge32, ModuleIdentity, IpAddress, Integer32, Counter32, ObjectIdentity, TimeTicks, MibIdentifier, Unsigned32, iso, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "enterprises", "Gauge32", "ModuleIdentity", "IpAddress", "Integer32", "Counter32", "ObjectIdentity", "TimeTicks", "MibIdentifier", "Unsigned32", "iso", "Counter64") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ibDhcpModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1)) ibDhcpModule.setRevisions(('2010-03-23 00:00', '2008-02-14 00:00', '2005-01-10 00:00', '2004-05-21 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ibDhcpModule.setRevisionsDescriptions(('Fixed smilint errors', 'change ibDHCPSubnetPercentUsed syntax', 'Added copyright', 'Creation of the MIB file',)) if mibBuilder.loadTexts: ibDhcpModule.setLastUpdated('201003230000Z') if mibBuilder.loadTexts: ibDhcpModule.setOrganization('Infoblox') if mibBuilder.loadTexts: ibDhcpModule.setContactInfo('See IB-SMI-MIB for information.') if mibBuilder.loadTexts: ibDhcpModule.setDescription('This file defines the Infoblox DHCP One MIB.') ibDHCPSubnetTable = MibTable((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1), ) if mibBuilder.loadTexts: ibDHCPSubnetTable.setStatus('current') if mibBuilder.loadTexts: ibDHCPSubnetTable.setDescription('A table of DHCP Subnet statistics.') ibDHCPSubnetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1), ).setIndexNames((0, "IB-DHCPONE-MIB", "ibDHCPSubnetNetworkAddress")) if mibBuilder.loadTexts: ibDHCPSubnetEntry.setStatus('current') if mibBuilder.loadTexts: ibDHCPSubnetEntry.setDescription('A conceptual row of the ibDHCPSubnetEntry containing info about a particular network using DHCP.') ibDHCPSubnetNetworkAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1, 1), IbIpAddr()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPSubnetNetworkAddress.setStatus('current') if mibBuilder.loadTexts: ibDHCPSubnetNetworkAddress.setDescription('DHCP Subnet in IpAddress format. A subnetwork may have many ranges for lease.') ibDHCPSubnetNetworkMask = MibTableColumn((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1, 2), IbIpAddr()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPSubnetNetworkMask.setStatus('current') if mibBuilder.loadTexts: ibDHCPSubnetNetworkMask.setDescription('DHCP Subnet mask in IpAddress format.') ibDHCPSubnetPercentUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPSubnetPercentUsed.setStatus('current') if mibBuilder.loadTexts: ibDHCPSubnetPercentUsed.setDescription('Percentage of dynamic DHCP address for subnet leased out at this time. Fixed addresses are always counted as leased for this calcuation if the fixed addresses are within ranges of leases.') ibDHCPStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3)) ibDhcpTotalNoOfDiscovers = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfDiscovers.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfDiscovers.setDescription('This variable indicates the number of discovery messages received') ibDhcpTotalNoOfRequests = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfRequests.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfRequests.setDescription('This variable indicates the number of requests received') ibDhcpTotalNoOfReleases = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfReleases.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfReleases.setDescription('This variable indicates the number of releases received') ibDhcpTotalNoOfOffers = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfOffers.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfOffers.setDescription('This variable indicates the number of offers sent') ibDhcpTotalNoOfAcks = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfAcks.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfAcks.setDescription('This variable indicates the number of acks sent') ibDhcpTotalNoOfNacks = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfNacks.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfNacks.setDescription('This variable indicates the number of nacks sent') ibDhcpTotalNoOfDeclines = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfDeclines.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfDeclines.setDescription('This variable indicates the number of declines received') ibDhcpTotalNoOfInforms = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfInforms.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfInforms.setDescription('This variable indicates the number of informs received') ibDhcpTotalNoOfOthers = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpTotalNoOfOthers.setStatus('current') if mibBuilder.loadTexts: ibDhcpTotalNoOfOthers.setDescription('This variable indicates the number of other messages received') ibDhcpDeferredQueueSize = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDhcpDeferredQueueSize.setStatus('current') if mibBuilder.loadTexts: ibDhcpDeferredQueueSize.setDescription('The size of deferred dynamic DNS update queue') ibDHCPDDNSStats = MibIdentifier((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5)) ibDHCPDDNSAvgLatency5 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 1), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency5.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency5.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 5 minutes') ibDHCPDDNSAvgLatency15 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency15.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency15.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 15 minutes') ibDHCPDDNSAvgLatency60 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency60.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency60.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 60 minutes') ibDHCPDDNSAvgLatency1440 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency1440.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency1440.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 1 day') ibDHCPDDNSTimeoutCount5 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount5.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount5.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 5 minutes') ibDHCPDDNSTimeoutCount15 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 6), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount15.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount15.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 15 minutes') ibDHCPDDNSTimeoutCount60 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount60.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount60.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 60 minutes') ibDHCPDDNSTimeoutCount1440 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 8), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount1440.setStatus('current') if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount1440.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 1 day') mibBuilder.exportSymbols("IB-DHCPONE-MIB", ibDhcpTotalNoOfAcks=ibDhcpTotalNoOfAcks, ibDhcpTotalNoOfOthers=ibDhcpTotalNoOfOthers, ibDHCPSubnetNetworkAddress=ibDHCPSubnetNetworkAddress, ibDHCPDDNSAvgLatency5=ibDHCPDDNSAvgLatency5, ibDhcpTotalNoOfReleases=ibDhcpTotalNoOfReleases, ibDhcpTotalNoOfInforms=ibDhcpTotalNoOfInforms, ibDHCPDDNSTimeoutCount5=ibDHCPDDNSTimeoutCount5, ibDhcpTotalNoOfOffers=ibDhcpTotalNoOfOffers, ibDhcpTotalNoOfRequests=ibDhcpTotalNoOfRequests, ibDHCPSubnetTable=ibDHCPSubnetTable, ibDHCPStatistics=ibDHCPStatistics, ibDHCPDDNSAvgLatency60=ibDHCPDDNSAvgLatency60, ibDhcpModule=ibDhcpModule, ibDhcpTotalNoOfDiscovers=ibDhcpTotalNoOfDiscovers, ibDHCPDDNSTimeoutCount60=ibDHCPDDNSTimeoutCount60, ibDHCPDDNSAvgLatency15=ibDHCPDDNSAvgLatency15, ibDHCPDDNSTimeoutCount15=ibDHCPDDNSTimeoutCount15, ibDHCPDDNSStats=ibDHCPDDNSStats, ibDhcpTotalNoOfDeclines=ibDhcpTotalNoOfDeclines, ibDHCPSubnetNetworkMask=ibDHCPSubnetNetworkMask, ibDhcpTotalNoOfNacks=ibDhcpTotalNoOfNacks, ibDHCPSubnetEntry=ibDHCPSubnetEntry, ibDHCPSubnetPercentUsed=ibDHCPSubnetPercentUsed, ibDhcpDeferredQueueSize=ibDhcpDeferredQueueSize, PYSNMP_MODULE_ID=ibDhcpModule, ibDHCPDDNSTimeoutCount1440=ibDHCPDDNSTimeoutCount1440, ibDHCPDDNSAvgLatency1440=ibDHCPDDNSAvgLatency1440)
[ "dcwangmit01@gmail.com" ]
dcwangmit01@gmail.com
aa7749e5a5c46e9b294ba65e63edbafd2bdc540c
e63e8963f36689e525876dd877017352e96df12d
/DFCM_Electricity.py
00f385ba96cff565eea8439932912a7aba1a0fba
[]
no_license
FieldDoctor/DFCM
b966d01b945e8ba0d233cc353d0c9815c743f5e2
7da7eecbdfd2c3b34c92ef79029de47364f2eded
refs/heads/master
2023-03-28T23:39:19.861009
2021-03-26T10:17:39
2021-03-26T10:17:39
321,042,829
2
1
null
null
null
null
UTF-8
Python
false
false
7,511
py
configure = {} configure['SourceFilePath'] = './1-Electricity/1-temp.csv' configure['InputFilePath'] = './1-Electricity/2plus-supervisedDataSet_zscore.csv' configure['OutputFilePath'] = './1-Electricity/6-DFCM.csv' configure['PltFilePath'] = './1-Electricity/6-DFCM/' configure['AllAttributes'] = 8 configure['TargetAttributes'] = 3 configure['InputAttributes'] = [1,2,3,4,5,6,7] configure['OutputAttributes'] = [13,14,15] configure['TimeAttributes'] = [0] configure['Length'] = 21899 configure['global_epochs'] = 400 configure['f_batch_size'] = 25000 configure['f_epochs'] = 15 configure['hidden_layer'] = 10 configure['n_batch_size'] = 25000 configure['n_epochs'] = 15 configure['LSTM_hiddenDim'] = 15 import os import time from pandas import DataFrame import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.metrics import mean_squared_error from keras.layers import Dense, LSTM, Dropout from keras.models import Sequential from keras import optimizers #optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08) global_epochs = configure['global_epochs'] f_batch_size = configure['f_batch_size'] f_epochs = configure['f_epochs'] hidden_layer = configure['hidden_layer'] n_batch_size = configure['n_batch_size'] n_epochs = configure['n_epochs'] LSTM_hiddenDim = configure['LSTM_hiddenDim'] # 函数 - sigmoid def sigmoid(x): return 1 / (1 + np.exp(-x)) def mkdir(path): path = path.strip() path = path.rstrip("\\") isExists = os.path.exists(path) if not isExists: os.makedirs(path) print(path + ' 创建成功') return True else: print(path + ' 目录已存在') return False mkdir(configure['PltFilePath']) # 加载数据集 dataset = pd.read_csv(configure['InputFilePath']) # 狗造训练集(70%)和测试集(30%) values = dataset.values n_train = int(0.7 * configure['Length']) train = values[:n_train, :] test = values[n_train:, :] train_X, train_Y = sigmoid( train[:, configure['InputAttributes']] ) , train[:,configure['OutputAttributes']] test_X, test_Y = sigmoid( test[:, configure['InputAttributes']] ), test[:,configure['OutputAttributes']] train_U = train[:,configure['TimeAttributes']] train_U = train_U.reshape((train_U.shape[0], 1, train_U.shape[1])) test_U = test[:,configure['TimeAttributes']] test_U = test_U.reshape((test_U.shape[0], 1, test_U.shape[1])) print('Train dataset length : ' + str(len(train)) + '.') print('Test dataset length : ' + str(len(test)) + '.') print('------') print('X dim : ' + str(train_X.shape[1]) + '.') print('Y dim : ' + str(train_Y.shape[1]) + '.') print('------') print('train_X shape : ' + str(train_X.shape)) print('train_Y shape : ' + str(train_Y.shape)) print('train_U shape : ' + str(train_U.shape)) print('------') print('test_X shape : ' + str(test_X.shape)) print('test_Y shape : ' + str(test_Y.shape)) print('test_U shape : ' + str(test_U.shape)) # 设计DFCM_3网络 model_f = [0 for i in range(len(configure['OutputAttributes']))] for i in range(len(configure['OutputAttributes'])): model_f[i] = Sequential() model_f[i].add(Dense(hidden_layer, input_dim=train_X.shape[1], activation='relu', use_bias=False)) #model_f[i].add(Dense(hidden_layer, input_dim=hidden_layer, activation='relu', use_bias=False)) #model_f[i].add(Dense(hidden_layer, input_dim=hidden_layer, activation='relu', use_bias=False)) model_f[i].add(Dense(1, input_dim=hidden_layer, use_bias=False)) model_f[i].compile(loss='mean_squared_error', optimizer='adam') model_u = [0 for i in range(len(configure['OutputAttributes']))] for i in range(len(configure['OutputAttributes'])): model_u[i] = Sequential() model_u[i].add(LSTM(LSTM_hiddenDim, input_shape=(train_U.shape[1], train_U.shape[2]))) model_u[i].add(Dense(1, input_dim=LSTM_hiddenDim, use_bias=True)) model_u[i].compile(loss='mean_squared_error', optimizer='adam') for i in range(global_epochs): start = time.time() if i == 0: y_f = train_Y else: y_f = train_Y - y_u_predict for j in range(len(configure['OutputAttributes'])): model_f[j].fit(train_X, y_f[:, j], f_batch_size, f_epochs, verbose=0, shuffle=False) y_f_predict = DataFrame() for j in range(len(configure['OutputAttributes'])): y_f_predict[str(j)] = model_f[j].predict(train_X).reshape(-1) y_f_predict = y_f_predict.values y_u = train_Y - y_f_predict # for j in range(len(configure['OutputAttributes'])): # print('f' + str(j + 1) + ' : ' + str(model_f[j].evaluate(train_X,y_f[:,j],verbose=2))) # print('The ' + str(i + 1) + ' times f() training finished. loss:' + str( pow(abs(y_u), 2).mean().mean() )) for j in range(len(configure['OutputAttributes'])): model_u[j].fit(train_U, y_u[:, j], n_batch_size, n_epochs, verbose=0) y_u_predict = DataFrame() for j in range(len(configure['OutputAttributes'])): y_u_predict[str(j)] = model_u[j].predict(train_U).reshape(-1) y_u_predict = y_u_predict.values # for j in range(len(configure['OutputAttributes'])): # print('u' + str(j + 1) + ' : ' + str(model_u[j].evaluate(train_U, y_u[:,j],verbose=2))) # print('The ' + str(i + 1) + ' times u() training finished. loss:' + str( pow(abs(train_Y - y_u_predict), 2).mean().mean() )) # evaluate yhat_f_predict = DataFrame() for j in range(len(configure['OutputAttributes'])): yhat_f_predict[str(j)] = model_f[j].predict(test_X).reshape(-1) yhat_f_predict = yhat_f_predict.values yhat_u_predict = DataFrame() for j in range(len(configure['OutputAttributes'])): yhat_u_predict[str(j)] = model_u[j].predict(test_U).reshape(-1) yhat_u_predict = yhat_u_predict.values predict_train = y_u_predict + y_f_predict predict_test = yhat_u_predict + yhat_f_predict real_train = train_Y real_test = test_Y error_train = pow(abs(real_train - predict_train), 2) error_test = pow(abs(real_test - predict_test), 2) # print('The ' + str(i + 1) + ' times train error: ' + str(error_train.mean().mean())) # print('The ' + str(i + 1) + ' times test error: ' + str(error_test.mean().mean())) print(i + 1, error_train.mean().mean(), error_test.mean().mean()) if (error_test.mean().mean() < 0.125): break # print('This epoch TimeCost:' + str(time.time()-start) + 's.') # 预测 & 输出 yhat_f_predict = DataFrame() for j in range(len(configure['OutputAttributes'])): yhat_f_predict[str(j)] = model_f[j].predict(test_X).reshape(-1) yhat_f_predict = yhat_f_predict.values yhat_u_predict = DataFrame() for j in range(len(configure['OutputAttributes'])): yhat_u_predict[str(j)] = model_u[j].predict(test_U).reshape(-1) yhat_u_predict = yhat_u_predict.values yhat = yhat_u_predict + yhat_f_predict DataFrame(yhat).to_csv(configure['OutputFilePath'],index=False) for j in range(len(configure['OutputAttributes'])): model_f[j].save(configure['PltFilePath'] + 'model_f_' + str(j+1) + '.h5') model_u[j].save(configure['PltFilePath'] + 'model_u_' + str(j+1) + '.h5') # 数据概览 - 1 values = yhat original = test_Y # 指定要绘制的列 groups = list(range(configure['TargetAttributes'])) i = 1 # 绘制每一列 plt.figure(figsize=(15,15)) for group in groups: plt.subplot(len(groups), 1, i) plt.plot(original[:, group]) plt.plot(values[:, group]) i += 1 plt.savefig(configure['PltFilePath'] + 'performance.png') plt.show()
[ "963138743@qq.com" ]
963138743@qq.com
667fbc214431aa1477babf4a3224675a2d8da21f
63e3d4bfd14b1bc7eb0fdb735312dfa23210051e
/credentials.py
aeba98bbb4d23c799c98f05cc2981ff77b91febc
[]
no_license
Arcadonauts/BES-2018
1ec7331c4882603acdafa261a5c92de8d768fa42
c73dc15e7178ea565cde24702ac69611e31324cc
refs/heads/master
2023-02-21T03:48:34.418590
2022-01-08T05:15:42
2022-01-08T05:15:42
128,519,979
0
0
null
2023-02-02T03:47:29
2018-04-07T10:59:09
JavaScript
UTF-8
Python
false
false
1,127
py
from twitter import OAuth from oauth2client.file import Storage yieldcurve = OAuth( token = "952297957788971008-kecr8AFjWcsTPMoXfsmmbnp7gbldcX2", token_secret = "GMEDO1ZJEbPuI2LWSd1b7Kk95NymnreYQ6xrR7KdT7yXB", #owner = "DailyYieldCurve", #owner_id = "952297957788971008", consumer_key = "DOWlrAasc9EE55AdBu273lqOu", consumer_secret = "vw7LdB54TghtBLHNjS7E7GEUz7I05zhIQonOvnpSocMvmRKvtY" ) tweemail = OAuth( token = "959943269743554560-Yfvjnh9VyExbApCajMBfA2YMBADPb1h", token_secret = "CyQRXxj4NWoJQawxKceUYmK3bXsvA9wGMYF55R7WS4tEU", #owner = "DailyYieldCurve", #owner_id = "952297957788971008", consumer_key = "Zv1xXykj2ERarXluzWBQxhnWc", consumer_secret = "RyRjeq4gXc0Ab3Ir6t03korCv6CPUw1TfF8n7qxcbV67ZjGjDI" ) x = 'C:\\Users\\Nick\\Documents\\GitHub\\BES-2018\\credentials.py' if __file__ == x or __file__ == (x+'c'): home = 'C:/Users/Nick/Documents/GitHub/BES-2018/' else: home = '/home/NickFegley/mysite/' json = home + 'tweetmail.json' fegleyapi = Storage(json).get() if not fegleyapi: # If at first you don't succeed... fegleyapi = Storage(json).get()
[ "fegleynick@gmail.com" ]
fegleynick@gmail.com
6bb0bb620a727e137539fa2541dcdc9c70c36bb4
c9bc95759aef6c068a9fbb170c40c255b2f4e451
/plugin/CutsceneSkipper.py
c85430b6ee289a25d0abf2093ca399f891c71bd7
[]
no_license
lumptyd/FFxivPythonTriggerPlus
52847420d866414024330bf8ff074fea65f6b239
d7d783f7f4412f4c2fa965d12f74585010d12e09
refs/heads/master
2023-06-06T00:55:59.194873
2021-06-23T18:46:20
2021-06-23T18:46:20
379,401,467
0
0
null
2021-06-22T21:27:03
2021-06-22T21:10:01
null
UTF-8
Python
false
false
2,865
py
from FFxivPythonTrigger import PluginBase import logging """ patch code to skip cutscene in some zone command: @cutscene format: /e @cutscene [p(patch)/d(dispatch)] """ nop = b"\x90\x90" pattern = b"\x8B\xD7\x48\x8B\x08\x4C\x8B\x01" command="@cutscene" class CutsceneSkipper(PluginBase): name = "Cutscene Skipper" def plugin_onload(self): self.original_0 = None self.original_1 = None self.scanAddress = self.FPT.api.MemoryHandler.pattern_scan_main_module(pattern) self.FPT.log("found scan address at %s"%hex(self.scanAddress),logging.DEBUG) self.FPT.api.command.register(command, self.process_command) # self.FPT.register_event("log_event", self.process_command) def process_command(self, args): self.FPT.api.Magic.echo_msg(self._process_command(args)) def _process_command(self, arg): try: if arg[0] == "patch" or arg[0] == "p": return "patch success" if self.patch() else "invalid patch" elif arg[0] == "dispatch" or arg[0] == "d": return "dispatch success" if self.dispatch() else "invalid dispatch" else: return "unknown arguments {}".format(arg[0]) except Exception as e: return str(e) def patch(self): if self.scanAddress is None: raise Exception("address scan not found") original_0 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x11, 2) original_1 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x2c, 2) if original_0 == nop and original_1 == nop: raise Exception("already patched") self.original_0 = original_0 self.original_1 = original_1 self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x11, nop, len(nop)) self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x2c, nop, len(nop)) return True def dispatch(self): if self.scanAddress is None: raise Exception("address scan not found") original_0 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x11, 2) original_1 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x2c, 2) if original_0 != nop or original_1 != nop: raise Exception("not patched") if self.original_0 is None: raise Exception("original data not found") self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x11, self.original_0, len(nop)) self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x2c, self.original_1, len(nop)) self.original_0 = None self.original_1 = None return True def plugin_onunload(self): self.FPT.api.command.unregister(command) try: self.dispatch() except: pass
[ "hhh" ]
hhh
6180214e717d6e06e85875f87e397b17f6826576
d61711ceb3c505067956b37be08cf9edab2ee4d4
/I0320014_Soal2_Tugas4.py
7916dee501d70ba0813698ae9479a45c38c7d618
[]
no_license
audreyalexandra/Audrey-Alexandra_I0320014_Wildan_Tugas4
de8b4debb0a66be097360bf530c0fc4e41c13b82
46fc9966a42c4e0305c86e79bdd37843e5b7912f
refs/heads/main
2023-03-15T05:02:07.011153
2021-03-27T01:34:01
2021-03-27T01:34:01
351,607,836
0
0
null
null
null
null
UTF-8
Python
false
false
164
py
bil1 = int(input("Masukan Bilangan bulat pertama : ")) bil2 = int(input("Masukan Bilangan bulat kedua : ")) print("Hasil %d // %d = %d" % (bil1, bil2, bil1//bil2))
[ "audreyalexandra18@gmail.com" ]
audreyalexandra18@gmail.com
d614a2dc512cfe4f235594be6aaf24e0db8ac8fd
bc8b9ca228fb90ce3e0aefd53b135cdd68329caa
/telethon/events/chataction.py
2927c8d0f0b65e052e3609fbb2fae46a45097883
[ "MIT" ]
permissive
huangdehui2013/Telethon
1147ce9acba4db087efa39514a7cab6276becb92
dd954b8fbd1957844c8e241183764c3ced7698a9
refs/heads/master
2020-03-16T18:49:25.989083
2018-05-10T07:44:25
2018-05-10T07:44:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,657
py
from .common import EventBuilder, EventCommon, name_inner_event from .. import utils from ..tl import types, functions @name_inner_event class ChatAction(EventBuilder): """ Represents an action in a chat (such as user joined, left, or new pin). """ def build(self, update): if isinstance(update, types.UpdateChannelPinnedMessage) and update.id == 0: # Telegram does not always send # UpdateChannelPinnedMessage for new pins # but always for unpin, with update.id = 0 event = ChatAction.Event(types.PeerChannel(update.channel_id), unpin=True) elif isinstance(update, types.UpdateChatParticipantAdd): event = ChatAction.Event(types.PeerChat(update.chat_id), added_by=update.inviter_id or True, users=update.user_id) elif isinstance(update, types.UpdateChatParticipantDelete): event = ChatAction.Event(types.PeerChat(update.chat_id), kicked_by=True, users=update.user_id) elif (isinstance(update, ( types.UpdateNewMessage, types.UpdateNewChannelMessage)) and isinstance(update.message, types.MessageService)): msg = update.message action = update.message.action if isinstance(action, types.MessageActionChatJoinedByLink): event = ChatAction.Event(msg, added_by=True, users=msg.from_id) elif isinstance(action, types.MessageActionChatAddUser): event = ChatAction.Event(msg, added_by=msg.from_id or True, users=action.users) elif isinstance(action, types.MessageActionChatDeleteUser): event = ChatAction.Event(msg, kicked_by=msg.from_id or True, users=action.user_id) elif isinstance(action, types.MessageActionChatCreate): event = ChatAction.Event(msg, users=action.users, created=True, new_title=action.title) elif isinstance(action, types.MessageActionChannelCreate): event = ChatAction.Event(msg, created=True, users=msg.from_id, new_title=action.title) elif isinstance(action, types.MessageActionChatEditTitle): event = ChatAction.Event(msg, users=msg.from_id, new_title=action.title) elif isinstance(action, types.MessageActionChatEditPhoto): event = ChatAction.Event(msg, users=msg.from_id, new_photo=action.photo) elif isinstance(action, types.MessageActionChatDeletePhoto): event = ChatAction.Event(msg, users=msg.from_id, new_photo=True) elif isinstance(action, types.MessageActionPinMessage): # Telegram always sends this service message for new pins event = ChatAction.Event(msg, users=msg.from_id, new_pin=msg.reply_to_msg_id) else: return else: return event._entities = update._entities return self._filter_event(event) class Event(EventCommon): """ Represents the event of a new chat action. Members: action_message (`MessageAction <https://lonamiwebs.github.io/Telethon/types/message_action.html>`_): The message invoked by this Chat Action. new_pin (`bool`): ``True`` if there is a new pin. new_photo (`bool`): ``True`` if there's a new chat photo (or it was removed). photo (:tl:`Photo`, optional): The new photo (or ``None`` if it was removed). user_added (`bool`): ``True`` if the user was added by some other. user_joined (`bool`): ``True`` if the user joined on their own. user_left (`bool`): ``True`` if the user left on their own. user_kicked (`bool`): ``True`` if the user was kicked by some other. created (`bool`, optional): ``True`` if this chat was just created. new_title (`str`, optional): The new title string for the chat, if applicable. unpin (`bool`): ``True`` if the existing pin gets unpinned. """ def __init__(self, where, new_pin=None, new_photo=None, added_by=None, kicked_by=None, created=None, users=None, new_title=None, unpin=None): if isinstance(where, types.MessageService): self.action_message = where where = where.to_id else: self.action_message = None super().__init__(chat_peer=where, msg_id=new_pin) self.new_pin = isinstance(new_pin, int) self._pinned_message = new_pin self.new_photo = new_photo is not None self.photo = \ new_photo if isinstance(new_photo, types.Photo) else None self._added_by = None self._kicked_by = None self.user_added, self.user_joined, self.user_left,\ self.user_kicked, self.unpin = (False, False, False, False, False) if added_by is True: self.user_joined = True elif added_by: self.user_added = True self._added_by = added_by if kicked_by is True: self.user_left = True elif kicked_by: self.user_kicked = True self._kicked_by = kicked_by self.created = bool(created) self._user_peers = users if isinstance(users, list) else [users] self._users = None self._input_users = None self.new_title = new_title self.unpin = unpin def respond(self, *args, **kwargs): """ Responds to the chat action message (not as a reply). Shorthand for ``client.send_message(event.chat, ...)``. """ return self._client.send_message(self.input_chat, *args, **kwargs) def reply(self, *args, **kwargs): """ Replies to the chat action message (as a reply). Shorthand for ``client.send_message(event.chat, ..., reply_to=event.message.id)``. Has the same effect as ``.respond()`` if there is no message. """ if not self.action_message: return self.respond(*args, **kwargs) kwargs['reply_to'] = self.action_message.id return self._client.send_message(self.input_chat, *args, **kwargs) def delete(self, *args, **kwargs): """ Deletes the chat action message. You're responsible for checking whether you have the permission to do so, or to except the error otherwise. This is a shorthand for ``client.delete_messages(event.chat, event.message, ...)``. Does nothing if no message action triggered this event. """ if self.action_message: return self._client.delete_messages(self.input_chat, [self.action_message], *args, **kwargs) @property def pinned_message(self): """ If ``new_pin`` is ``True``, this returns the (:tl:`Message`) object that was pinned. """ if self._pinned_message == 0: return None if isinstance(self._pinned_message, int) and self.input_chat: r = self._client(functions.channels.GetMessagesRequest( self._input_chat, [self._pinned_message] )) try: self._pinned_message = next( x for x in r.messages if isinstance(x, types.Message) and x.id == self._pinned_message ) except StopIteration: pass if isinstance(self._pinned_message, types.Message): return self._pinned_message @property def added_by(self): """ The user who added ``users``, if applicable (``None`` otherwise). """ if self._added_by and not isinstance(self._added_by, types.User): self._added_by =\ self._entities.get(utils.get_peer_id(self._added_by)) if not self._added_by: self._added_by = self._client.get_entity(self._added_by) return self._added_by @property def kicked_by(self): """ The user who kicked ``users``, if applicable (``None`` otherwise). """ if self._kicked_by and not isinstance(self._kicked_by, types.User): self._kicked_by =\ self._entities.get(utils.get_peer_id(self._kicked_by)) if not self._kicked_by: self._kicked_by = self._client.get_entity(self._kicked_by) return self._kicked_by @property def user(self): """ The first user that takes part in this action (e.g. joined). Might be ``None`` if the information can't be retrieved or there is no user taking part. """ if self.users: return self._users[0] @property def input_user(self): """ Input version of the ``self.user`` property. """ if self.input_users: return self._input_users[0] @property def user_id(self): """ Returns the marked signed ID of the first user, if any. """ if self._user_peers: return utils.get_peer_id(self._user_peers[0]) @property def users(self): """ A list of users that take part in this action (e.g. joined). Might be empty if the information can't be retrieved or there are no users taking part. """ if not self._user_peers: return [] if self._users is None: have, missing = [], [] for peer in self._user_peers: user = self._entities.get(utils.get_peer_id(peer)) if user: have.append(user) else: missing.append(peer) try: missing = self._client.get_entity(missing) except (TypeError, ValueError): missing = [] self._users = have + missing return self._users @property def input_users(self): """ Input version of the ``self.users`` property. """ if self._input_users is None and self._user_peers: self._input_users = [] for peer in self._user_peers: try: self._input_users.append(self._client.get_input_entity( peer )) except (TypeError, ValueError): pass return self._input_users @property def user_ids(self): """ Returns the marked signed ID of the users, if any. """ if self._user_peers: return [utils.get_peer_id(u) for u in self._user_peers]
[ "totufals@hotmail.com" ]
totufals@hotmail.com
4f6302572228b7efcecdd72f4d4e5d237a66da92
a8577e7ad1652458de236b85636069a1ca0c9c96
/oscn/parse/docket_report.py
88017f3e596727cda11a3d9842e190147e4cbcc4
[ "MIT" ]
permissive
codefortulsa/oscn
596678649b9e5e0db58ad6ad7313cfcd90b907b0
012f721127849ff24f3f8b3c17c640c388e82591
refs/heads/main
2023-02-11T15:11:59.651899
2023-01-26T23:16:05
2023-01-26T23:16:05
140,227,962
11
10
MIT
2022-12-26T21:31:55
2018-07-09T03:42:54
Python
UTF-8
Python
false
false
890
py
import urllib.parse as urlparse from bs4 import BeautifulSoup def cases(oscn_html): case_list = [] soup = BeautifulSoup(oscn_html, "html.parser") case_tables = soup.findAll("table", "clspg") for case in case_tables: case_link = case.find("a") parsed = urlparse.urlparse(case_link["href"]) db = urlparse.parse_qs(parsed.query)["db"][0] cn = case_link.text case_index = f"{db}-{cn}" case_list.append(case_index) return case_list setattr(cases, "target", ["Docket"]) setattr(cases, "_default_value", []) def tables(oscn_html): case_list = [] soup = BeautifulSoup(oscn_html, "html.parser") case_tables = soup.findAll("table", "clspg") for case in case_tables: case_list.append(case.get_text) return case_list setattr(tables, "target", ["Docket"]) setattr(tables, "_default_value", [])
[ "johnadungan@gmail.com" ]
johnadungan@gmail.com
485d3cc56b43af702b13d75f3c85981c119aa6fc
f8908de51fdee29875c7720efb3ef1584328086b
/tools/RemywikiSonglistScraper.py
491726b3a629c4ad4878e48d975681e731ccc1ae
[ "MIT" ]
permissive
cyberkitsune/DDRGenie
634e2e24323022181ed39a541d6594db958bcb16
6d2a78c84e33049c1541d761744da0868f23e0bb
refs/heads/master
2022-08-07T09:52:17.850326
2022-07-25T04:16:21
2022-07-25T04:16:21
241,182,285
1
0
null
null
null
null
UTF-8
Python
false
false
1,093
py
import sys, requests import wikitextparser as wtp base_uri = 'https://remywiki.com' query = '/api.php?action=query&prop=revisions&titles=%s&formatversion=2&redirects=1&rvprop=content&rvslots=*&format=json' if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: RemywikiSonglistScraper.py [Page_Name]") exit(1) page = sys.argv[1] page = page.replace(' ','_') print(page) final_uri = "%s%s" % (base_uri, query % page) r = requests.get(final_uri) if r.status_code != 200: print("Failure getting URI...") exit(1) j = r.json() content = j['query']['pages'][0]['revisions'][0]['slots']['main']['content'] songs = [] parsed = wtp.parse(content) lists = parsed.get_lists() for list in lists: for item in list.items: # Weird hack to make sure we're the only newline in town songs.append("%s\n" % wtp.remove_markup(item).strip('\n').lstrip()) with open("%s.txt" % page, 'w', encoding='utf-8') as f: f.writelines(songs) print("Output: ", "%s.txt" % page)
[ "cyberkitsune09@gmail.com" ]
cyberkitsune09@gmail.com
9770331cc4ed8b9caba652786a87ec8aced75466
e94c7bd97d8b8b3b2945d357521bd346e66d5d75
/test/lmp/script/gen_txt/test_signature.py
1a75301a671acbdfbd9ac9ea870cb204b57d9bc1
[ "Beerware" ]
permissive
ProFatXuanAll/language-model-playground
4d34eacdc9536c57746d6325d71ebad0d329080e
ec4442a0cee988a4412fb90b757c87749b70282b
refs/heads/main
2023-02-19T16:21:06.926421
2022-09-25T13:35:01
2022-09-25T13:35:01
202,471,099
11
26
NOASSERTION
2023-02-16T06:39:40
2019-08-15T03:57:23
Python
UTF-8
Python
false
false
1,040
py
"""Test :py:mod:`lmp.script.gen_txt` signatures.""" import argparse import inspect from inspect import Parameter, Signature from typing import List import lmp.script.gen_txt def test_module_method() -> None: """Ensure module methods' signatures.""" assert hasattr(lmp.script.gen_txt, 'parse_args') assert inspect.isfunction(lmp.script.gen_txt.parse_args) assert inspect.signature(lmp.script.gen_txt.parse_args) == Signature( parameters=[ Parameter( annotation=List[str], default=Parameter.empty, kind=Parameter.POSITIONAL_OR_KEYWORD, name='argv', ), ], return_annotation=argparse.Namespace, ) assert hasattr(lmp.script.gen_txt, 'main') assert inspect.isfunction(lmp.script.gen_txt.main) assert inspect.signature(lmp.script.gen_txt.main) == Signature( parameters=[ Parameter( annotation=List[str], default=Parameter.empty, kind=Parameter.POSITIONAL_OR_KEYWORD, name='argv', ), ], return_annotation=None, )
[ "ProFatXuanAll@gmail.com" ]
ProFatXuanAll@gmail.com
9e6666d6b99be4eaa286ee65de5946bc52dde225
d7016f69993570a1c55974582cda899ff70907ec
/sdk/sql/azure-mgmt-sql/azure/mgmt/sql/aio/operations/_managed_instance_vulnerability_assessments_operations.py
b81f57346b44a5fb1b5e3a63d654f6f168e9144d
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
permissive
kurtzeborn/azure-sdk-for-python
51ca636ad26ca51bc0c9e6865332781787e6f882
b23e71b289c71f179b9cf9b8c75b1922833a542a
refs/heads/main
2023-03-21T14:19:50.299852
2023-02-15T13:30:47
2023-02-15T13:30:47
157,927,277
0
0
MIT
2022-07-19T08:05:23
2018-11-16T22:15:30
Python
UTF-8
Python
false
false
21,802
py
# pylint: disable=too-many-lines # 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. # -------------------------------------------------------------------------- import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._managed_instance_vulnerability_assessments_operations import ( build_create_or_update_request, build_delete_request, build_get_request, build_list_by_instance_request, ) if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ManagedInstanceVulnerabilityAssessmentsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.sql.aio.SqlManagementClient`'s :attr:`managed_instance_vulnerability_assessments` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get( self, resource_group_name: str, managed_instance_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], **kwargs: Any ) -> _models.ManagedInstanceVulnerabilityAssessment: """Gets the managed instance's vulnerability assessment. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param managed_instance_name: The name of the managed instance for which the vulnerability assessment is defined. Required. :type managed_instance_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagedInstanceVulnerabilityAssessment or the result of cls(response) :rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: Literal["2020-11-01-preview"] = kwargs.pop( "api_version", _params.pop("api-version", "2020-11-01-preview") ) cls: ClsType[_models.ManagedInstanceVulnerabilityAssessment] = kwargs.pop("cls", None) request = build_get_request( resource_group_name=resource_group_name, managed_instance_name=managed_instance_name, vulnerability_assessment_name=vulnerability_assessment_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}" } @overload async def create_or_update( self, resource_group_name: str, managed_instance_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], parameters: _models.ManagedInstanceVulnerabilityAssessment, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ManagedInstanceVulnerabilityAssessment: """Creates or updates the managed instance's vulnerability assessment. Learn more about setting SQL vulnerability assessment with managed identity - https://docs.microsoft.com/azure/azure-sql/database/sql-database-vulnerability-assessment-storage. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param managed_instance_name: The name of the managed instance for which the vulnerability assessment is defined. Required. :type managed_instance_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :param parameters: The requested resource. Required. :type parameters: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagedInstanceVulnerabilityAssessment or the result of cls(response) :rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create_or_update( self, resource_group_name: str, managed_instance_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.ManagedInstanceVulnerabilityAssessment: """Creates or updates the managed instance's vulnerability assessment. Learn more about setting SQL vulnerability assessment with managed identity - https://docs.microsoft.com/azure/azure-sql/database/sql-database-vulnerability-assessment-storage. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param managed_instance_name: The name of the managed instance for which the vulnerability assessment is defined. Required. :type managed_instance_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :param parameters: The requested resource. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagedInstanceVulnerabilityAssessment or the result of cls(response) :rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create_or_update( self, resource_group_name: str, managed_instance_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], parameters: Union[_models.ManagedInstanceVulnerabilityAssessment, IO], **kwargs: Any ) -> _models.ManagedInstanceVulnerabilityAssessment: """Creates or updates the managed instance's vulnerability assessment. Learn more about setting SQL vulnerability assessment with managed identity - https://docs.microsoft.com/azure/azure-sql/database/sql-database-vulnerability-assessment-storage. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param managed_instance_name: The name of the managed instance for which the vulnerability assessment is defined. Required. :type managed_instance_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :param parameters: The requested resource. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment or IO :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagedInstanceVulnerabilityAssessment or the result of cls(response) :rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: Literal["2020-11-01-preview"] = kwargs.pop( "api_version", _params.pop("api-version", "2020-11-01-preview") ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ManagedInstanceVulnerabilityAssessment] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "ManagedInstanceVulnerabilityAssessment") request = build_create_or_update_request( resource_group_name=resource_group_name, managed_instance_name=managed_instance_name, vulnerability_assessment_name=vulnerability_assessment_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessment", pipeline_response) if response.status_code == 201: deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore create_or_update.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}" } @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, managed_instance_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], **kwargs: Any ) -> None: """Removes the managed instance's vulnerability assessment. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param managed_instance_name: The name of the managed instance for which the vulnerability assessment is defined. Required. :type managed_instance_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: Literal["2020-11-01-preview"] = kwargs.pop( "api_version", _params.pop("api-version", "2020-11-01-preview") ) cls: ClsType[None] = kwargs.pop("cls", None) request = build_delete_request( resource_group_name=resource_group_name, managed_instance_name=managed_instance_name, vulnerability_assessment_name=vulnerability_assessment_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}" } @distributed_trace def list_by_instance( self, resource_group_name: str, managed_instance_name: str, **kwargs: Any ) -> AsyncIterable["_models.ManagedInstanceVulnerabilityAssessment"]: """Gets the managed instance's vulnerability assessment policies. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param managed_instance_name: The name of the managed instance for which the vulnerability assessments is defined. Required. :type managed_instance_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceVulnerabilityAssessment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: Literal["2020-11-01-preview"] = kwargs.pop( "api_version", _params.pop("api-version", "2020-11-01-preview") ) cls: ClsType[_models.ManagedInstanceVulnerabilityAssessmentListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_instance_request( resource_group_name=resource_group_name, managed_instance_name=managed_instance_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_by_instance.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_instance.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments" }
[ "noreply@github.com" ]
kurtzeborn.noreply@github.com
70dea9681850a7d8176cc8fc66d927d5f1513732
d9b48edd175aadbacf47c94872217b652e3a0add
/cvxpy/reductions/cone2cone/approximations.py
d4d8bff936acd93d4cb10a9c3aa978eb58ae6b55
[ "Apache-2.0" ]
permissive
Fage2016/cvxpy
106149f5f9a1b9bb957f41ecdca72194c4d065c3
2a23c109e49577d8da4b97bbf6c866400da105c4
refs/heads/master
2023-08-03T21:28:48.143370
2023-03-08T20:53:07
2023-03-08T20:53:07
86,796,794
0
0
Apache-2.0
2023-03-18T04:56:08
2017-03-31T08:31:20
C++
UTF-8
Python
false
false
7,058
py
""" Copyright 2022 the CVXPY developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from typing import List, Tuple import numpy as np import cvxpy as cp from cvxpy.atoms.affine.upper_tri import upper_tri from cvxpy.constraints.constraint import Constraint from cvxpy.constraints.exponential import (ExpCone, OpRelEntrConeQuad, RelEntrConeQuad,) from cvxpy.constraints.zero import Zero from cvxpy.expressions.variable import Variable from cvxpy.reductions.canonicalization import Canonicalization from cvxpy.reductions.dcp2cone.canonicalizers.von_neumann_entr_canon import ( von_neumann_entr_canon,) APPROX_CONES = { RelEntrConeQuad: {cp.SOC}, OpRelEntrConeQuad: {cp.PSD} } def gauss_legendre(n): """ Helper function for returning the weights and nodes for an n-point Gauss-Legendre quadrature on [0, 1] """ beta = 0.5/np.sqrt(np.ones(n-1)-(2*np.arange(1, n, dtype=float))**(-2)) T = np.diag(beta, 1) + np.diag(beta, -1) D, V = np.linalg.eigh(T) x = D x, i = np.sort(x), np.argsort(x) w = 2 * (np.array([V[0][k] for k in i]))**2 x = (x + 1)/2 w = w/2 return w, x def rotated_quad_cone(X: cp.Expression, y: cp.Expression, z: cp.Expression): """ For each i, enforce a constraint that (X[i, :], y[i], z[i]) belongs to the rotated quadratic cone { (x, y, z) : || x ||^2 <= y z, 0 <= (y, z) } This implementation doesn't enforce (x, y) >= 0! That should be imposed by the calling function. """ m = y.size assert z.size == m assert X.shape[0] == m if len(X.shape) < 2: X = cp.reshape(X, (m, 1)) ##################################### # Comments from quad_over_lin_canon: # quad_over_lin := sum_{i} x^2_{i} / y # t = Variable(1,) is the epigraph variable. # Becomes a constraint # SOC(t=y + t, X=[y - t, 2*x]) #################################### soc_X_col0 = cp.reshape(y - z, (m, 1)) soc_X = cp.hstack((soc_X_col0, 2*X)) soc_t = y + z con = cp.SOC(t=soc_t, X=soc_X, axis=1) return con def RelEntrConeQuad_canon(con: RelEntrConeQuad, args) -> Tuple[Constraint, List[Constraint]]: """ Use linear and SOC constraints to approximately enforce con.x * log(con.x / con.y) <= con.z. We rely on an SOC characterization of 2-by-2 PSD matrices. Namely, a matrix [ a, b ] [ b, c ] is PSD if and only if (a, c) >= 0 and a*c >= b**2. That system of constraints can be expressed as a >= quad_over_lin(b, c). Note: constraint canonicalization in CVXPY uses a return format (lead_con, con_list) where lead_con is a Constraint that might be used in dual variable recovery and con_list consists of extra Constraint objects as needed. """ k, m = con.k, con.m x, y = con.x, con.y n = x.size # Z has been declared as so to allow for proper vectorization Z = Variable(shape=(k+1, n)) w, t = gauss_legendre(m) T = Variable(shape=(m, n)) lead_con = Zero(w @ T + con.z/2**k) constrs = [Zero(Z[0] - y)] for i in range(k): # The following matrix needs to be PSD. # [Z[i] , Z[i+1]] # [Z[i+1], x ] # The below recipe for imposing a 2x2 matrix as PSD follows from Pg-35, Ex 2.6 # of Boyd's convex optimization. Where the constraint simply becomes a # rotated quadratic cone, see `dcp2cone/quad_over_lin_canon.py` for the very similar # scalar case epi = Z[i, :] stackedZ = Z[i+1, :] cons = rotated_quad_cone(stackedZ, epi, x) constrs.append(cons) constrs.extend([epi >= 0, x >= 0]) for i in range(m): off_diag = -(t[i]**0.5) * T[i, :] # The following matrix needs to be PSD. # [ Z[k] - x - T[i] , off_diag ] # [ off_diag , x - t[i]*T[i] ] epi = (Z[k, :] - x - T[i, :]) cons = rotated_quad_cone(off_diag, epi, x-t[i]*T[i, :]) constrs.append(cons) constrs.extend([epi >= 0, x-t[i]*T[i, :] >= 0]) return lead_con, constrs def OpRelEntrConeQuad_canon(con: OpRelEntrConeQuad, args) -> Tuple[Constraint, List[Constraint]]: k, m = con.k, con.m X, Y = con.X, con.Y assert X.is_real() assert Y.is_real() assert con.Z.is_real() Zs = {i: Variable(shape=X.shape, symmetric=True) for i in range(k+1)} Ts = {i: Variable(shape=X.shape, symmetric=True) for i in range(m+1)} constrs = [Zero(Zs[0] - Y)] if not X.is_symmetric(): ut = upper_tri(X) lt = upper_tri(X.T) constrs.append(ut == lt) if not Y.is_symmetric(): ut = upper_tri(Y) lt = upper_tri(Y.T) constrs.append(ut == lt) if not con.Z.is_symmetric(): ut = upper_tri(con.Z) lt = upper_tri(con.Z.T) constrs.append(ut == lt) w, t = gauss_legendre(m) lead_con = Zero(cp.sum([w[i] * Ts[i] for i in range(m)]) + con.Z/2**k) for i in range(k): # [Z[i] , Z[i+1]] # [Z[i+1], x ] constrs.append(cp.bmat([[Zs[i], Zs[i+1]], [Zs[i+1].T, X]]) >> 0) for i in range(m): off_diag = -(t[i]**0.5) * Ts[i] # The following matrix needs to be PSD. # [ Z[k] - x - T[i] , off_diag ] # [ off_diag , x - t[i]*T[i] ] constrs.append(cp.bmat([[Zs[k] - X - Ts[i], off_diag], [off_diag.T, X-t[i]*Ts[i]]]) >> 0) return lead_con, constrs def von_neumann_entr_QuadApprox(expr, args): m, k = expr.quad_approx[0], expr.quad_approx[1] epi, initial_cons = von_neumann_entr_canon(expr, args) cons = [] for con in initial_cons: if isinstance(con, ExpCone): # should only hit this once. qa_con = con.as_quad_approx(m, k) qa_con_canon_lead, qa_con_canon = RelEntrConeQuad_canon( qa_con, None) cons.append(qa_con_canon_lead) cons.extend(qa_con_canon) else: cons.append(con) return epi, cons def von_neumann_entr_canon_dispatch(expr, args): if expr.quad_approx: return von_neumann_entr_QuadApprox(expr, args) else: return von_neumann_entr_canon(expr, args) class QuadApprox(Canonicalization): CANON_METHODS = { RelEntrConeQuad: RelEntrConeQuad_canon, OpRelEntrConeQuad: OpRelEntrConeQuad_canon } def __init__(self, problem=None) -> None: super(QuadApprox, self).__init__( problem=problem, canon_methods=QuadApprox.CANON_METHODS)
[ "noreply@github.com" ]
Fage2016.noreply@github.com
29b762ec133fdade4911774d3363521b2f7f9ba4
3a5c7d812fac93b4a2543a36a07149f864d4ed0b
/Hmm/hmm_new/2H.py
59a37551d7613858f64e6cebb22695e8f0e26a66
[ "MIT" ]
permissive
MrAlexLemon/GeneratorOfPoems
d54a17476cd3cc581f0bcc03865d5adb7e1063df
467f798153fed967c9c5994c9a796b90d565f597
refs/heads/master
2020-04-23T08:36:43.411172
2019-02-16T19:30:45
2019-02-16T19:30:45
171,042,939
0
0
null
null
null
null
UTF-8
Python
false
false
8,861
py
from HMM import unsupervised_HMM from Utility import Utility import re import copy def unsupervised_learning(n_states, n_iters): ''' Trains an HMM using supervised learning on the file 'ron.txt' and prints the results. Arguments: n_states: Number of hidden states that the HMM should have. ''' genres, genre_map, rhyming = Utility.load_shakespeare_hidden_stripped_poems() # Train the HMM. HMM = unsupervised_HMM(genres, n_states, n_iters) # Print the transition matrix. print("Transition Matrix:") print('#' * 70) for i in range(len(HMM.A)): print(''.join("{:<12.3e}".format(HMM.A[i][j]) for j in range(len(HMM.A[i])))) print('') print('') # Print the observation matrix. print("Observation Matrix: ") print('#' * 70) for i in range(len(HMM.O)): print(''.join("{:<12.3e}".format(HMM.O[i][j]) for j in range(len(HMM.O[i])))) print('') print('') return HMM, genre_map, rhyming def syllables(word): ''' This function counts number of syllables in a word ''' count = 0 vowels = 'aeiouy' word = word.lower().strip(".:;?!") if word[0] in vowels: count +=1 for index in range(1,len(word)): if word[index] in vowels and word[index-1] not in vowels: count +=1 if word.endswith('e'): count -= 1 if word.endswith('le'): count+=1 if count == 0: count +=1 return count def sylco(word) : word = word.lower() # exception_add are words that need extra syllables # exception_del are words that need less syllables exception_add = ['serious','crucial'] exception_del = ['fortunately','unfortunately'] co_one = ['cool','coach','coat','coal','count','coin','coarse','coup','coif','cook','coign','coiffe','coof','court'] co_two = ['coapt','coed','coinci'] pre_one = ['preach'] syls = 0 #added syllable number disc = 0 #discarded syllable number #1) if letters < 3 : return 1 if len(word) <= 3 : syls = 1 return syls #2) if doesn't end with "ted" or "tes" or "ses" or "ied" or "ies", discard "es" and "ed" at the end. # if it has only 1 vowel or 1 set of consecutive vowels, discard. (like "speed", "fled" etc.) if word[-2:] == "es" or word[-2:] == "ed" : doubleAndtripple_1 = len(re.findall(r'[eaoui][eaoui]',word)) if doubleAndtripple_1 > 1 or len(re.findall(r'[eaoui][^eaoui]',word)) > 1 : if word[-3:] == "ted" or word[-3:] == "tes" or word[-3:] == "ses" or word[-3:] == "ied" or word[-3:] == "ies" : pass else : disc+=1 #3) discard trailing "e", except where ending is "le" le_except = ['whole','mobile','pole','male','female','hale','pale','tale','sale','aisle','whale','while'] if word[-1:] == "e" : if word[-2:] == "le" and word not in le_except : pass else : disc+=1 #4) check if consecutive vowels exists, triplets or pairs, count them as one. doubleAndtripple = len(re.findall(r'[eaoui][eaoui]',word)) tripple = len(re.findall(r'[eaoui][eaoui][eaoui]',word)) disc+=doubleAndtripple + tripple #5) count remaining vowels in word. numVowels = len(re.findall(r'[eaoui]',word)) #6) add one if starts with "mc" if word[:2] == "mc" : syls+=1 #7) add one if ends with "y" but is not surrouned by vowel if word[-1:] == "y" and word[-2] not in "aeoui" : syls +=1 #8) add one if "y" is surrounded by non-vowels and is not in the last word. for i,j in enumerate(word) : if j == "y" : if (i != 0) and (i != len(word)-1) : if word[i-1] not in "aeoui" and word[i+1] not in "aeoui" : syls+=1 #9) if starts with "tri-" or "bi-" and is followed by a vowel, add one. if word[:3] == "tri" and word[3] in "aeoui" : syls+=1 if word[:2] == "bi" and word[2] in "aeoui" : syls+=1 #10) if ends with "-ian", should be counted as two syllables, except for "-tian" and "-cian" if word[-3:] == "ian" : #and (word[-4:] != "cian" or word[-4:] != "tian") : if word[-4:] == "cian" or word[-4:] == "tian" : pass else : syls+=1 #11) if starts with "co-" and is followed by a vowel, check if exists in the double syllable dictionary, if not, check if in single dictionary and act accordingly. if word[:2] == "co" and word[2] in 'eaoui' : if word[:4] in co_two or word[:5] in co_two or word[:6] in co_two : syls+=1 elif word[:4] in co_one or word[:5] in co_one or word[:6] in co_one : pass else : syls+=1 #12) if starts with "pre-" and is followed by a vowel, check if exists in the double syllable dictionary, if not, check if in single dictionary and act accordingly. if word[:3] == "pre" and word[3] in 'eaoui' : if word[:6] in pre_one : pass else : syls+=1 #13) check for "-n't" and cross match with dictionary to add syllable. negative = ["doesn't", "isn't", "shouldn't", "couldn't","wouldn't"] if word[-3:] == "n't" : if word in negative : syls+=1 else : pass #14) Handling the exceptional words. if word in exception_del : disc+=1 if word in exception_add : syls+=1 # calculate the output return numVowels - disc + syls if __name__ == '__main__': print('') print('') print('#' * 70) print("{:^70}".format("Running Code For Question 2H")) print('#' * 70) print('') print('') HMM, mapping, rhyming = unsupervised_learning(8,100) inv_map = {v: k for k, v in mapping.items()} numLines = 0 count = 0 topN = 15 # Find the top 10 words associated with each state toPrint = [0. for i in range(topN)] for i, row in enumerate(HMM.O): # Need to map probability to word, not just index to word, because of sorting d = {row[i]: inv_map[i] for i in range(len(row))} probs = sorted(row) for j, p in enumerate(probs[-topN:]): toPrint[j] = d[p] print(i, toPrint) while numLines != 14: numSyllables = 0 currentLine = (HMM.generate_emission(8)) currentNumberLine = copy.deepcopy(currentLine) for i in range(len(currentLine)): currentLine[i] = inv_map[int(currentLine[i])] currentLine[0] = currentLine[0][0].upper() + currentLine[0][1:] for i in currentLine: if syllables(i) == sylco(i): numSyllables += syllables(i) if numSyllables == 10: print (" ". join(currentLine)) print() numLines += 1 for i in range(1): print() lst =[] lst2 = [] count = 0 while (count < 7): flag = 0 numSyllables = 0 numSyllables2 = 0 currentLine = (HMM.generate_emission(8)) currentLine2 = (HMM.generate_emission(8)) lastNum1 = currentLine[-1] lastNum2 = currentLine2[-1] if (lastNum1 == lastNum2): continue for i in rhyming: if lastNum1 in i and lastNum2 in i: flag = 1 break if flag == 0: continue for i in range(len(currentLine)): currentLine[i] = inv_map[int(currentLine[i])] currentLine2[i] = inv_map[int(currentLine2[i])] currentLine[0] = currentLine[0][0].upper() + currentLine[0][1:] currentLine2[0] = currentLine2[0][0].upper() + currentLine2[0][1:] for i in range(len(currentLine)): if syllables(currentLine[i]) == sylco(currentLine[i]) and syllables(currentLine2[i]) == sylco(currentLine2[i]): numSyllables += syllables(currentLine[i]) numSyllables2 += syllables(currentLine2[i]) if numSyllables == 10 and numSyllables2 == 10: lst.append(" ". join(currentLine)) lst2.append(" ". join(currentLine2)) count += 1 assert(len(lst) == 7) print(lst[0]) print(lst[1]) print(lst2[0]) print(lst2[1]) print(lst[2]) print(lst[3]) print(lst2[2]) print(lst2[3]) print(lst[4]) print(lst[5]) print(lst2[4]) print(lst2[5]) print(lst[6]) print(lst2[6])
[ "lileynuk@gmail.com" ]
lileynuk@gmail.com
e578ca55d3417235a395630d3703b4a15be034e3
0d16ed8dffd7b951abd66bf895c254749ed8195a
/Lab4_Data_Structure__And_Iternation/List_questions/Three_largest_Four_smallest.py
d88b064b48df1c3232635c99c3140107e8c2ceb9
[]
no_license
sanjiv576/LabExercises
1cfea292e5b94537722b2caca42f350ab8fc7ab8
ef5adb4fbcff28162fe9e3e80782172b93127b33
refs/heads/master
2023-07-22T08:13:04.771784
2021-08-17T12:23:21
2021-08-17T12:23:21
372,397,796
1
0
null
null
null
null
UTF-8
Python
false
false
275
py
# Write a Python program to get the largest number from a list. # Write a Python program to get the smallest number from a list. ThreeFour = [23,11,5,12,4] print(max(ThreeFour)) # max() gives the largest number of the list print(min(ThreeFour)) # min() gives the smallest
[ "83968516+sanjiv576@users.noreply.github.com" ]
83968516+sanjiv576@users.noreply.github.com
36e937ed9a02e89828503fe4075624dadcde6ed4
bf3bc3abdb7b2660c02bc1375ba146461b188364
/modules/loto/loto.py
7328f3cabee6872a53226de8c3ab6bb8d672bf29
[]
no_license
JeremyMet/matrix_bot
39a3d942ad091f49445b5e5bcd8600175c919b8f
be76fb8276d031dc796ce3c329c871ec8854c30b
refs/heads/master
2023-05-13T00:36:39.384341
2021-05-01T19:44:03
2021-05-01T19:44:03
143,750,633
0
0
null
2023-05-01T22:16:13
2018-08-06T15:49:40
Python
UTF-8
Python
false
false
7,150
py
import json; import random; import datetime; from collections import namedtuple; import os.path import pickle Draw_Time = namedtuple("Draw_Time", "hour minute"); class loto(object): pt_table = {} ; pt_table[0] = 0 ; pt_table[1] = 1 ; pt_table[2] = 5 ; pt_table[3] = 75 ; pt_table[4] = 3400 ; pt_table[5] = 800000 ; pt_table[6] = 10000000 ; def __init__(self, hour=0, minute=0, scoreboard_file="./modules/loto/scoreboard_file.dic", \ dailybet_file="./modules/loto/dailybet_file.dic", log_file = "./modules/loto/log.dic", nb_numbers=49, combination_length=6): self.scoreboard_file = scoreboard_file; self.dailybet_file = dailybet_file; self.log_file = log_file; self.nb_numbers = nb_numbers; self.combination_length = combination_length; self.scoreboard = {} ; self.dailybet = {} ; # On initialise au jour précédent ; typiquement si on lance le script le 1er juin et que l'on souhaite un tirage à 22h # on initialise "le tirage précédent" (fictif, il n'a pas eu lieu) le 31 mai à 22h ; le module loto_bot.py (le "wrapper de cette classe") # vérifie toutes les secondes s'il y a eu 24h écoulés entre la date datetime.now() et la date du tirage précédent. Ainsi, même si l'on lance le script # à 21h45 un premier juin, en utilisant le tirage "fictif" (celui de 31 mai à 22h), nous aurons bien à tirage à 22h, le 1er juin. self.draw_time = Draw_Time(hour, minute); if os.path.isfile(self.log_file): with open(self.log_file, "rb") as pickle_file: self.log = pickle.load(pickle_file); else: tmp_datetime = datetime.datetime.now(); self.log = {} ; self.log["last_draw"] = datetime.datetime(year=tmp_datetime.year, month = tmp_datetime.month, \ day = tmp_datetime.day, hour = self.draw_time.hour, minute = self.draw_time.minute)-datetime.timedelta(days=1) ; self.load_previous_state(); random.seed(datetime.datetime.now()); # Seed initialisation def set_scoreboard_file(self, scoreboard_file): self.scoreboard_file = scoreboard_file; def set_log_file(self, log_file): self.log_file = log_file; def set_dailybet_file(self, dailybet_file): self.dailybet_file = dailybet_file; # def set_draw_time(self, hour, minute): # self.draw_time = Draw_Time(hour, minute); def get_draw_time(self): return self.draw_time; def get_log(self): return self.log; def load_previous_state(self): if os.path.isfile(self.scoreboard_file): with open(self.scoreboard_file, "rb") as pickle_file: self.scoreboard = pickle.load(pickle_file); if os.path.isfile(self.dailybet_file): with open(self.dailybet_file, "rb") as pickle_file: self.dailybet = pickle.load(pickle_file); if os.path.isfile(self.log_file): with open(self.log_file, "rb") as pickle_file: self.log = pickle.load(pickle_file); def save_current_state(self): with open(self.scoreboard_file, "wb") as pickle_file: pickle.dump(self.scoreboard, pickle_file); with open(self.dailybet_file, "wb") as pickle_file: pickle.dump(self.dailybet, pickle_file); with open(self.log_file, "wb") as pickle_file: pickle.dump(self.log, pickle_file); def draw(self): self.current_result = set(); while(len(self.current_result) < self.combination_length): rd = random.randint(1, self.nb_numbers); self.current_result.add(rd); tmp_datetime = datetime.datetime.now(); self.log["last_draw"] = datetime.datetime(year=tmp_datetime.year, month = tmp_datetime.month, day = tmp_datetime.day, hour = self.draw_time.hour, minute = self.draw_time.minute) ; #self.current_result = {1,2,3,8,33,2}; # todo remove! def check_result(self): self.draw(); # tirage ret = "\U0001F3B2 Le tirage du {} est {}. \nBravo à".format(datetime.datetime.today().strftime('%d-%m-%Y'), self.current_result); is_there_a_winner = False; for key, value in self.dailybet.items(): tmp_nb_pt = len(self.current_result & value); nb_pt = loto.pt_table[tmp_nb_pt]; if nb_pt > 0: is_there_a_winner = True; ret += "\n\t- {} avec {} point(s) ({} nombre(s) correct(s))".format(key.capitalize(), nb_pt, tmp_nb_pt) if key in self.scoreboard.keys(): # on ajoute quand même les participants avec zero point. self.scoreboard[key] += nb_pt; else: self.scoreboard[key] = nb_pt; self.dailybet = {} ; # réinitialisation des paris ;) if is_there_a_winner: return ret; else: return "\U0001F3B2 Pas de vainqueurs aujourd'hui ({}) !\nLe tirage était le suivant : {}.".format(datetime.datetime.today().strftime('%d-%m-%Y'), self.current_result); def bet(self, sender, proposition): # check if proposition is well-formed proposition = proposition.replace(" ", ""); if (proposition[0] != "(" or proposition[-1] != ")"): return ""; proposition = proposition[1:-1]; proposition_array = proposition.split(","); for i in proposition_array: if not(i.isnumeric()): return "" # On ne traite pas ce cas if (len(proposition_array) != self.combination_length): return "\U0001F3B2 La combinaison doit être de longueur {}.".format(self.combination_length); proposition_array = [(int(i) if (int(i) <= self.nb_numbers) else 0) for i in proposition_array]; if (0 in proposition_array): return "\U0001F3B2 Les valeurs doivent être comprises entre 1 et {}.".format(self.nb_numbers); proposition_set = set(proposition_array); if (len(proposition_set) != self.combination_length): return "\U0001F3B2 Les propositions ne doivent pas contenir deux fois le même nombre." # proposition is well-formed, self.dailybet[sender] = proposition_set; return "\U0001F3B2 La proposition {} de {} a bien été prise en compte.".format(self.dailybet[sender], sender.capitalize()); def get_dailybet(self): ret = "\U0001F3B2 Joueurs Participants - Grille"; for key, value in self.dailybet.items(): ret = "{}\n\t- {}: {} ".format(ret, key.capitalize(), value); return ret; #todo mettre dans l'ordre croissant def get_scoreboard(self): medals_array = ["\U0001F947", "\U0001f948", "\U0001f949"] ; ret = "\U0001F3B2 Tableau des Scores :"; cpt = 0 ; for key_value in sorted(self.scoreboard.items(), key=lambda x: x[1], reverse=True): ret = "{}\n\t- {}: {}".format(ret, key_value[0].capitalize(), key_value[1]); if cpt < 3: ret+= (" ({})".format(medals_array[cpt])); cpt+=1; return ret;
[ "metairie.jeremy@gmail.com" ]
metairie.jeremy@gmail.com
dc2c1061b024a7d9902210c6ee216bf9908e7be1
1511bc3e1dac288855e0757f199e5f505afb8e6c
/Senior(2018-2019)/Python/Chapter 4/P4.3-B.py
42a71b3597b3d64dcf32077b45bf2392ed09c958
[]
no_license
jakelorah/highschoolprojects
a629fa36cc662c908371ad800b53bbdb2cc8390f
dfe8eec9894338933ce4eb46f180d7eeadd7e4d3
refs/heads/main
2023-02-26T03:01:55.570156
2021-01-31T19:05:41
2021-01-31T19:05:41
308,147,867
1
0
null
null
null
null
UTF-8
Python
false
false
267
py
#Name: Jake Lorah #Date: 10/18/2018 #Program Number: P4.3-B #Program Description: This program prints every second letter of the string. #B: string = input("Please enter a string: ") n = len(string) for n in range (1, n, 2) : print(string [n])
[ "jlorah@highpoint.edu" ]
jlorah@highpoint.edu
202bff332bc7441a918f1a1ed187ec533a4b32cf
04bae28a2eefc1db77097a94af558d3df6a1e713
/20191009/Deblur_GAN/deblurgan/losses.py
c5c6dfc84d0af0c2ed18a1f853911c052d194acb
[]
no_license
Armida220/DIPHomeWork
8fc56df852fdedf26ef852ca2cc62f7be4067005
1753c1ad9783aba8a5402c98421d1126d5081aaf
refs/heads/master
2020-11-26T06:10:24.752413
2019-10-31T08:11:08
2019-10-31T08:11:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,208
py
import keras.backend as K from keras.applications.vgg16 import VGG16 from keras.models import Model import numpy as np # Note the image_shape must be multiple of patch_shape # image_shape = (256, 256, 3) image_shape = (1024, 1024, 3) def l1_loss(y_true, y_pred): return K.mean(K.abs(y_pred - y_true)) def perceptual_loss_100(y_true, y_pred): return 100 * perceptual_loss(y_true, y_pred) def perceptual_loss(y_true, y_pred): vgg = VGG16(include_top=False, weights='imagenet', input_shape=image_shape) loss_model = Model(inputs=vgg.input, outputs=vgg.get_layer('block3_conv3').output) loss_model.trainable = False return K.mean(K.square(loss_model(y_true) - loss_model(y_pred))) def wasserstein_loss(y_true, y_pred): return K.mean(y_true*y_pred) def gradient_penalty_loss(self, y_true, y_pred, averaged_samples): gradients = K.gradients(y_pred, averaged_samples)[0] gradients_sqr = K.square(gradients) gradients_sqr_sum = K.sum(gradients_sqr, axis=np.arange(1, len(gradients_sqr.shape))) gradient_l2_norm = K.sqrt(gradients_sqr_sum) gradient_penalty = K.square(1 - gradient_l2_norm) return K.mean(gradient_penalty)
[ "754037927@qq.com" ]
754037927@qq.com
fb2ac13cd6ae9f98927d9133160b287216fab5b2
2d7c21a793c8080a090ce8c9f05df38f6477c7c7
/creator/referral_tokens/apps.py
1e50dca4c827c703ff396ac486c4cdb4d6185f08
[ "Apache-2.0" ]
permissive
kids-first/kf-api-study-creator
c40e0a8a514fd52a857e9a588635ef76d16d5bc7
ba62b369e6464259ea92dbb9ba49876513f37fba
refs/heads/master
2023-08-17T01:09:38.789364
2023-08-15T14:06:29
2023-08-15T14:06:29
149,347,812
3
0
Apache-2.0
2023-09-08T15:33:40
2018-09-18T20:25:38
Python
UTF-8
Python
false
false
104
py
from django.apps import AppConfig class ReferralTokensConfig(AppConfig): name = "referral_tokens"
[ "xzhu.fg@gmail.com" ]
xzhu.fg@gmail.com
16c9a46a2c9d733a15e6609b93e0c2dda7c13452
12a6a68913fa5772973af9b2b2c4c90bc0656a57
/assignment03/mdp-simulator/ai982-mdp/utilities.py
5ec736a82ac011e00107bc86d94110542ff535c6
[]
no_license
homasms/AI_projects
42b944166617f76a106edcafe7d940dd240be0b1
c66c2e6c7e1965e6579b9ed849b7d6415c6e5e9a
refs/heads/master
2023-06-01T05:03:27.160197
2021-06-10T14:28:36
2021-06-10T14:28:36
276,040,644
0
0
null
null
null
null
UTF-8
Python
false
false
1,036
py
import enum class Actions(enum.Enum): N = 1 W = 2 S = 3 E = 4 EXIT = 5 def initialize_world_parameters(world_type): if world_type == 'smallWorld': return (3, 3), {(0, 2): 1, (1, 2): -1} if world_type == 'largeWorld': return (10, 10), {(0, 9): 1, (1, 9): -1} else: raise Exception("Wrong Entry.") def initialize_mdp_parameters(width, height, exit_locations): v_states = [[0 for i in range(0, width)] for j in range(height)] # Current step's V*(s) grid. pre_v_states = [[0 for i in range(0, width)] for j in range(height)] # Last step's V*(s) grid. policy = [[Actions.N for i in range(0, width)] for j in range(height)] # Current step's policy gird. for exit_state, exit_reward in exit_locations.items(): exit_x, exit_y = exit_state v_states[exit_x][exit_y] = exit_reward pre_v_states[exit_x][exit_y] = exit_reward policy[exit_x][exit_y] = Actions.EXIT return v_states, pre_v_states, policy
[ "homasemsarha@yahoo.com" ]
homasemsarha@yahoo.com
78f30f4848d93d075ba4bebcbc215dde6d0351fd
f777be3ca7cfe3c4ac24a1f962ea4c4d4e0aada3
/testing.py
b672b936e7b0c0fe9bbfe3fdaf65b82198dabdb3
[]
no_license
rogelio08/text_based_story
ab7419865b34c6c1b47f87fc768a02eddcc5c2ea
e7c646335ead1cf552e382dff3025157b4540ecf
refs/heads/master
2023-07-02T03:49:46.080875
2021-08-08T05:07:09
2021-08-08T05:07:09
393,861,497
0
0
null
null
null
null
UTF-8
Python
false
false
10,411
py
import sys import time #I changed this a = 2 b = 0.2 # slower time between characters getting spaced out c = 0.08 # quicker time between characters getting printed def intro(): print("\n") time.sleep(a) string_1 = '"Very well, remember to answer truthfully... Or don\'t, either way you\'ll provide valuable data"\n' for character in string_1: sys.stdout.write(character) sys.stdout.flush() time.sleep(b) time.sleep(1) print("With that the voice leaves you and the lights turn off for a moment\nWhen they turn on again you find a table has appeared") time.sleep(a) print("On the table you see a key on end of the table and a hammer on the other\nThe voice chimes in again") s = '"Please choose the item that has most value to you..."\n' for character in s: sys.stdout.write(character) sys.stdout.flush() time.sleep(b) time.sleep(1) print() first_path = input("which item do you pick? (key = 1 / hammer = 2): ") if first_path == '1': print() path1() elif first_path == '2': print() path2() else: print("Unknown path detected") def path1(): time.sleep(a) print("\nDespite how strange and unnerving the situation is, you decided that perhaps the key might be important for something down the line.") time.sleep(a) print("You rationalize that there has to be some kind of logic as to why you're here and what's the meaning behind all this.") time.sleep(a) print("After picking up the key the lights turn off and the voice speaks up.") s = '"Interesting choice, you have no idea where you are or if that key even fits anywhere yet you still chose it?"' for character in s: sys.stdout.write(character) sys.stdout.flush() time.sleep(c) time.sleep(1) print() s2 = '"Let us find out whether your choice will be the key to freedom or the key to your death."' for character in s2: sys.stdout.write(character) sys.stdout.flush() time.sleep(b) time.sleep(1) print() print("When the lights turn on again the table is gone, but now the room includes two doors.\n") time.sleep(a) print("The first door appears to have seen better days, mots of its color has faded while several cracks could be seen in the wood.") time.sleep(a) print("The second door leaves you stunned, you recognize the door as the same one on the front of your home!") door_choice = input("\nWhich door do you use the key on? (1/2): ") if door_choice == "1": print() path1_1() elif door_choice == '2': print() path1_2() def path1_1(): print("\nWhile the familiar door is calling out to you, you realize that such an obvious choice must be a trap. So going against all your instincts for survival you hesitantely unlock the worn down door and head inside.") time.sleep(a) print("After exiting the concrete prison you find yourself somewhere damp, dark, and cold. Using your hands to feel around you deduce that you must be in some sort of cave.") time.sleep(a) print("Realizing that the door is no longer behind you and left with no other options you decide to feel your way to what is hopefully an exit.") time.sleep(a) print("After wandering around in the dark you notice small beams of light that eventually lead to an opening in the cave, and before you know you're outside in a forest.") time.sleep(a) print("Out in the distance you notice smoke from a what could be a campfire but at the same time you have no idea if you've actually escaped or not.") time.sleep(a) print("Armed with the determination to survive, you venture towards the smoke.") def path1_2(): print("\nNot wanting to spend another moment in the room you rush over to the familiar door and check to see if they key works.") time.sleep(a) print("By some miracle the key fits and you're able to open the door\nRushing through the door you find yourself in your own living room, and breathing a sigh of relief.") time.sleep(a) print("Things however, are not as they seem. You begin to notice that your home is eerily quiet, with no traces of your family anywhere.") time.sleep(a) print("As you search through your home your fears and only confirmed, none of your family members are anywhere!\nDesperate for answers you go back through the front door but are shocked by the result.") time.sleep(a) print("Instead of making it back to the isolated room your find yourself in your neighborhood, only there's no neighbors in sight. Moreover the normally busy interstate freeway you live next to is unusually quiet.") time.sleep(a) print("While trying to process what's happening you realize that if the door was in fact the one to your home how did they key you picked up unlock it if you've never seen a key like it?") time.sleep(a) print("Trying to remain optimistic, you figure there has to be someone around. And so you you go off in search of survivors that don't exist, forever wandering the hollow shell of the world you once knew.") def path2(): time.sleep(a) print("\nGiven the situation you're in, you can't rule out the possibility that this is all some kind of twisted game. Thus you reason that it's in your best interest to have some kind of weapon.") time.sleep(a) print("Besides, who knows if the key is meant to throw you off from choosing a multi-purpose tool? Not to mention you could theoretically open any lock using the hammer if you're smart about it.") time.sleep(a) print("Feeling satisfied you pick up the hammer, soon after the lights turn off and the voice could be heard again.\n") s = '"What an interesting choice, while it\'s clever to be cautious in your position choosing what could be considered a weapon does seem rather barbaric. Though that\'s nothing new to humans."' for character in s: sys.stdout.write(character) sys.stdout.flush() time.sleep(c) time.sleep(1) print() s2 = '"You made a bold choice, let\'s find out whether you have the dexterity to justify such an option."' for character in s2: sys.stdout.write(character) sys.stdout.flush() time.sleep(c) time.sleep(1) print() print("Soon the lights turn on and you notice the table and key is gone but you're not interested in that. What has your attention now is the 500 pound apex preadator that occupies the room with.") time.sleep(a) print("With a low growl, the spontaneous bear is sizng you up. It's at this moment when your adrenaline kicks in and you're given a few breif seconds to form a plan of attack.") time.sleep(a) print("You narrow down to your options to two choices: 1) Use your adrenaline to take on the bear in a battle to the death or 2) Throw the hammer towards the one lightbulb in the room and use the darkness to hide and wait it out.") bear_choice = input("\nHow do you go about dealing with the bear? (1/2): ") if bear_choice == '1': print() path2_1() else: print() path2_2() def path2_1(): print("\nDespite feeling panicked and afraid for your life you decide to muster up all the courage you have and challenge the bear for the right to live.") time.sleep(a) print("With a war cry you rush the bear ad the bear responds with a roar of its own and stands on two feet in order to strike you down.") time.sleep(a) print("Seeing this you fling yourself to the right in order to dodge the potentially fatal blow and as the bear crashes its paws down and turns to face you, you get in a lucky swing and manage to strike the bear near it's eye.") time.sleep(a) print("With a roar of pain the bear backs off. You can't believe it, you just might be able to pull this off! Is what you were thinking before you realized that you didn't completely dodge the first attack.") time.sleep(a) print("Looking down you realize you see an unsightly slash on the left side of your abdomen and while attempting to stop the bleeding the last of your adrenaline fades as the bear recovers.") time.sleep(a) print("Your last thoughts as you see the bear closing in for the finishing move were about how people who don't consider bears as apex predators have never fought one.") def path2_2(): print("\nUnderstanding the fact that under the laws of nature no human could ever beat a grown bear with just a hammer in an enclosed space you decide to use your higher level intelligence to your advantage.") time.sleep(a) print("As the bear prepares to attack your quickly throw your hammer at the dim lightbulb hanging from the ceiling, shattering it and engulfing the room in darkness.") time.sleep(a) print("At first your gamble seems to pay off as the bear's roars turn from aggressive to confused at the lack of vision.\nAs you hide in the corner of the now dark room a terrifying thought hits you.") time.sleep(a) print("Not only are you in a small room but bears don't exactly have to rely on sight alone. Sure enough, the bear begins to compose itself and soon begins sniffing the air.") time.sleep(a) print("You could only cower in horror and wait for your inevitable death as you curse your own lack of foresight") print() print() print(" #######################") print(" # #") print(" # Title Card #") print(" # #") print(" #######################") print() print() time.sleep(a) print("You find yourself in a dim, concrete room with only a single lightbulb hanging from the ceiling") time.sleep(a) print("Before you are able to asses your surroundings a monotone voice could be heard") time.sleep(a) print() start_game = input("Would you like to start the game? (Y/N): ") if start_game == 'n' or start_game == 'N': print("Understood, subject #[REDACTED] does not wish to participate in the experiment. Bringing in the next subject...") elif start_game == 'y' or start_game == 'Y': intro() else: print("Answer does not compute, try again")
[ "noreply@github.com" ]
rogelio08.noreply@github.com
6388a2abfd90b416b71fb102e7f2bdc93ad8f6ca
23da742e7b7fd998f499abda3d26d4a8689f681f
/split_list.py
3b3f52e747e063226bbd99bd7574ca6f7c7cdadf
[ "Apache-2.0" ]
permissive
JustDoItGit/daily_utils
57c25f7beb57f887d69e1244ecac518e0f357d63
503937f284bca021e10a11d846dfae2fcae808d8
refs/heads/master
2023-01-22T04:34:31.114116
2020-12-04T05:28:30
2020-12-04T05:28:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
656
py
def split_list(ls, num): """ 拆分list :param ls: 带截取的列表 [0, 1, 2, 3, 4, 5, 6] :param num: 除最后一个列表之外其他列表长度 3 :return: 所有拆分的列表 [[0, 1, 2], [3, 4, 5], [6]] """ a = len(ls) if a <= num: return [ls] quotient = a // num # 商 remainder = a % num # 余数 res_split = [] for i in range(quotient): res_split.append(ls[num * i: num * (i + 1)]) if remainder != 0: res_split.append(ls[num * quotient: num * quotient + remainder]) # 方法2 # res_split = [ls[i:i + num] for i in range(0, len(ls), num)] return res_split
[ "noreply@github.com" ]
JustDoItGit.noreply@github.com
5accaca4d79de6e89aeddb67971165259bec460b
7a866c210bba93fa33e02305e221338541d6ec9b
/Direction JOL/Timed JOL/Output/Merged/EX2_conf_plots.py
912af24af1f000dedf77b86d611584c4bba457a1
[]
no_license
npm27/Spring-2019-Projects
afbb6d3816e097b58f7d5032bc8d7563536a232a
52e0c1c4dc3de2e0399e5391dd2c8aff56754c1c
refs/heads/master
2021-12-20T01:01:11.218779
2021-12-08T14:49:18
2021-12-08T14:49:18
168,214,407
0
0
null
null
null
null
UTF-8
Python
false
false
2,075
py
##set up import pandas as pd import numpy as np import matplotlib.pyplot as plt dat = pd.read_csv("Delayed conf.csv") #JUST NEED TO ADD DATA dat['diff'] = dat['Upper'].sub(dat['Lower']) dat['diff2'] = dat['diff'].div(2) ##make subsets datF = dat[dat['Direction'] == 'F'] datB = dat[dat['Direction'] == 'B'] datS = dat[dat['Direction'] == 'S'] datU = dat[dat['Direction'] == 'U'] ##set up the initial plot fig = plt.figure() fig.set_size_inches(11,8) ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) ax4 = fig.add_subplot(2, 2, 4) dot_line = np.arange(100) major_ticks = np.arange(0, 101, 20) fig.text(0.5, 0.04, 'JOL Rating', ha='center', fontsize=18) fig.text(0.04, 0.5, '% Correct Recall', va='center', rotation='vertical', fontsize=18) ##forward x1 = datF.JOL_Bin.values y1 = datF.Average.values ax1.plot(dot_line, 'k--') ax1.plot(x1, y1, marker = '.', color = 'k') ax1.set_xticks(major_ticks) ax1.set_yticks(major_ticks) ax1.set_title("Forward", fontsize = 16) ax1.errorbar(x1, y1, yerr=(datF['diff2']), fmt='none', c= 'k', capsize=5) ##backward x2 = datB.JOL_Bin.values y2 = datB.Average.values ax2.plot(dot_line, 'k--') ax2.plot(x2, y2, marker = '.', color = 'k') ax2.set_xticks(major_ticks) ax2.set_yticks(major_ticks) ax2.set_title("Backward", fontsize = 16) ax2.errorbar(x2, y2, yerr=(datB['diff2']), fmt='none', c= 'k', capsize=5) ##symmetrical x3 = datS.JOL_Bin.values y3 = datS.Average.values ax3.plot(dot_line, 'k--') ax3.plot(x3, y3, marker = '.', color = 'k') ax3.set_xticks(major_ticks) ax3.set_yticks(major_ticks) ax3.set_title("Symmetrical", fontsize = 16) ax3.errorbar(x3, y3, yerr=(datS['diff2']), fmt='none', c= 'k', capsize=5) ##unrelated x4 = datU.JOL_Bin.values y4 = datU.Average.values ax4.plot(dot_line, 'k--') ax4.plot(x4, y4, marker = '.', color = 'k') ax4.set_xticks(major_ticks) ax4.set_yticks(major_ticks) ax4.set_title("Unrelated", fontsize = 16) ax4.errorbar(x4, y4, yerr=(datU['diff2']), fmt='none', c= 'k', capsize=5) ##save figure #fig.savefig('Plot2_smoothed.png')
[ "35810320+npm27@users.noreply.github.com" ]
35810320+npm27@users.noreply.github.com
68b259649181c54eea9faebc337711ab016af534
5c4289608693609de3d755674cba53b77cbc4c69
/Python_Study/2课堂练习/Python基础班/06_名片管理系统/cards_main.py
32a8e9caa251e2f2c3000e3de1f3a1e6e5ad5bcf
[ "Apache-2.0" ]
permissive
vipliujunjie/HouseCore
95892e632f840f22715d08467d6610195d562261
e9fa5ebc048cbede7823ac59a011a554bddf8674
refs/heads/master
2021-02-05T13:09:43.962224
2020-02-28T14:46:26
2020-02-28T14:46:26
243,783,276
0
0
null
null
null
null
UTF-8
Python
false
false
1,298
py
#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 import cards_tools # 无限循环 由用户决定什么时候退出循环 while True: # TODO(刘俊杰) 显示功能菜单 cards_tools.show_menu() action_str = input("请输入希望执行的操作:") print("您选择的操作是【%s】" % action_str) # [1,2,3] 针对名片的操作 if action_str in ["1", "2", "3"]: # 判断在指定列表内 # 新增名片 if action_str == "1": cards_tools.new_card() # pass # 显示全部 if action_str == "2": cards_tools.show_all() # pass # 查询名片 if action_str == "3": cards_tools.search_card() # pass # pass # 0 退出系统 elif action_str == "0": # 如果在开发程序时,不希望立刻编写分支内部的代码 # 可以使用 pass 关键字,表示一个占位符,能够保证程序的代码结构正确! # 程序运行时,pass 关键字不会执行任何的操作 print("\n欢迎再次使用【名片管理系统】") break # pass # 输入其他内容提示用户错误 else: print("您输入的不正确,请从新选择")
[ "1520997065@qq.com" ]
1520997065@qq.com
6557c40afa926f83bc0721834c9ee2d158e8fd46
0d0988d2afeba6539ab3802f0cac9a25ff862076
/metodosConjuntosSTR.py
f42cea1cbd2300014f65169bbb193579f1ddd1e4
[]
no_license
alexisflores99/Repo-for-Python
a5e967c17c0938dc5a8e91db2a6ea7302e2cd109
d4339edcee3d2b1f57129df8059eb32c41ce4864
refs/heads/master
2023-04-18T18:43:06.864806
2021-05-02T04:05:41
2021-05-02T04:05:41
363,562,129
0
0
null
null
null
null
UTF-8
Python
false
false
480
py
# set_conjunto1 = set({1,2,3,4}) # set_conjunto1.add(5) # print(set_conjunto1) #************************************ # set_conjunto = set({1.0, "Auto", True}) # otro_conjunto = set_conjunto.copy() # set_conjunto == otro_conjunto # print(otro_conjunto) #************************************ # paquete = set({"Hola",2 ,3 ,4 }) # paquete.discard("Hola") # print(paquete) #************************************ paquete = set({"Hola" ,2, 3, 4}) paquete.remove("Hola") print(paquete)
[ "hector.flores6@unmsm.edu.pe" ]
hector.flores6@unmsm.edu.pe
6affbb678c0509cdb3dd5674c2edb67dd98dcb75
e53d920751b86ae09a16913c7531a806c334265f
/mmdet3d/ops/furthest_point_sample/points_sampler.py
9a3bd2ae42d625cc19355492246d4967a8e96b92
[ "Apache-2.0" ]
permissive
destinyls/mmdetection3d
e959e4a1a9316b385cec73a654bc8a016cb43a02
f2247c2471dbb429512353b3f0802f839655dd16
refs/heads/master
2023-03-20T21:12:32.105859
2023-01-24T01:45:12
2023-01-24T01:45:12
279,744,471
1
1
Apache-2.0
2020-07-15T02:42:54
2020-07-15T02:42:53
null
UTF-8
Python
false
false
5,373
py
import torch from mmcv.runner import force_fp32 from torch import nn as nn from typing import List from .furthest_point_sample import (furthest_point_sample, furthest_point_sample_with_dist) from .utils import calc_square_dist def get_sampler_type(sampler_type): """Get the type and mode of points sampler. Args: sampler_type (str): The type of points sampler. The valid value are "D-FPS", "F-FPS", or "FS". Returns: class: Points sampler type. """ if sampler_type == 'D-FPS': sampler = DFPS_Sampler elif sampler_type == 'F-FPS': sampler = FFPS_Sampler elif sampler_type == 'FS': sampler = FS_Sampler else: raise ValueError('Only "sampler_type" of "D-FPS", "F-FPS", or "FS"' f' are supported, got {sampler_type}') return sampler class Points_Sampler(nn.Module): """Points sampling. Args: num_point (list[int]): Number of sample points. fps_mod_list (list[str]: Type of FPS method, valid mod ['F-FPS', 'D-FPS', 'FS'], Default: ['D-FPS']. F-FPS: using feature distances for FPS. D-FPS: using Euclidean distances of points for FPS. FS: using F-FPS and D-FPS simultaneously. fps_sample_range_list (list[int]): Range of points to apply FPS. Default: [-1]. """ def __init__(self, num_point: List[int], fps_mod_list: List[str] = ['D-FPS'], fps_sample_range_list: List[int] = [-1]): super(Points_Sampler, self).__init__() # FPS would be applied to different fps_mod in the list, # so the length of the num_point should be equal to # fps_mod_list and fps_sample_range_list. assert len(num_point) == len(fps_mod_list) == len( fps_sample_range_list) self.num_point = num_point self.fps_sample_range_list = fps_sample_range_list self.samplers = nn.ModuleList() for fps_mod in fps_mod_list: self.samplers.append(get_sampler_type(fps_mod)()) self.fp16_enabled = False @force_fp32() def forward(self, points_xyz, features): """forward. Args: points_xyz (Tensor): (B, N, 3) xyz coordinates of the features. features (Tensor): (B, C, N) Descriptors of the features. Return: Tensor: (B, npoint, sample_num) Indices of sampled points. """ indices = [] last_fps_end_index = 0 for fps_sample_range, sampler, npoint in zip( self.fps_sample_range_list, self.samplers, self.num_point): assert fps_sample_range < points_xyz.shape[1] if fps_sample_range == -1: sample_points_xyz = points_xyz[:, last_fps_end_index:] sample_features = features[:, :, last_fps_end_index:] if \ features is not None else None else: sample_points_xyz = \ points_xyz[:, last_fps_end_index:fps_sample_range] sample_features = \ features[:, :, last_fps_end_index:fps_sample_range] if \ features is not None else None fps_idx = sampler(sample_points_xyz.contiguous(), sample_features, npoint) indices.append(fps_idx + last_fps_end_index) last_fps_end_index += fps_sample_range indices = torch.cat(indices, dim=1) return indices class DFPS_Sampler(nn.Module): """DFPS_Sampling. Using Euclidean distances of points for FPS. """ def __init__(self): super(DFPS_Sampler, self).__init__() def forward(self, points, features, npoint): """Sampling points with D-FPS.""" fps_idx = furthest_point_sample(points.contiguous(), npoint) return fps_idx class FFPS_Sampler(nn.Module): """FFPS_Sampler. Using feature distances for FPS. """ def __init__(self): super(FFPS_Sampler, self).__init__() def forward(self, points, features, npoint): """Sampling points with F-FPS.""" assert features is not None, \ 'feature input to FFPS_Sampler should not be None' features_for_fps = torch.cat([points, features.transpose(1, 2)], dim=2) features_dist = calc_square_dist( features_for_fps, features_for_fps, norm=False) fps_idx = furthest_point_sample_with_dist(features_dist, npoint) return fps_idx class FS_Sampler(nn.Module): """FS_Sampling. Using F-FPS and D-FPS simultaneously. """ def __init__(self): super(FS_Sampler, self).__init__() def forward(self, points, features, npoint): """Sampling points with FS_Sampling.""" assert features is not None, \ 'feature input to FS_Sampler should not be None' features_for_fps = torch.cat([points, features.transpose(1, 2)], dim=2) features_dist = calc_square_dist( features_for_fps, features_for_fps, norm=False) fps_idx_ffps = furthest_point_sample_with_dist(features_dist, npoint) fps_idx_dfps = furthest_point_sample(points, npoint) fps_idx = torch.cat([fps_idx_ffps, fps_idx_dfps], dim=1) return fps_idx
[ "noreply@github.com" ]
destinyls.noreply@github.com
230c05c7d30324adcb69a3442767523215dea7ec
a56252fda5c9e42eff04792c6e16e413ad51ba1a
/resources/usr/local/lib/python2.7/dist-packages/sklearn/metrics/cluster/supervised.py
31d1a45b74047c04f16b5e95a5fec55fca7b256f
[ "Apache-2.0" ]
permissive
edawson/parliament2
4231e692565dbecf99d09148e75c00750e6797c4
2632aa3484ef64c9539c4885026b705b737f6d1e
refs/heads/master
2021-06-21T23:13:29.482239
2020-12-07T21:10:08
2020-12-07T21:10:08
150,246,745
0
0
Apache-2.0
2019-09-11T03:22:55
2018-09-25T10:21:03
Python
UTF-8
Python
false
false
26,696
py
"""Utilities to evaluate the clustering performance of models Functions named as *_score return a scalar value to maximize: the higher the better. """ # Authors: Olivier Grisel <olivier.grisel@ensta.org> # Wei LI <kuantkid@gmail.com> # Diego Molla <dmolla-aliod@gmail.com> # License: BSD 3 clause from math import log from scipy.misc import comb from scipy.sparse import coo_matrix import numpy as np from ...utils.fixes import unique from .expected_mutual_info_fast import expected_mutual_information def comb2(n): # the exact version is faster for k == 2: use it by default globally in # this module instead of the float approximate variant return comb(n, 2, exact=1) def check_clusterings(labels_true, labels_pred): """Check that the two clusterings matching 1D integer arrays""" labels_true = np.asarray(labels_true) labels_pred = np.asarray(labels_pred) # input checks if labels_true.ndim != 1: raise ValueError( "labels_true must be 1D: shape is %r" % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError( "labels_pred must be 1D: shape is %r" % (labels_pred.shape,)) if labels_true.shape != labels_pred.shape: raise ValueError( "labels_true and labels_pred must have same size, got %d and %d" % (labels_true.shape[0], labels_pred.shape[0])) return labels_true, labels_pred def contingency_matrix(labels_true, labels_pred, eps=None): """Build a contengency matrix describing the relationship between labels. Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference labels_pred : array, shape = [n_samples] Cluster labels to evaluate eps: None or float If a float, that value is added to all values in the contingency matrix. This helps to stop NaN propagation. If ``None``, nothing is adjusted. Returns ------- contingency: array, shape=[n_classes_true, n_classes_pred] Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in true class :math:`i` and in predicted class :math:`j`. If ``eps is None``, the dtype of this array will be integer. If ``eps`` is given, the dtype will be float. """ classes, class_idx = unique(labels_true, return_inverse=True) clusters, cluster_idx = unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] # Using coo_matrix to accelerate simple histogram calculation, # i.e. bins are consecutive integers # Currently, coo_matrix is faster than histogram2d for simple cases contingency = coo_matrix((np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=np.int).toarray() if eps is not None: # don't use += as contingency is integer contingency = contingency + eps return contingency # clustering measures def adjusted_rand_score(labels_true, labels_pred): """Rand index adjusted for chance The Rand Index computes a similarity measure between two clusterings by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in the predicted and true clusterings. The raw RI score is then "adjusted for chance" into the ARI score using the following scheme:: ARI = (RI - Expected_RI) / (max(RI) - Expected_RI) The adjusted Rand index is thus ensured to have a value close to 0.0 for random labeling independently of the number of clusters and samples and exactly 1.0 when the clusterings are identical (up to a permutation). ARI is a symmetric measure:: adjusted_rand_score(a, b) == adjusted_rand_score(b, a) Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference labels_pred : array, shape = [n_samples] Cluster labels to evaluate Returns ------- ari: float Similarity score between -1.0 and 1.0. Random labelings have an ARI close to 0.0. 1.0 stands for perfect match. Examples -------- Perfectly maching labelings have a score of 1 even >>> from sklearn.metrics.cluster import adjusted_rand_score >>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 1]) 1.0 >>> adjusted_rand_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 Labelings that assign all classes members to the same clusters are complete be not always pure, hence penalized:: >>> adjusted_rand_score([0, 0, 1, 2], [0, 0, 1, 1]) # doctest: +ELLIPSIS 0.57... ARI is symmetric, so labelings that have pure clusters with members coming from the same classes but unnecessary splits are penalized:: >>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 2]) # doctest: +ELLIPSIS 0.57... If classes members are completely split across different clusters, the assignment is totally incomplete, hence the ARI is very low:: >>> adjusted_rand_score([0, 0, 0, 0], [0, 1, 2, 3]) 0.0 References ---------- .. [Hubert1985] `L. Hubert and P. Arabie, Comparing Partitions, Journal of Classification 1985` http://www.springerlink.com/content/x64124718341j1j0/ .. [wk] http://en.wikipedia.org/wiki/Rand_index#Adjusted_Rand_index See also -------- adjusted_mutual_info_score: Adjusted Mutual Information """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) n_samples = labels_true.shape[0] classes = np.unique(labels_true) clusters = np.unique(labels_pred) # Special limit cases: no clustering since the data is not split; # or trivial clustering where each document is assigned a unique cluster. # These are perfect matches hence return 1.0. if (classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0 or classes.shape[0] == clusters.shape[0] == len(labels_true)): return 1.0 contingency = contingency_matrix(labels_true, labels_pred) # Compute the ARI using the contingency data sum_comb_c = sum(comb2(n_c) for n_c in contingency.sum(axis=1)) sum_comb_k = sum(comb2(n_k) for n_k in contingency.sum(axis=0)) sum_comb = sum(comb2(n_ij) for n_ij in contingency.flatten()) prod_comb = (sum_comb_c * sum_comb_k) / float(comb(n_samples, 2)) mean_comb = (sum_comb_k + sum_comb_c) / 2. return ((sum_comb - prod_comb) / (mean_comb - prod_comb)) def homogeneity_completeness_v_measure(labels_true, labels_pred): """Compute the homogeneity and completeness and V-Measure scores at once Those metrics are based on normalized conditional entropy measures of the clustering labeling to evaluate given the knowledge of a Ground Truth class labels of the same samples. A clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class. A clustering result satisfies completeness if all the data points that are members of a given class are elements of the same cluster. Both scores have positive values between 0.0 and 1.0, larger values being desirable. Those 3 metrics are independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score values in any way. V-Measure is furthermore symmetric: swapping ``labels_true`` and ``label_pred`` will give the same score. This does not hold for homogeneity and completeness. Parameters ---------- labels_true : int array, shape = [n_samples] ground truth class labels to be used as a reference labels_pred : array, shape = [n_samples] cluster labels to evaluate Returns ------- homogeneity: float score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling completeness: float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling v_measure: float harmonic mean of the first two See also -------- homogeneity_score completeness_score v_measure_score """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) if len(labels_true) == 0: return 1.0, 1.0, 1.0 entropy_C = entropy(labels_true) entropy_K = entropy(labels_pred) MI = mutual_info_score(labels_true, labels_pred) homogeneity = MI / (entropy_C) if entropy_C else 1.0 completeness = MI / (entropy_K) if entropy_K else 1.0 if homogeneity + completeness == 0.0: v_measure_score = 0.0 else: v_measure_score = (2.0 * homogeneity * completeness / (homogeneity + completeness)) return homogeneity, completeness, v_measure_score def homogeneity_score(labels_true, labels_pred): """Homogeneity metric of a cluster labeling given a ground truth A clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is not symmetric: switching ``label_true`` with ``label_pred`` will return the :func:`completeness_score` which will be different in general. Parameters ---------- labels_true : int array, shape = [n_samples] ground truth class labels to be used as a reference labels_pred : array, shape = [n_samples] cluster labels to evaluate Returns ------- homogeneity: float score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling References ---------- .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A conditional entropy-based external cluster evaluation measure <http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf>`_ See also -------- completeness_score v_measure_score Examples -------- Perfect labelings are homogeneous:: >>> from sklearn.metrics.cluster import homogeneity_score >>> homogeneity_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 Non-perfect labelings that further split classes into more clusters can be perfectly homogeneous:: >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 1, 2])) ... # doctest: +ELLIPSIS 1.0... >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3])) ... # doctest: +ELLIPSIS 1.0... Clusters that include samples from different classes do not make for an homogeneous labeling:: >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1])) ... # doctest: +ELLIPSIS 0.0... >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 0, 0])) ... # doctest: +ELLIPSIS 0.0... """ return homogeneity_completeness_v_measure(labels_true, labels_pred)[0] def completeness_score(labels_true, labels_pred): """Completeness metric of a cluster labeling given a ground truth A clustering result satisfies completeness if all the data points that are members of a given class are elements of the same cluster. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is not symmetric: switching ``label_true`` with ``label_pred`` will return the :func:`homogeneity_score` which will be different in general. Parameters ---------- labels_true : int array, shape = [n_samples] ground truth class labels to be used as a reference labels_pred : array, shape = [n_samples] cluster labels to evaluate Returns ------- completeness: float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling References ---------- .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A conditional entropy-based external cluster evaluation measure <http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf>`_ See also -------- homogeneity_score v_measure_score Examples -------- Perfect labelings are complete:: >>> from sklearn.metrics.cluster import completeness_score >>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 Non-perfect labelings that assign all classes members to the same clusters are still complete:: >>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0])) 1.0 >>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1])) 1.0 If classes members are split across different clusters, the assignment cannot be complete:: >>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1])) 0.0 >>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3])) 0.0 """ return homogeneity_completeness_v_measure(labels_true, labels_pred)[1] def v_measure_score(labels_true, labels_pred): """V-measure cluster labeling given a ground truth. This score is identical to :func:`normalized_mutual_info_score`. The V-measure is the harmonic mean between homogeneity and completeness:: v = 2 * (homogeneity * completeness) / (homogeneity + completeness) This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Parameters ---------- labels_true : int array, shape = [n_samples] ground truth class labels to be used as a reference labels_pred : array, shape = [n_samples] cluster labels to evaluate Returns ------- v_measure: float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling References ---------- .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A conditional entropy-based external cluster evaluation measure <http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf>`_ See also -------- homogeneity_score completeness_score Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0:: >>> from sklearn.metrics.cluster import v_measure_score >>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 1]) 1.0 >>> v_measure_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 Labelings that assign all classes members to the same clusters are complete be not homogeneous, hence penalized:: >>> print("%.6f" % v_measure_score([0, 0, 1, 2], [0, 0, 1, 1])) ... # doctest: +ELLIPSIS 0.8... >>> print("%.6f" % v_measure_score([0, 1, 2, 3], [0, 0, 1, 1])) ... # doctest: +ELLIPSIS 0.66... Labelings that have pure clusters with members coming from the same classes are homogeneous but un-necessary splits harms completeness and thus penalize V-measure as well:: >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 1, 2])) ... # doctest: +ELLIPSIS 0.8... >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 1, 2, 3])) ... # doctest: +ELLIPSIS 0.66... If classes members are completely split across different clusters, the assignment is totally incomplete, hence the V-Measure is null:: >>> print("%.6f" % v_measure_score([0, 0, 0, 0], [0, 1, 2, 3])) ... # doctest: +ELLIPSIS 0.0... Clusters that include samples from totally different classes totally destroy the homogeneity of the labeling, hence:: >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 0, 0])) ... # doctest: +ELLIPSIS 0.0... """ return homogeneity_completeness_v_measure(labels_true, labels_pred)[2] def mutual_info_score(labels_true, labels_pred, contingency=None): """Mutual Information between two clusterings The Mutual Information is a measure of the similarity between two labels of the same data. Where :math:`P(i)` is the probability of a random sample occurring in cluster :math:`U_i` and :math:`P'(j)` is the probability of a random sample occurring in cluster :math:`V_j`, the Mutual Information between clusterings :math:`U` and :math:`V` is given as: .. math:: MI(U,V)=\sum_{i=1}^R \sum_{j=1}^C P(i,j)\log\\frac{P(i,j)}{P(i)P'(j)} This is equal to the Kullback-Leibler divergence of the joint distribution with the product distribution of the marginals. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets. labels_pred : array, shape = [n_samples] A clustering of the data into disjoint subsets. contingency: None or array, shape = [n_classes_true, n_classes_pred] A contingency matrix given by the :func:`contingency_matrix` function. If value is ``None``, it will be computed, otherwise the given value is used, with ``labels_true`` and ``labels_pred`` ignored. Returns ------- mi: float Mutual information, a non-negative value See also -------- adjusted_mutual_info_score: Adjusted against chance Mutual Information normalized_mutual_info_score: Normalized Mutual Information """ if contingency is None: labels_true, labels_pred = check_clusterings(labels_true, labels_pred) contingency = contingency_matrix(labels_true, labels_pred) contingency = np.array(contingency, dtype='float') contingency_sum = np.sum(contingency) pi = np.sum(contingency, axis=1) pj = np.sum(contingency, axis=0) outer = np.outer(pi, pj) nnz = contingency != 0.0 # normalized contingency contingency_nm = contingency[nnz] log_contingency_nm = np.log(contingency_nm) contingency_nm /= contingency_sum # log(a / b) should be calculated as log(a) - log(b) for # possible loss of precision log_outer = -np.log(outer[nnz]) + log(pi.sum()) + log(pj.sum()) mi = (contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer) return mi.sum() def adjusted_mutual_info_score(labels_true, labels_pred): """Adjusted Mutual Information between two clusterings Adjusted Mutual Information (AMI) is an adjustment of the Mutual Information (MI) score to account for chance. It accounts for the fact that the MI is generally higher for two clusterings with a larger number of clusters, regardless of whether there is actually more information shared. For two clusterings :math:`U` and :math:`V`, the AMI is given as:: AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [max(H(U), H(V)) - E(MI(U, V))] This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Be mindful that this function is an order of magnitude slower than other metrics, such as the Adjusted Rand Index. Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets. labels_pred : array, shape = [n_samples] A clustering of the data into disjoint subsets. Returns ------- ami: float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling See also -------- adjusted_rand_score: Adjusted Rand Index mutual_information_score: Mutual Information (not adjusted for chance) Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0:: >>> from sklearn.metrics.cluster import adjusted_mutual_info_score >>> adjusted_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) 1.0 >>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 If classes members are completely split across different clusters, the assignment is totally in-complete, hence the AMI is null:: >>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) 0.0 References ---------- .. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for Clusterings Comparison: Variants, Properties, Normalization and Correction for Chance, JMLR <http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf>`_ .. [2] `Wikipedia entry for the Adjusted Mutual Information <http://en.wikipedia.org/wiki/Adjusted_Mutual_Information>`_ """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) n_samples = labels_true.shape[0] classes = np.unique(labels_true) clusters = np.unique(labels_pred) # Special limit cases: no clustering since the data is not split. # This is a perfect match hence return 1.0. if (classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0): return 1.0 contingency = contingency_matrix(labels_true, labels_pred) contingency = np.array(contingency, dtype='float') # Calculate the MI for the two clusterings mi = mutual_info_score(labels_true, labels_pred, contingency=contingency) # Calculate the expected value for the mutual information emi = expected_mutual_information(contingency, n_samples) # Calculate entropy for each labeling h_true, h_pred = entropy(labels_true), entropy(labels_pred) ami = (mi - emi) / (max(h_true, h_pred) - emi) return ami def normalized_mutual_info_score(labels_true, labels_pred): """Normalized Mutual Information between two clusterings Normalized Mutual Information (NMI) is an normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual information) and 1 (perfect correlation). In this function, mutual information is normalized by ``sqrt(H(labels_true) * H(labels_pred))`` This measure is not adjusted for chance. Therefore :func:`adjusted_mustual_info_score` might be preferred. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets. labels_pred : array, shape = [n_samples] A clustering of the data into disjoint subsets. Returns ------- nmi: float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling See also -------- adjusted_rand_score: Adjusted Rand Index adjusted_mutual_info_score: Adjusted Mutual Information (adjusted against chance) Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0:: >>> from sklearn.metrics.cluster import normalized_mutual_info_score >>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) 1.0 >>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 If classes members are completely split across different clusters, the assignment is totally in-complete, hence the NMI is null:: >>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) 0.0 """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) classes = np.unique(labels_true) clusters = np.unique(labels_pred) # Special limit cases: no clustering since the data is not split. # This is a perfect match hence return 1.0. if (classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0): return 1.0 contingency = contingency_matrix(labels_true, labels_pred) contingency = np.array(contingency, dtype='float') # Calculate the MI for the two clusterings mi = mutual_info_score(labels_true, labels_pred, contingency=contingency) # Calculate the expected value for the mutual information # Calculate entropy for each labeling h_true, h_pred = entropy(labels_true), entropy(labels_pred) nmi = mi / max(np.sqrt(h_true * h_pred), 1e-10) return nmi def entropy(labels): """Calculates the entropy for a labeling.""" if len(labels) == 0: return 1.0 label_idx = unique(labels, return_inverse=True)[1] pi = np.bincount(label_idx).astype(np.float) pi = pi[pi > 0] pi_sum = np.sum(pi) # log(a / b) should be calculated as log(a) - log(b) for # possible loss of precision return -np.sum((pi / pi_sum) * (np.log(pi) - log(pi_sum)))
[ "szarate@dnanexus.com" ]
szarate@dnanexus.com
26d03fcefa5d70539bb6d822b5978722de681a0c
a9e578a66a4706dedf83838ec3288adb893e57fd
/src/impute.py
e82f2af49047a8a2aa131493f61070eb732b20a6
[]
no_license
jgondin/predict-water-pump-failure
4e741c9385717c9f802e7ccc5fbc1c5032b81129
73d7664fb6b0ab605b6b3d6605ede256a56024fa
refs/heads/master
2020-12-25T17:16:36.944533
2016-07-09T22:53:14
2016-07-09T22:53:14
62,754,230
1
0
null
2016-07-06T21:22:52
2016-07-06T21:22:52
null
UTF-8
Python
false
false
13,041
py
import pandas as pd #import matplotlib.pyplot as plt #import statsmodels.api as sm #import seaborn as sbrn import numpy as np #import re #import trainetime import pickle #from collections import OrderedDict #import sklearn def imputeTrain(trn): """ Input: Training dataset Output: Returns copy of imputed training set; and a reference map (nested dictionary) Function takes in a trainaset for the "water pump failure" driventraina.org competition and returns a list of two items: 1. A training dataframe that contains imputed columns, namely: - gps_height - population - latitude - longitude - construction_year *Note: An exception will be thrown if any one of these columns are missing *Note: Columns do not need to contain 'NaN' values. The function will replace zeroes with NaNs as well as erroneous lat, long values *Note: Uses a heirarchical geographically nearest neighbors mean measure 2. A nested dictionary in the following format that contains trained imputed values for each variable above, by a heirarchical geography. The intent is to use this nested dictionary to inform unseen test observations during prediction. """ train = trn.copy() imputeCols = ['gps_height','population','latitude','longitude','construction_year', 'subvillage','ward','lga','region_code'] imputeMap = {'population':{'subvillage':{},'ward':{},'lga':{},'region_code':{}}, 'gps_height':{'subvillage':{},'ward':{},'lga':{},'region_code':{}}, 'construction_year':{'subvillage':{},'ward':{},'lga':{},'region_code':{}}, 'latitude':{'subvillage':{},'ward':{},'lga':{},'region_code':{}}, 'longitude':{'subvillage':{},'ward':{},'lga':{},'region_code':{}} } exception = 'Missing Columns! Please make sure all of the following columns are in your training frame: \n'+str(imputeCols) if not set(imputeCols) < set(list(train.columns)): raise Exception(exception) #replace continuous predictor missing values (0s) with NaN train.population.replace({0:np.nan,1:np.nan,2:np.nan}, inplace=True) train.gps_height.replace({0:np.nan}, inplace=True) train['construction_year']=train['construction_year'].astype('int64') train.loc[train.construction_year==0,['construction_year']]=np.nan #replace lat/long outliers with NaN; replace in plce won't work for multiple columns train.loc[((train.longitude==0)&(train.latitude==-2.000000e-08)),['latitude','longitude']]=train.loc[((train.longitude==0)&(train.latitude==-2.000000e-08)),['latitude','longitude']].replace({'latitude':{-2.000000e-08:np.nan}, 'longitude':{0.0:np.nan}}, regex=False) #now, impute NaNs with the mean of hierarchical geographies going from nearest to farthest: #sub-village > ward > lga > region_code #population #first, store location mean per location unit imputeMap=generateMap('subvillage','population',train,imputeMap) train.population.fillna(train.groupby(['subvillage'])['population'].transform('mean'), inplace=True) imputeMap=generateMap('ward','population',train,imputeMap) train.population.fillna(train.groupby(['ward'])['population'].transform('mean'), inplace=True) imputeMap=generateMap('lga','population',train,imputeMap) train.population.fillna(train.groupby(['lga'])['population'].transform('mean'), inplace=True) imputeMap=generateMap('region_code','population',train,imputeMap) train.population.fillna(train.groupby(['region_code'])['population'].transform('mean'), inplace=True) #gps_height (do the same thing) imputeMap=generateMap('subvillage','gps_height',train,imputeMap) train.gps_height.fillna(train.groupby(['subvillage'])['gps_height'].transform('mean'), inplace=True) imputeMap=generateMap('ward','gps_height',train,imputeMap) train.gps_height.fillna(train.groupby(['ward'])['gps_height'].transform('mean'), inplace=True) imputeMap=generateMap('lga','gps_height',train,imputeMap) train.gps_height.fillna(train.groupby(['lga'])['gps_height'].transform('mean'), inplace=True) imputeMap=generateMap('region_code','gps_height',train,imputeMap) train.gps_height.fillna(train.groupby(['region_code'])['gps_height'].transform('mean'), inplace=True) #construction_year (same! just set construction year back to int64 at the end) imputeMap=generateMap('subvillage','construction_year',train,imputeMap) train.construction_year.fillna(train.groupby(['subvillage'])['construction_year'].transform('mean'), inplace=True) imputeMap=generateMap('ward','construction_year',train,imputeMap) train.construction_year.fillna(train.groupby(['ward'])['construction_year'].transform('mean'), inplace=True) imputeMap=generateMap('lga','construction_year',train,imputeMap) train.construction_year.fillna(train.groupby(['lga'])['construction_year'].transform('mean'), inplace=True) imputeMap=generateMap('region_code','construction_year',train,imputeMap) train.construction_year.fillna(train.groupby(['region_code'])['construction_year'].transform('mean'), inplace=True) train['construction_year']=train.construction_year.astype('int64') #set to int! or we'll have too many #same for lats and longs imputeMap=generateMap('subvillage','latitude',train,imputeMap) train.latitude.fillna(train.groupby(['subvillage'])['latitude'].transform('mean'), inplace=True) imputeMap=generateMap('ward','latitude',train,imputeMap) train.latitude.fillna(train.groupby(['ward'])['latitude'].transform('mean'), inplace=True) imputeMap=generateMap('lga','latitude',train,imputeMap) train.latitude.fillna(train.groupby(['lga'])['latitude'].transform('mean'), inplace=True) imputeMap=generateMap('region_code','latitude',train,imputeMap) train.latitude.fillna(train.groupby(['region_code'])['latitude'].transform('mean'), inplace=True) #long imputeMap=generateMap('subvillage','longitude',train,imputeMap) train.longitude.fillna(train.groupby(['subvillage'])['longitude'].transform('mean'), inplace=True) imputeMap=generateMap('ward','longitude',train,imputeMap) train.longitude.fillna(train.groupby(['ward'])['longitude'].transform('mean'), inplace=True) imputeMap=generateMap('lga','longitude',train,imputeMap) train.longitude.fillna(train.groupby(['lga'])['longitude'].transform('mean'), inplace=True) imputeMap=generateMap('region_code','longitude',train,imputeMap) train.longitude.fillna(train.groupby(['region_code'])['longitude'].transform('mean'), inplace=True) return train, imputeMap def generateMap(geog, col, train, imputeMap): """helps the imputeTrain function out by storing the means of each location breakdown for that column in the nested dictionary""" grpdf = train.groupby(train[geog])[col].mean().reset_index() grpdf = grpdf.loc[~grpdf[col].isnull()] grpdf.set_index(grpdf.iloc[:,0], inplace=True) grpdf.drop(geog, inplace=True, axis=1) #insert into nested dict imputeMap[col][geog].update(grpdf.iloc[:,0].to_dict()) return imputeMap def fillTest(tst, imputeMap): """ Inputs: Test dataframe, reference map nested dictionary Outputs: Copy of Test dataframe with filled in trained values. uses a passed in reference map that contains trained means by geographical nearness for numerics - gps_height - population - latitude - longitude - construction_year. Function returns the passed in test dataframe with any missing values filled in according to the reference map. *Note: if input dataframe is sorted in any order the order will be lost as missing values are removed, filled in, and appended back to the dataframe. Simply re-sort if original order is desired. """ test_imp=tst.copy() imputeCols = ['gps_height','population','latitude','longitude','construction_year', 'subvillage','ward','lga','region_code'] exception = 'Missing Columns! Please make sure all of the following columns are in your test frame: \n'+str(imputeCols) numCols = ['gps_height','population','latitude','longitude','construction_year'] if not set(imputeCols) < set(list(test_imp.columns)): raise Exception(exception) geogHierarch = np.array(['subvillage','ward','lga','region_code']) #replace continuous predictor missing values (0s) with NaN test_imp.population.replace({0:np.nan, 1:np.nan, 2:np.nan}, inplace=True) test_imp.gps_height.replace({0:np.nan}, inplace=True) test_imp['construction_year']=test_imp['construction_year'].astype('int64') test_imp.loc[test_imp.construction_year==0,['construction_year']]=np.nan #replace lat/long outliers with NaN; replace in plce won't work for multiple columns test_imp.loc[((test_imp.longitude==0)&(test_imp.latitude==-2.000000e-08)),['latitude','longitude']]=test_imp.loc[((test_imp.longitude==0)&(test_imp.latitude==-2.000000e-08)),['latitude','longitude']].replace({'latitude':{-2.000000e-08:np.nan}, 'longitude':{0.0:np.nan}}, regex=False) #BACKUP IMPUTE STRATEGY: NOT USING REFERENCE MAP """ test.gps_height.fillna(test.groupby(['subvillage'])['gps_height'].transform('mean'), inplace=True) test.gps_height.fillna(test.groupby(['ward'])['gps_height'].transform('mean'), inplace=True) test.gps_height.fillna(test.groupby(['lga'])['gps_height'].transform('mean'), inplace=True) test.gps_height.fillna(test.groupby(['region_code'])['gps_height'].transform('mean'), inplace=True) test.population.fillna(test.groupby(['subvillage'])['population'].transform('mean'), inplace=True) test.population.fillna(test.groupby(['ward'])['population'].transform('mean'), inplace=True) test.population.fillna(test.groupby(['lga'])['population'].transform('mean'), inplace=True) test.populationr.fillna(test.groupby(['region_code'])['population'].transform('mean'), inplace=True) test.construction_year.fillna(test.groupby(['subvillage'])['construction_year'].transform('mean'), inplace=True) test.construction_year.fillna(test.groupby(['ward'])['construction_year'].transform('mean'), inplace=True) test.construction_year.fillna(test.groupby(['lga'])['construction_year'].transform('mean'), inplace=True) test.construction_year.fillna(test.groupby(['region_code'])['construction_year'].transform('mean'), inplace=True) test.latitude.fillna(test.groupby(['subvillage'])['latitude'].transform('mean'), inplace=True) test.latitude.fillna(test.groupby(['ward'])['latitude'].transform('mean'), inplace=True) test.latitude.fillna(test.groupby(['lga'])['latitude'].transform('mean'), inplace=True) test.latitude.fillna(test.groupby(['region_code'])['latitude'].transform('mean'), inplace=True) test.longitude.fillna(test.groupby(['subvillage'])['longitude'].transform('mean'), inplace=True) test.longitude.fillna(test.groupby(['ward'])['longitude'].transform('mean'), inplace=True) test.longitude.fillna(test.groupby(['lga'])['longitude'].transform('mean'), inplace=True) test.longitude.fillna(test.groupby(['region_code'])['longitude'].transform('mean'), inplace=True) """ df_id = test_imp[['id']] test = test_imp for col in numCols: if test[col].isnull().sum(): #subset ad remove from test frame col specific nulls (will append filled values later) test_sub = test[test[col].isnull()] test = test[~test[col].isnull()] #fill in missing values by tiered geography test_filled = test_sub[~test_sub[col].isnull()] #empty at first for geog in geogHierarch: #get col and geog specific reference map refdf = extractMap(imputeMap, col, geog) #now merge col and geog missing values in test with ref map test_sub=pd.merge(test_sub, refdf, how='left', on=geog) test_sub[col+'_x']=test_sub[col+'_y'] test_sub.drop(col+'_y', axis=1, inplace=True) test_sub=test_sub.rename(columns={col+'_x':col}) #remove _x #get all non NaNs from test_sub test_filled = pd.concat([test_filled,test_sub[~test_sub[col].isnull()]], axis=0) test_sub = test_sub[test_sub[col].isnull()] if test_sub.shape[0]==0: break #merge filled set and any remaining (could not fill) back to Test test = pd.concat([test, test_filled, test_sub], axis=0, ignore_index=True) #make sure construction year is an integer col test['construction_year']=test['construction_year'].astype('int64') df_merge = pd.merge(df_id, test, on='id') return df_merge def extractMap(imap, col, geog): """ Extract impute column and geography specific values from trained reference map. Returns a reference dataframe, with columns col, geog. """ #extract col and geog specific values from reference map as dataframe mapdf = pd.DataFrame() mapdf = mapdf.from_dict(imap[col][geog],orient='index') mapdf[geog]=mapdf.index mapdf.columns=[col,geog] return mapdf
[ "ashirwad08@yahoo.com" ]
ashirwad08@yahoo.com
1ad67f537ad7c367ceee20cd2b88f9124ff2566a
6971681df75216216f4b0a196b49077361ed6829
/src/olympia/migrations/335-perms-locales.py
6e210baccd4f36e7d0b22701cea1f573819fb9dc
[ "CC-BY-3.0", "CC-BY-NC-4.0", "CC-BY-4.0", "CC-BY-ND-3.0", "CC-BY-NC-ND-3.0", "CC-BY-SA-3.0", "CC-BY-NC-3.0", "CC-BY-NC-ND-4.0", "CC-BY-NC-SA-3.0" ]
permissive
piyushmittal25/addons-server
fb6eafc2c1239608c435e3afc7a6bd3db3e38e77
1527d1542f0e025940b7b370bf98350869737e2f
refs/heads/master
2020-03-18T21:44:06.420678
2018-05-29T11:08:31
2018-05-29T11:08:31
130,405,465
0
0
BSD-3-Clause
2018-04-23T10:56:40
2018-04-20T19:29:28
Python
UTF-8
Python
false
false
1,140
py
from django.conf import settings from access.models import Group, GroupUser LANGS = sorted(list( set(settings.AMO_LANGUAGES + settings.HIDDEN_LANGUAGES) - set(['en-US']))) def run(): Group.objects.create(pk=50006, name='Senior Localizers', rules='Locales:Edit') for idx, locale in enumerate(LANGS): pk = 50007 + idx name = '%s Localizers' % locale rules = 'Locale.%s:Edit,L10nTools:View' % locale group = Group.objects.create(pk=pk, name=name, rules=rules) print 'New group created: (%d) %s' % (pk, name) try: old_group = Group.objects.get(pk__lt=50000, name=name) except Group.DoesNotExist: print 'Old group not found: %s' % name continue # Rename old groups so they are distinguisable. old_group.update(name=old_group.name + ' (OLD)') # Migrate users to new group. cnt = 0 for user in old_group.users.all(): cnt += 1 GroupUser.objects.create(group=group, user=user) print 'Migrated %d users to new group (%s)' % (cnt, name)
[ "chudson@mozilla.com" ]
chudson@mozilla.com
468ec6b362681d9a3018b5f0182ef31622ef30b1
1b0a729f6e20c542a6370785a49c181c0675e334
/main.py
35fb3f77ad0ea393411e9e0c57d85315d85bd310
[]
no_license
fans656/mint-dev
68125c4b41ab64b20d54a2b19e8bf0179dc4636b
408f6f055670b15a3f3ee9c9ec086b1090cce372
refs/heads/master
2021-05-04T11:43:44.740116
2016-09-07T13:43:44
2016-09-07T13:43:44
45,515,119
3
1
null
null
null
null
UTF-8
Python
false
false
239
py
from mint import * from mint.protocols.test import Retransmit a, b, c = Host(), Host(), Host() s = Switch() link(a, s.tips[0], 1) link(b, s.tips[1], 2) #link(c, s.tips[2], 3) a += Retransmit() a.send('hi') #b.send('me').at(5) start()
[ "fans656@yahoo.com" ]
fans656@yahoo.com
a66207933164a09184cfbafd8103be05a5840217
204833b06d6b62a66cf60c966835d0876f84432e
/Constants.py
ee09c1a8cfc4c6f068b2057c868b723727983bbc
[]
no_license
dariodematties/Dirichlet
d03a9067bcedd882f9e3421dc5a35c592da0c360
7a69ea351e64110b699290268379b6ef2fc86e4b
refs/heads/master
2018-11-10T11:02:49.439077
2018-08-21T17:37:26
2018-08-21T17:37:26
109,689,246
1
1
null
null
null
null
UTF-8
Python
false
false
32
py
ENABLE_RANDOM_BEHAVIOUR = True;
[ "dariodematties@yahoo.com.ar" ]
dariodematties@yahoo.com.ar
8dcb22ca5cfbfea727ccfbf086dcd7217f807a28
e5487abf1270a8b14f003c444b199483c6d825d2
/Code/lambda/skill_env/bin/rst2s5.py
28d30c28e7838663dfad221a9f679ae1e398e04c
[]
no_license
tmoessing/Coin-Collector
8828c789da2fa7a46fbfc741487d1a6dc533c7c8
c5e9dccee6ed393c81db7350bdab89111033ac33
refs/heads/master
2020-11-26T01:23:03.131189
2019-12-18T21:02:07
2019-12-18T21:02:07
223,520,354
0
0
null
null
null
null
UTF-8
Python
false
false
685
py
#!c:\users\tmoes\appdata\local\programs\python\python36\python.exe # $Id: rst2s5.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Chris Liechti <cliechti@gmx.net> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML slides using the S5 template system. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates S5 (X)HTML slideshow documents from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='s5', description=description)
[ "tmoessing@gmail.com" ]
tmoessing@gmail.com
ad42586e96c02a379336285a2bc1b60cb0230dec
5e6d8b9989247801718dd1f10009f0f7f54c1eb4
/sdk/python/pulumi_azure_native/containerinstance/v20180401/container_group.py
393f32a489204ca350e64cfea46921dc0a2db827
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
vivimouret29/pulumi-azure-native
d238a8f91688c9bf09d745a7280b9bf2dd6d44e0
1cbd988bcb2aa75a83e220cb5abeb805d6484fce
refs/heads/master
2023-08-26T05:50:40.560691
2021-10-21T09:25:07
2021-10-21T09:25:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
21,452
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['ContainerGroupArgs', 'ContainerGroup'] @pulumi.input_type class ContainerGroupArgs: def __init__(__self__, *, containers: pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]], os_type: pulumi.Input[Union[str, 'OperatingSystemTypes']], resource_group_name: pulumi.Input[str], container_group_name: Optional[pulumi.Input[str]] = None, image_registry_credentials: Optional[pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]]] = None, ip_address: Optional[pulumi.Input['IpAddressArgs']] = None, location: Optional[pulumi.Input[str]] = None, restart_policy: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, volumes: Optional[pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]]] = None): """ The set of arguments for constructing a ContainerGroup resource. :param pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]] containers: The containers within the container group. :param pulumi.Input[Union[str, 'OperatingSystemTypes']] os_type: The operating system type required by the containers in the container group. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] container_group_name: The name of the container group. :param pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]] image_registry_credentials: The image registry credentials by which the container group is created from. :param pulumi.Input['IpAddressArgs'] ip_address: The IP address type of the container group. :param pulumi.Input[str] location: The resource location. :param pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']] restart_policy: Restart policy for all containers within the container group. - `Always` Always restart - `OnFailure` Restart on failure - `Never` Never restart :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: The resource tags. :param pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]] volumes: The list of volumes that can be mounted by containers in this container group. """ pulumi.set(__self__, "containers", containers) pulumi.set(__self__, "os_type", os_type) pulumi.set(__self__, "resource_group_name", resource_group_name) if container_group_name is not None: pulumi.set(__self__, "container_group_name", container_group_name) if image_registry_credentials is not None: pulumi.set(__self__, "image_registry_credentials", image_registry_credentials) if ip_address is not None: pulumi.set(__self__, "ip_address", ip_address) if location is not None: pulumi.set(__self__, "location", location) if restart_policy is not None: pulumi.set(__self__, "restart_policy", restart_policy) if tags is not None: pulumi.set(__self__, "tags", tags) if volumes is not None: pulumi.set(__self__, "volumes", volumes) @property @pulumi.getter def containers(self) -> pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]]: """ The containers within the container group. """ return pulumi.get(self, "containers") @containers.setter def containers(self, value: pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]]): pulumi.set(self, "containers", value) @property @pulumi.getter(name="osType") def os_type(self) -> pulumi.Input[Union[str, 'OperatingSystemTypes']]: """ The operating system type required by the containers in the container group. """ return pulumi.get(self, "os_type") @os_type.setter def os_type(self, value: pulumi.Input[Union[str, 'OperatingSystemTypes']]): pulumi.set(self, "os_type", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The name of the resource group. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="containerGroupName") def container_group_name(self) -> Optional[pulumi.Input[str]]: """ The name of the container group. """ return pulumi.get(self, "container_group_name") @container_group_name.setter def container_group_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "container_group_name", value) @property @pulumi.getter(name="imageRegistryCredentials") def image_registry_credentials(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]]]: """ The image registry credentials by which the container group is created from. """ return pulumi.get(self, "image_registry_credentials") @image_registry_credentials.setter def image_registry_credentials(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]]]): pulumi.set(self, "image_registry_credentials", value) @property @pulumi.getter(name="ipAddress") def ip_address(self) -> Optional[pulumi.Input['IpAddressArgs']]: """ The IP address type of the container group. """ return pulumi.get(self, "ip_address") @ip_address.setter def ip_address(self, value: Optional[pulumi.Input['IpAddressArgs']]): pulumi.set(self, "ip_address", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ The resource location. """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="restartPolicy") def restart_policy(self) -> Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]]: """ Restart policy for all containers within the container group. - `Always` Always restart - `OnFailure` Restart on failure - `Never` Never restart """ return pulumi.get(self, "restart_policy") @restart_policy.setter def restart_policy(self, value: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]]): pulumi.set(self, "restart_policy", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ The resource tags. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) @property @pulumi.getter def volumes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]]]: """ The list of volumes that can be mounted by containers in this container group. """ return pulumi.get(self, "volumes") @volumes.setter def volumes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]]]): pulumi.set(self, "volumes", value) class ContainerGroup(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, container_group_name: Optional[pulumi.Input[str]] = None, containers: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerArgs']]]]] = None, image_registry_credentials: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ImageRegistryCredentialArgs']]]]] = None, ip_address: Optional[pulumi.Input[pulumi.InputType['IpAddressArgs']]] = None, location: Optional[pulumi.Input[str]] = None, os_type: Optional[pulumi.Input[Union[str, 'OperatingSystemTypes']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, restart_policy: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, volumes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VolumeArgs']]]]] = None, __props__=None): """ A container group. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] container_group_name: The name of the container group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerArgs']]]] containers: The containers within the container group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ImageRegistryCredentialArgs']]]] image_registry_credentials: The image registry credentials by which the container group is created from. :param pulumi.Input[pulumi.InputType['IpAddressArgs']] ip_address: The IP address type of the container group. :param pulumi.Input[str] location: The resource location. :param pulumi.Input[Union[str, 'OperatingSystemTypes']] os_type: The operating system type required by the containers in the container group. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']] restart_policy: Restart policy for all containers within the container group. - `Always` Always restart - `OnFailure` Restart on failure - `Never` Never restart :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: The resource tags. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VolumeArgs']]]] volumes: The list of volumes that can be mounted by containers in this container group. """ ... @overload def __init__(__self__, resource_name: str, args: ContainerGroupArgs, opts: Optional[pulumi.ResourceOptions] = None): """ A container group. :param str resource_name: The name of the resource. :param ContainerGroupArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ContainerGroupArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, container_group_name: Optional[pulumi.Input[str]] = None, containers: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerArgs']]]]] = None, image_registry_credentials: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ImageRegistryCredentialArgs']]]]] = None, ip_address: Optional[pulumi.Input[pulumi.InputType['IpAddressArgs']]] = None, location: Optional[pulumi.Input[str]] = None, os_type: Optional[pulumi.Input[Union[str, 'OperatingSystemTypes']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, restart_policy: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, volumes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VolumeArgs']]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ContainerGroupArgs.__new__(ContainerGroupArgs) __props__.__dict__["container_group_name"] = container_group_name if containers is None and not opts.urn: raise TypeError("Missing required property 'containers'") __props__.__dict__["containers"] = containers __props__.__dict__["image_registry_credentials"] = image_registry_credentials __props__.__dict__["ip_address"] = ip_address __props__.__dict__["location"] = location if os_type is None and not opts.urn: raise TypeError("Missing required property 'os_type'") __props__.__dict__["os_type"] = os_type if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["restart_policy"] = restart_policy __props__.__dict__["tags"] = tags __props__.__dict__["volumes"] = volumes __props__.__dict__["instance_view"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:containerinstance/v20180401:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20170801preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20170801preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20171001preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20171001preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20171201preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20171201preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20180201preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20180201preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20180601:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20180601:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20180901:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20180901:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20181001:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20181001:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20191201:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20191201:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20201101:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20201101:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20210301:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20210301:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20210701:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20210701:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20210901:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20210901:ContainerGroup")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ContainerGroup, __self__).__init__( 'azure-native:containerinstance/v20180401:ContainerGroup', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ContainerGroup': """ Get an existing ContainerGroup resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ContainerGroupArgs.__new__(ContainerGroupArgs) __props__.__dict__["containers"] = None __props__.__dict__["image_registry_credentials"] = None __props__.__dict__["instance_view"] = None __props__.__dict__["ip_address"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["os_type"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["restart_policy"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None __props__.__dict__["volumes"] = None return ContainerGroup(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def containers(self) -> pulumi.Output[Sequence['outputs.ContainerResponse']]: """ The containers within the container group. """ return pulumi.get(self, "containers") @property @pulumi.getter(name="imageRegistryCredentials") def image_registry_credentials(self) -> pulumi.Output[Optional[Sequence['outputs.ImageRegistryCredentialResponse']]]: """ The image registry credentials by which the container group is created from. """ return pulumi.get(self, "image_registry_credentials") @property @pulumi.getter(name="instanceView") def instance_view(self) -> pulumi.Output['outputs.ContainerGroupResponseInstanceView']: """ The instance view of the container group. Only valid in response. """ return pulumi.get(self, "instance_view") @property @pulumi.getter(name="ipAddress") def ip_address(self) -> pulumi.Output[Optional['outputs.IpAddressResponse']]: """ The IP address type of the container group. """ return pulumi.get(self, "ip_address") @property @pulumi.getter def location(self) -> pulumi.Output[Optional[str]]: """ The resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="osType") def os_type(self) -> pulumi.Output[str]: """ The operating system type required by the containers in the container group. """ return pulumi.get(self, "os_type") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state of the container group. This only appears in the response. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="restartPolicy") def restart_policy(self) -> pulumi.Output[Optional[str]]: """ Restart policy for all containers within the container group. - `Always` Always restart - `OnFailure` Restart on failure - `Never` Never restart """ return pulumi.get(self, "restart_policy") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ The resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ The resource type. """ return pulumi.get(self, "type") @property @pulumi.getter def volumes(self) -> pulumi.Output[Optional[Sequence['outputs.VolumeResponse']]]: """ The list of volumes that can be mounted by containers in this container group. """ return pulumi.get(self, "volumes")
[ "noreply@github.com" ]
vivimouret29.noreply@github.com
17edec3a0cbd5397bc360dc2289f7aa23fef2f2b
02122ec38633c178ced34d8a027addc919b4c200
/Nutrients/api/urls.py
757826e0b86fe90b0ab82e9e332d35f5dd0ee419
[]
no_license
SIBU99/serverCVKM
07907b3c416892bcc432b9317506927112750a93
8182f2274216016a15a2a98ea5a31d7e05222ed5
refs/heads/master
2023-01-12T10:19:54.966211
2020-11-10T08:33:41
2020-11-10T08:33:41
311,407,784
0
0
null
null
null
null
UTF-8
Python
false
false
182
py
from django.urls import path from .views import NutrientExamination urlpatterns = [ path("nutrient-examination/", NutrientExamination.as_view(), name="nutrient-examination"), ]
[ "kumarmishra678@gmail.com" ]
kumarmishra678@gmail.com
a006f031a6bef10a643b1366ee30edb96ede4562
7e40fdb15a67e3b53162bbcd2b1f091805837d9f
/article/migrations/0006_auto__add_newslettermain.py
ee4e4c7d24923010ed32341a3a741fa9e7bb03f5
[]
no_license
brentcappello/newsdub
79a5eecd92dcaf44aa07314eedbc7d5183683689
cdfc6619cc8b89bc224100e913cb85378d0d8cea
refs/heads/master
2016-09-01T20:53:07.784968
2012-11-15T02:53:41
2012-11-15T02:53:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,992
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'NewsletterMain' db.create_table('article_newslettermain', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=200)), ('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)), ('description', self.gf('django.db.models.fields.TextField')()), ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), ('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)), ('status', self.gf('django.db.models.fields.IntegerField')(default=2)), )) db.send_create_signal('article', ['NewsletterMain']) # Adding M2M table for field newsletters_main on 'Newsletter' db.create_table('article_newsletter_newsletters_main', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('newsletter', models.ForeignKey(orm['article.newsletter'], null=False)), ('newslettermain', models.ForeignKey(orm['article.newslettermain'], null=False)) )) db.create_unique('article_newsletter_newsletters_main', ['newsletter_id', 'newslettermain_id']) def backwards(self, orm): # Deleting model 'NewsletterMain' db.delete_table('article_newslettermain') # Removing M2M table for field newsletters_main on 'Newsletter' db.delete_table('article_newsletter_newsletters_main') models = { 'article.newsletter': { 'Meta': {'ordering': "('-publish',)", 'object_name': 'Newsletter'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'newsletters_main': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['article.NewsletterMain']", 'symmetrical': 'False'}), 'publish': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'article.newslettermain': { 'Meta': {'object_name': 'NewsletterMain'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'article.post': { 'Meta': {'ordering': "('-publish',)", 'object_name': 'Post'}, 'allow_comments': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'added_posts'", 'to': "orm['auth.User']"}), 'body': ('django.db.models.fields.TextField', [], {}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'newsletters': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['article.Newsletter']", 'symmetrical': 'False'}), 'publish': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'tease': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) } } complete_apps = ['article']
[ "brent@gmail" ]
brent@gmail
a56825bd2f75c83393aad08f9a63136c9a6cd561
393f30495e9cecebd6f8950d51b10c0817ed7d28
/venv/task2_10.py
ad6a65bf495eaffc67787979cd14e929bce47380
[]
no_license
Skornel/NNGASU_Domrachev_Python
8f741d99a9b689e4c09a739ff42b0648da0cf24c
9a996925ca6729178b7a439025508aad72d633ae
refs/heads/master
2020-12-19T15:36:24.546269
2020-04-13T15:48:24
2020-04-13T15:48:24
235,776,259
1
0
null
null
null
null
UTF-8
Python
false
false
596
py
s=[] for i in range(4): b=[] print("Введите данные ",i+1," списка") for row in range(4): print("Вводи ",row+1," элемент ",i+1," списка ") b.append(input()) s.append(b) print(s) maximum=0 minimum=1000 for i in range(len(s)): for j in range(len(s[i])): if int(s[i][j])>int(maximum): maximum=s[i][j] if int(s[i][j])<int(minimum): minimum=s[i][j] print("Максимальное число:", maximum, "Минимальное: ", minimum, " Разность: ",int(maximum)-int(minimum))
[ "Suslova2907@gmail.com" ]
Suslova2907@gmail.com
42e1c516f36f4fbc2863cfbb85713138553946f4
e62ade72c9808b806a523a73908fa1032b10f9fc
/AlgorithmPrograms/InsertionSort.py
42bdf35e24078997b64c895332640f2b507087c1
[]
no_license
manjumugali/Python_Programs
40b0b77586cc20d1f77b6035cdc67f62b5e9955e
06934cb8037594dd4269f8c2fee3d301c27f624f
refs/heads/master
2020-04-17T06:54:55.571579
2019-02-13T04:37:25
2019-02-13T04:37:25
166,344,863
0
0
null
null
null
null
UTF-8
Python
false
false
981
py
""" ****************************************************************************** * Purpose: Reads in strings from standard input and prints them in sorted order.Uses insertion sort. * * @author: Manjunath Mugali * @version: 3.7 * @since: 16-01-2019 * ****************************************************************************** """ import re from Utility import UtilityTest c1 = UtilityTest.TestFunctional() class InsertionSort: try: print("Enter The String") str1 = input() # read The String onlystr = re.sub('[^A-Za-z]+', ' ', str1) # Remove The All Special Characters word = onlystr.split() # It splits the Given Sentence into Words(by Space) print("Before Sorting:") print(word) print("After Sorting:") sort = c1.insertionSort(word) # Invoking function it takes One arguments As list print(sort) except ValueError: print("...........oops Something Went Wrong.........")
[ "manjumugali111@gmail.com" ]
manjumugali111@gmail.com
6316d5bbf61b883c8a1230ade79e25d1b8b68ce4
8b4521c046779bee7f0499d73e183851f198af14
/server.py
b5d0f09fbb907e26b62a438d288a204612cc22b5
[]
no_license
sugrospi/RPSLS
80fa53a88f1531af03809716c44f10a937a125e4
1c50c9b3019dcc8f244f6ae2d1cba87d409bbd56
refs/heads/master
2023-07-24T15:21:35.423381
2021-09-07T15:13:47
2021-09-07T15:13:47
403,999,856
0
0
null
null
null
null
UTF-8
Python
false
false
1,475
py
import socket from _thread import * import pickle from game import Game server = "IP_ADDRESS" port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((server, port)) except socket.error as e: str(e) s.listen(2) print("Waiting for a connection, Server Started") connected = set() games = {} idCount = 0 def threaded_client(conn, p, gameId): global idCount conn.send(str.encode(str(p))) reply = "" while True: try: data = conn.recv(4096).decode() if gameId in games: game = games[gameId] if not data: break else: if data == "reset": game.resetWent() elif data != "get": game.play(p, data) conn.sendall(pickle.dumps(game)) else: break except: break print("Lost connection") try: del games[gameId] print("Closing Game", gameId) except: pass idCount -= 1 conn.close() while True: conn, addr = s.accept() print("Connected to:", addr) idCount += 1 p = 0 gameId = (idCount - 1)//2 if idCount % 2 == 1: games[gameId] = Game(gameId) print("Creating a new game...") else: games[gameId].ready = True p = 1 start_new_thread(threaded_client, (conn, p, gameId))
[ "s.shaggypi@gmail.com" ]
s.shaggypi@gmail.com
2f42da8393cd536ef56b1a0bef15efe947177b66
d83118503614bb83ad8edb72dda7f449a1226f8b
/src/dprj/platinumegg/app/cabaret/views/mgr/model_edit/trade_shop.py
d402834b28b5ad1f8056bc5d4ec9eec808d29ae6
[]
no_license
hitandaway100/caba
686fe4390e182e158cd9714c90024a082deb8c69
492bf477ac00c380f2b2758c86b46aa7e58bbad9
refs/heads/master
2021-08-23T05:59:28.910129
2017-12-03T19:03:15
2017-12-03T19:03:15
112,512,044
0
0
null
null
null
null
UTF-8
Python
false
false
2,156
py
# -*- coding: utf-8 -*- from platinumegg.app.cabaret.views.mgr.model_edit import AdminModelEditHandler,\ AppModelForm, ModelEditValidError, AppModelChoiceField from defines import Defines from platinumegg.app.cabaret.util.api import BackendApi from platinumegg.app.cabaret.models.TradeShop import TradeShopMaster, TradeShopItemMaster from platinumegg.app.cabaret.models.Schedule import ScheduleMaster class Handler(AdminModelEditHandler): """マスターデータの操作. """ class Form(AppModelForm): class Meta: model = TradeShopMaster exclude = ( Defines.MASTER_EDITTIME_COLUMN, ) schedule = AppModelChoiceField(ScheduleMaster, required=False, label=u'期間') def setting_property(self): self.MODEL_LABEL = u'トレードショップ' def valid_insert(self, master): self.__valid_master(master) def valid_update(self, master): self.__valid_master(master) def __valid_master(self, master): model_mgr = self.getModelMgr() self.__check_schedule(model_mgr, master) self.__check_trade_shop_item_masetr_ids(model_mgr, master) model_mgr.write_all() def __check_schedule(self, model_mgr, master): model = model_mgr.get_model(ScheduleMaster, master.schedule) if model is None: raise ModelEditValidError(u'スケジュールに、存在しないIDが指定されています.id=%d' % master.id) def __check_trade_shop_item_masetr_ids(self, model_mgr, master): if not isinstance(master.trade_shop_item_master_ids, (list)): raise ModelEditValidError(u'trade_shop_item_master_idsのJsonが壊れています.id=%d' % master.id) for trade_shop_item_master_id in master.trade_shop_item_master_ids: model = model_mgr.get_model(TradeShopItemMaster, trade_shop_item_master_id) if model is None: raise ModelEditValidError(u'trade_shop_item_master_idsで指定されているidがTradeShopItemMasterに存在しません.id=%d' % master.id) def main(request): return Handler.run(request)
[ "shangye@mail.com" ]
shangye@mail.com
47b2fcaa1e74c97b42be077420a4335f38b24f8d
a7ff1ba9437204454c6b8639e99b007393c64118
/synapse/tools/aha/enroll.py
a643a485268842bbc531afab92dd9b5e8bf84112
[ "Apache-2.0" ]
permissive
vishalbelsare/synapse
67013933db31ac71a4074b08a46b129774f63e47
a418b1354b2f94e32644ede612c271a6c362ccae
refs/heads/master
2023-09-01T10:45:34.439767
2022-05-13T21:07:20
2022-05-13T21:07:20
164,022,574
0
0
Apache-2.0
2022-05-15T07:45:07
2019-01-03T21:01:32
Python
UTF-8
Python
false
false
2,609
py
import os import sys import asyncio import argparse import synapse.common as s_common import synapse.telepath as s_telepath import synapse.lib.output as s_output import synapse.lib.certdir as s_certdir descr = ''' Use a one-time use key to initialize your AHA user enrivonment. Examples: python -m synapse.tools.aha.register tcp://aha.loop.vertex.link:27272/b751e6c3e6fc2dad7a28d67e315e1874 ''' async def main(argv, outp=s_output.stdout): pars = argparse.ArgumentParser(prog='provision', description=descr) pars.add_argument('onceurl', help='The one-time use AHA user enrollment URL.') opts = pars.parse_args(argv) async with s_telepath.withTeleEnv(): certpath = s_common.getSynDir('certs') yamlpath = s_common.getSynPath('telepath.yaml') teleyaml = s_common.yamlload(yamlpath) if teleyaml is None: teleyaml = {} teleyaml.setdefault('version', 1) teleyaml.setdefault('aha:servers', ()) s_common.gendir(certpath) certdir = s_certdir.CertDir(path=certpath) async with await s_telepath.openurl(opts.onceurl) as prov: userinfo = await prov.getUserInfo() ahaurls = userinfo.get('aha:urls') ahauser = userinfo.get('aha:user') ahanetw = userinfo.get('aha:network') username = f'{ahauser}@{ahanetw}' capath = certdir.getCaCertPath(ahanetw) if capath is not None: os.path.unlink(capath) byts = await prov.getCaCert() capath = certdir.saveCaCertByts(byts) outp.printf(f'Saved CA certificate: {capath}') keypath = certdir.getUserKeyPath(username) if keypath is not None: os.path.unlink(keypath) crtpath = certdir.getUserCertPath(username) if crtpath is not None: os.path.unlink(keypath) xcsr = certdir.genUserCsr(username) byts = await prov.signUserCsr(xcsr) crtpath = certdir.saveUserCertByts(byts) outp.printf(f'Saved user certificate: {crtpath}') ahaurls = s_telepath.modurl(ahaurls, user=ahauser) if ahaurls not in teleyaml.get('aha:servers'): outp.printf('Updating known AHA servers') servers = list(teleyaml.get('aha:servers')) servers.append(ahaurls) teleyaml['aha:servers'] = servers s_common.yamlsave(teleyaml, yamlpath) if __name__ == '__main__': # pragma: no cover sys.exit(asyncio.run(main(sys.argv[1:])))
[ "noreply@github.com" ]
vishalbelsare.noreply@github.com
b27a50e038b03e30c82265c12688de6cc9a21df9
0ac34d1fad3ed7e18b3803a25878a8e3d74a259e
/messages_app/forms.py
39b210591b39588f92dd76cf69d3813ca820b149
[]
no_license
predictnonprofit/PredictME-WebApplication
b20a35a3ca9fcd0f8349cca83a75576afe96841c
557864cf9b98188478b9661cba23477d3e16ff85
refs/heads/main
2023-08-12T12:01:53.865143
2021-10-06T18:40:01
2021-10-06T18:40:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
272
py
# -*- coding: utf-8 -*-# from django.forms import ModelForm from .models import MemberMessages class MemberMessagesForm(ModelForm): class Meta: model = MemberMessages fields = ('sender', 'subject', "other_subject", "attachment", 'message', "reply")
[ "ibm_luq95@yahoo.com" ]
ibm_luq95@yahoo.com
07ed4b9273137675fff9b21384eac1a28eb95b43
137524b533472fd4b2752078e0a6d7f4c0fcf2d7
/tasksLab1/task2/TaskC.py
fcb64df58dd9a0784cd9d4db227026f85e35aa2e
[]
no_license
blazejmichal/inteligencja-obliczeniowa
8666869c227006fdae5dc1ab3a1b549c1db91548
4ffef53cddd82711d559eafd5c9d47e09c0e048d
refs/heads/master
2023-02-17T05:42:43.522395
2021-01-17T16:09:34
2021-01-17T16:09:34
319,463,135
0
0
null
null
null
null
UTF-8
Python
false
false
595
py
import matplotlib.pyplot as plt import csv class Task2c: def __init__(self): pass @staticmethod def execute(): x = [] y = [] with open('miasta.csv') as csvfile: reader = csv.DictReader(csvfile) for column in reader: x.append(column['Rok']) y.append(column['Gdansk']) plt.plot(x, y, 'r', label='Krzywa wykresu') plt.xlabel('Lata') plt.ylabel('Liczba ludnosci [w tys.]') plt.title('Ludnosc w miastach Polski (Gdansk)') plt.legend() plt.show()
[ "Blazej@DESKTOP-P8SE49K" ]
Blazej@DESKTOP-P8SE49K
ace388a41b74682d643ef7c6c7176d8cf1f6b831
3a5d8cdc7ac14c389fd9426f3f39c3b1dc906dda
/nautobot/extras/tests/test_jobs.py
e04668889b1dffc9a3853d2e190027a5f793514f
[ "Apache-2.0" ]
permissive
nammie-punshine/nautobot
f3cdb9d269c37a74706c105d237b883650f10465
d6227b211ad89f25233a8791937cd75092421c8a
refs/heads/main
2023-03-08T10:51:29.437859
2021-02-24T20:44:32
2021-02-24T20:44:32
342,080,836
0
0
Apache-2.0
2021-02-25T01:01:36
2021-02-25T01:01:36
null
UTF-8
Python
false
false
1,970
py
import os import uuid from django.conf import settings from django.contrib.contenttypes.models import ContentType from nautobot.extras.choices import JobResultStatusChoices from nautobot.extras.jobs import get_job, run_job from nautobot.extras.models import JobResult from nautobot.utilities.testing import TestCase class JobTest(TestCase): """ Test basic jobs to ensure importing works. """ def test_job_pass(self): """ Job test with pass result. """ with self.settings(JOBS_ROOT=os.path.join(settings.BASE_DIR, "extras/tests/dummy_jobs")): module = "test_pass" name = "TestPass" job_class = get_job(f"local/{module}/{name}") job_content_type = ContentType.objects.get(app_label="extras", model="job") job_result = JobResult.objects.create( name=job_class.class_path, obj_type=job_content_type, user=None, job_id=uuid.uuid4(), ) run_job(data={}, request=None, commit=False, job_result=job_result) self.assertEqual(job_result.status, JobResultStatusChoices.STATUS_COMPLETED) def test_job_fail(self): """ Job test with fail result. """ with self.settings(JOBS_ROOT=os.path.join(settings.BASE_DIR, "extras/tests/dummy_jobs")): module = "test_fail" name = "TestFail" job_class = get_job(f"local/{module}/{name}") job_content_type = ContentType.objects.get(app_label="extras", model="job") job_result = JobResult.objects.create( name=job_class.class_path, obj_type=job_content_type, user=None, job_id=uuid.uuid4(), ) run_job(data={}, request=None, commit=False, job_result=job_result) self.assertEqual(job_result.status, JobResultStatusChoices.STATUS_ERRORED)
[ "lampwins@gmail.com" ]
lampwins@gmail.com
0829499a37fc13ac636386433fe887068436789a
b8ab0e1ac2634741a05e5fef583585b597a6cdcf
/wsltools/utils/faker/providers/date_time/fil_PH/__init__.py
42a736439193745ecd672678cc198a9d48ef49e4
[ "MIT" ]
permissive
Symbo1/wsltools
be99716eac93bfc270a5ef0e47769290827fc0c4
0b6e536fc85c707a1c81f0296c4e91ca835396a1
refs/heads/master
2022-11-06T16:07:50.645753
2020-06-30T13:08:00
2020-06-30T13:08:00
256,140,035
425
34
MIT
2020-04-16T14:10:45
2020-04-16T07:22:21
Python
UTF-8
Python
false
false
829
py
from .. import Provider as DateTimeProvider class Provider(DateTimeProvider): """Provider for datetimes for fil_PH locale""" DAY_NAMES = { '0': 'Linggo', '1': 'Lunes', '2': 'Martes', '3': 'Miyerkules', '4': 'Huwebes', '5': 'Biyernes', '6': 'Sabado', } MONTH_NAMES = { '01': 'Enero', '02': 'Pebrero', '03': 'Marso', '04': 'Abril', '05': 'Mayo', '06': 'Hunyo', '07': 'Hulyo', '08': 'Agosto', '09': 'Setyembre', '10': 'Oktubre', '11': 'Nobyembre', '12': 'Disyembre', } def day_of_week(self): day = self.date('%w') return self.DAY_NAMES[day] def month_name(self): month = self.month() return self.MONTH_NAMES[month]
[ "tr3jer@gmail.com" ]
tr3jer@gmail.com
b3cffcaaac0bef8d65f8fdbae1aa31e4b48f15ed
2a1b8a671aceda6bc446f8ce26400aa84fa444a6
/Packs/FiltersAndTransformers/Scripts/JoinIfSingleElementOnly/JoinIfSingleElementOnly.py
c91e49454d83bdef53b8f6eeabbd9dcc16b073fc
[ "MIT" ]
permissive
demisto/content
6d4722d46f0ff0beea2748e9f7de585bf91a78b4
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
refs/heads/master
2023-09-04T00:02:25.618032
2023-09-03T21:56:22
2023-09-03T21:56:22
60,525,392
1,023
1,921
MIT
2023-09-14T20:55:24
2016-06-06T12:17:02
Python
UTF-8
Python
false
false
466
py
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def return_first_element_if_single(value): res = value if isinstance(value, list): if len(value) == 1: res = value[0] return res def main(): # pragma: no cover value = demisto.args()["value"] res = return_first_element_if_single(value) demisto.results(res) if __name__ in ('__main__', '__builtin__', 'builtins'): main()
[ "noreply@github.com" ]
demisto.noreply@github.com
8d80bf9946e1f8e66795f476eeb0e9382bf7ca7d
0c70dcec22a090e70b1f20613ea6e0a64fd9a037
/GPS卫星位置的计算/venv/Lib/site-packages/pandas/core/arrays/boolean.py
071e1ce42914a78c713b3948405141a7734c0ce1
[ "MIT" ]
permissive
payiz-asj/Gis
82c1096d830878f62c7a0d5dfb6630d4e4744764
3d315fed93e2ab850b836ddfd7a67f5618969d10
refs/heads/main
2023-06-27T15:25:17.301154
2021-08-03T10:02:58
2021-08-03T10:02:58
392,269,853
1
1
null
null
null
null
UTF-8
Python
false
false
25,132
py
import numbers from typing import TYPE_CHECKING, List, Tuple, Type, Union import warnings import numpy as np from pandas._libs import lib, missing as libmissing from pandas._typing import ArrayLike from pandas.compat import set_function_name from pandas.compat.numpy import function as nv from pandas.core.dtypes.common import ( is_bool_dtype, is_extension_array_dtype, is_float, is_float_dtype, is_integer_dtype, is_list_like, is_numeric_dtype, pandas_dtype, ) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries from pandas.core.dtypes.missing import isna from pandas.core import ops from .masked import BaseMaskedArray, BaseMaskedDtype if TYPE_CHECKING: import pyarrow # noqa: F401 @register_extension_dtype class BooleanDtype(BaseMaskedDtype): """ Extension dtype for boolean data. .. versionadded:: 1.0.0 .. warning:: BooleanDtype is considered experimental. The implementation and parts of the API may change without warning. Attributes ---------- None Methods ------- None Examples -------- >>> pd.BooleanDtype() BooleanDtype """ name = "boolean" @property def type(self) -> Type[np.bool_]: return np.bool_ @property def kind(self) -> str: return "b" @property def numpy_dtype(self) -> np.dtype: return np.dtype("bool") @classmethod def construct_array_type(cls) -> Type["BooleanArray"]: """ Return the array type associated with this dtype. Returns ------- type """ return BooleanArray def __repr__(self) -> str: return "BooleanDtype" @property def _is_boolean(self) -> bool: return True @property def _is_numeric(self) -> bool: return True def __from_arrow__( self, array: Union["pyarrow.Array", "pyarrow.ChunkedArray"] ) -> "BooleanArray": """ Construct BooleanArray from pyarrow Array/ChunkedArray. """ import pyarrow # noqa: F811 if isinstance(array, pyarrow.Array): chunks = [array] else: # pyarrow.ChunkedArray chunks = array.chunks results = [] for arr in chunks: # TODO should optimize this without going through object array bool_arr = BooleanArray._from_sequence(np.array(arr)) results.append(bool_arr) return BooleanArray._concat_same_type(results) def coerce_to_array( values, mask=None, copy: bool = False ) -> Tuple[np.ndarray, np.ndarray]: """ Coerce the input values array to numpy arrays with a mask. Parameters ---------- values : 1D list-like mask : bool 1D array, optional copy : bool, default False if True, copy the input Returns ------- tuple of (values, mask) """ if isinstance(values, BooleanArray): if mask is not None: raise ValueError("cannot pass mask for BooleanArray input") values, mask = values._data, values._mask if copy: values = values.copy() mask = mask.copy() return values, mask mask_values = None if isinstance(values, np.ndarray) and values.dtype == np.bool_: if copy: values = values.copy() elif isinstance(values, np.ndarray) and is_numeric_dtype(values.dtype): mask_values = isna(values) values_bool = np.zeros(len(values), dtype=bool) values_bool[~mask_values] = values[~mask_values].astype(bool) if not np.all( values_bool[~mask_values].astype(values.dtype) == values[~mask_values] ): raise TypeError("Need to pass bool-like values") values = values_bool else: values_object = np.asarray(values, dtype=object) inferred_dtype = lib.infer_dtype(values_object, skipna=True) integer_like = ("floating", "integer", "mixed-integer-float") if inferred_dtype not in ("boolean", "empty") + integer_like: raise TypeError("Need to pass bool-like values") mask_values = isna(values_object) values = np.zeros(len(values), dtype=bool) values[~mask_values] = values_object[~mask_values].astype(bool) # if the values were integer-like, validate it were actually 0/1's if inferred_dtype in integer_like: if not np.all( values[~mask_values].astype(float) == values_object[~mask_values].astype(float) ): raise TypeError("Need to pass bool-like values") if mask is None and mask_values is None: mask = np.zeros(len(values), dtype=bool) elif mask is None: mask = mask_values else: if isinstance(mask, np.ndarray) and mask.dtype == np.bool_: if mask_values is not None: mask = mask | mask_values else: if copy: mask = mask.copy() else: mask = np.array(mask, dtype=bool) if mask_values is not None: mask = mask | mask_values if not values.ndim == 1: raise ValueError("values must be a 1D list-like") if not mask.ndim == 1: raise ValueError("mask must be a 1D list-like") return values, mask class BooleanArray(BaseMaskedArray): """ Array of boolean (True/False) data with missing values. This is a pandas Extension array for boolean data, under the hood represented by 2 numpy arrays: a boolean array with the data and a boolean array with the mask (True indicating missing). BooleanArray implements Kleene logic (sometimes called three-value logic) for logical operations. See :ref:`boolean.kleene` for more. To construct an BooleanArray from generic array-like input, use :func:`pandas.array` specifying ``dtype="boolean"`` (see examples below). .. versionadded:: 1.0.0 .. warning:: BooleanArray is considered experimental. The implementation and parts of the API may change without warning. Parameters ---------- values : numpy.ndarray A 1-d boolean-dtype array with the data. mask : numpy.ndarray A 1-d boolean-dtype array indicating missing values (True indicates missing). copy : bool, default False Whether to copy the `values` and `mask` arrays. Attributes ---------- None Methods ------- None Returns ------- BooleanArray Examples -------- Create an BooleanArray with :func:`pandas.array`: >>> pd.array([True, False, None], dtype="boolean") <BooleanArray> [True, False, <NA>] Length: 3, dtype: boolean """ # The value used to fill '_data' to avoid upcasting _internal_fill_value = False def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): if not (isinstance(values, np.ndarray) and values.dtype == np.bool_): raise TypeError( "values should be boolean numpy array. Use " "the 'pd.array' function instead" ) self._dtype = BooleanDtype() super().__init__(values, mask, copy=copy) @property def dtype(self) -> BooleanDtype: return self._dtype @classmethod def _from_sequence(cls, scalars, dtype=None, copy: bool = False) -> "BooleanArray": if dtype: assert dtype == "boolean" values, mask = coerce_to_array(scalars, copy=copy) return BooleanArray(values, mask) @classmethod def _from_sequence_of_strings( cls, strings: List[str], dtype=None, copy: bool = False ) -> "BooleanArray": def map_string(s): if isna(s): return s elif s in ["True", "TRUE", "true", "1", "1.0"]: return True elif s in ["False", "FALSE", "false", "0", "0.0"]: return False else: raise ValueError(f"{s} cannot be cast to bool") scalars = [map_string(x) for x in strings] return cls._from_sequence(scalars, dtype, copy) _HANDLED_TYPES = (np.ndarray, numbers.Number, bool, np.bool_) def __array_ufunc__(self, ufunc, method: str, *inputs, **kwargs): # For BooleanArray inputs, we apply the ufunc to ._data # and mask the result. if method == "reduce": # Not clear how to handle missing values in reductions. Raise. raise NotImplementedError("The 'reduce' method is not supported.") out = kwargs.get("out", ()) for x in inputs + out: if not isinstance(x, self._HANDLED_TYPES + (BooleanArray,)): return NotImplemented # for binary ops, use our custom dunder methods result = ops.maybe_dispatch_ufunc_to_dunder_op( self, ufunc, method, *inputs, **kwargs ) if result is not NotImplemented: return result mask = np.zeros(len(self), dtype=bool) inputs2 = [] for x in inputs: if isinstance(x, BooleanArray): mask |= x._mask inputs2.append(x._data) else: inputs2.append(x) def reconstruct(x): # we don't worry about scalar `x` here, since we # raise for reduce up above. if is_bool_dtype(x.dtype): m = mask.copy() return BooleanArray(x, m) else: x[mask] = np.nan return x result = getattr(ufunc, method)(*inputs2, **kwargs) if isinstance(result, tuple): tuple(reconstruct(x) for x in result) else: return reconstruct(result) def _coerce_to_array(self, value) -> Tuple[np.ndarray, np.ndarray]: return coerce_to_array(value) def astype(self, dtype, copy: bool = True) -> ArrayLike: """ Cast to a NumPy array or ExtensionArray with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if not necessary. If False, a copy is made only if the old dtype does not match the new dtype. Returns ------- ndarray or ExtensionArray NumPy ndarray, BooleanArray or IntegerArray with 'dtype' for its dtype. Raises ------ TypeError if incompatible type with an BooleanDtype, equivalent of same_kind casting """ from pandas.core.arrays.string_ import StringDtype dtype = pandas_dtype(dtype) if isinstance(dtype, BooleanDtype): values, mask = coerce_to_array(self, copy=copy) return BooleanArray(values, mask, copy=False) elif isinstance(dtype, StringDtype): return dtype.construct_array_type()._from_sequence(self, copy=False) if is_bool_dtype(dtype): # astype_nansafe converts np.nan to True if self._hasna: raise ValueError("cannot convert float NaN to bool") else: return self._data.astype(dtype, copy=copy) if is_extension_array_dtype(dtype) and is_integer_dtype(dtype): from pandas.core.arrays import IntegerArray return IntegerArray( self._data.astype(dtype.numpy_dtype), self._mask.copy(), copy=False ) # for integer, error if there are missing values if is_integer_dtype(dtype): if self._hasna: raise ValueError("cannot convert NA to integer") # for float dtype, ensure we use np.nan before casting (numpy cannot # deal with pd.NA) na_value = self._na_value if is_float_dtype(dtype): na_value = np.nan # coerce return self.to_numpy(dtype=dtype, na_value=na_value, copy=False) def _values_for_argsort(self) -> np.ndarray: """ Return values for sorting. Returns ------- ndarray The transformed values should maintain the ordering between values within the array. See Also -------- ExtensionArray.argsort """ data = self._data.copy() data[self._mask] = -1 return data def any(self, skipna: bool = True, **kwargs): """ Return whether any element is True. Returns False unless there is at least one element that is True. By default, NAs are skipped. If ``skipna=False`` is specified and missing values are present, similar :ref:`Kleene logic <boolean.kleene>` is used as for logical operations. Parameters ---------- skipna : bool, default True Exclude NA values. If the entire array is NA and `skipna` is True, then the result will be False, as for an empty array. If `skipna` is False, the result will still be True if there is at least one element that is True, otherwise NA will be returned if there are NA's present. **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- bool or :attr:`pandas.NA` See Also -------- numpy.any : Numpy version of this method. BooleanArray.all : Return whether all elements are True. Examples -------- The result indicates whether any element is True (and by default skips NAs): >>> pd.array([True, False, True]).any() True >>> pd.array([True, False, pd.NA]).any() True >>> pd.array([False, False, pd.NA]).any() False >>> pd.array([], dtype="boolean").any() False >>> pd.array([pd.NA], dtype="boolean").any() False With ``skipna=False``, the result can be NA if this is logically required (whether ``pd.NA`` is True or False influences the result): >>> pd.array([True, False, pd.NA]).any(skipna=False) True >>> pd.array([False, False, pd.NA]).any(skipna=False) <NA> """ kwargs.pop("axis", None) nv.validate_any((), kwargs) values = self._data.copy() np.putmask(values, self._mask, False) result = values.any() if skipna: return result else: if result or len(self) == 0 or not self._mask.any(): return result else: return self.dtype.na_value def all(self, skipna: bool = True, **kwargs): """ Return whether all elements are True. Returns True unless there is at least one element that is False. By default, NAs are skipped. If ``skipna=False`` is specified and missing values are present, similar :ref:`Kleene logic <boolean.kleene>` is used as for logical operations. Parameters ---------- skipna : bool, default True Exclude NA values. If the entire array is NA and `skipna` is True, then the result will be True, as for an empty array. If `skipna` is False, the result will still be False if there is at least one element that is False, otherwise NA will be returned if there are NA's present. **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- bool or :attr:`pandas.NA` See Also -------- numpy.all : Numpy version of this method. BooleanArray.any : Return whether any element is True. Examples -------- The result indicates whether any element is True (and by default skips NAs): >>> pd.array([True, True, pd.NA]).all() True >>> pd.array([True, False, pd.NA]).all() False >>> pd.array([], dtype="boolean").all() True >>> pd.array([pd.NA], dtype="boolean").all() True With ``skipna=False``, the result can be NA if this is logically required (whether ``pd.NA`` is True or False influences the result): >>> pd.array([True, True, pd.NA]).all(skipna=False) <NA> >>> pd.array([True, False, pd.NA]).all(skipna=False) False """ kwargs.pop("axis", None) nv.validate_all((), kwargs) values = self._data.copy() np.putmask(values, self._mask, True) result = values.all() if skipna: return result else: if not result or len(self) == 0 or not self._mask.any(): return result else: return self.dtype.na_value @classmethod def _create_logical_method(cls, op): def logical_method(self, other): if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): # Rely on pandas to unbox and dispatch to us. return NotImplemented assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"} other = lib.item_from_zerodim(other) other_is_booleanarray = isinstance(other, BooleanArray) other_is_scalar = lib.is_scalar(other) mask = None if other_is_booleanarray: other, mask = other._data, other._mask elif is_list_like(other): other = np.asarray(other, dtype="bool") if other.ndim > 1: raise NotImplementedError( "can only perform ops with 1-d structures" ) other, mask = coerce_to_array(other, copy=False) elif isinstance(other, np.bool_): other = other.item() if other_is_scalar and not (other is libmissing.NA or lib.is_bool(other)): raise TypeError( "'other' should be pandas.NA or a bool. " f"Got {type(other).__name__} instead." ) if not other_is_scalar and len(self) != len(other): raise ValueError("Lengths must match to compare") if op.__name__ in {"or_", "ror_"}: result, mask = ops.kleene_or(self._data, other, self._mask, mask) elif op.__name__ in {"and_", "rand_"}: result, mask = ops.kleene_and(self._data, other, self._mask, mask) elif op.__name__ in {"xor", "rxor"}: result, mask = ops.kleene_xor(self._data, other, self._mask, mask) return BooleanArray(result, mask) name = f"__{op.__name__}__" return set_function_name(logical_method, name, cls) @classmethod def _create_comparison_method(cls, op): def cmp_method(self, other): from pandas.arrays import IntegerArray if isinstance( other, (ABCDataFrame, ABCSeries, ABCIndexClass, IntegerArray) ): # Rely on pandas to unbox and dispatch to us. return NotImplemented other = lib.item_from_zerodim(other) mask = None if isinstance(other, BooleanArray): other, mask = other._data, other._mask elif is_list_like(other): other = np.asarray(other) if other.ndim > 1: raise NotImplementedError( "can only perform ops with 1-d structures" ) if len(self) != len(other): raise ValueError("Lengths must match to compare") if other is libmissing.NA: # numpy does not handle pd.NA well as "other" scalar (it returns # a scalar False instead of an array) result = np.zeros_like(self._data) mask = np.ones_like(self._data) else: # numpy will show a DeprecationWarning on invalid elementwise # comparisons, this will raise in the future with warnings.catch_warnings(): warnings.filterwarnings("ignore", "elementwise", FutureWarning) with np.errstate(all="ignore"): result = op(self._data, other) # nans propagate if mask is None: mask = self._mask.copy() else: mask = self._mask | mask return BooleanArray(result, mask, copy=False) name = f"__{op.__name__}" return set_function_name(cmp_method, name, cls) def _reduce(self, name: str, skipna: bool = True, **kwargs): if name in {"any", "all"}: return getattr(self, name)(skipna=skipna, **kwargs) return super()._reduce(name, skipna, **kwargs) def _maybe_mask_result(self, result, mask, other, op_name: str): """ Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str """ # if we have a float operand we are by-definition # a float result # or our op is a divide if (is_float_dtype(other) or is_float(other)) or ( op_name in ["rtruediv", "truediv"] ): result[mask] = np.nan return result if is_bool_dtype(result): return BooleanArray(result, mask, copy=False) elif is_integer_dtype(result): from pandas.core.arrays import IntegerArray return IntegerArray(result, mask, copy=False) else: result[mask] = np.nan return result @classmethod def _create_arithmetic_method(cls, op): op_name = op.__name__ def boolean_arithmetic_method(self, other): if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): # Rely on pandas to unbox and dispatch to us. return NotImplemented other = lib.item_from_zerodim(other) mask = None if isinstance(other, BooleanArray): other, mask = other._data, other._mask elif is_list_like(other): other = np.asarray(other) if other.ndim > 1: raise NotImplementedError( "can only perform ops with 1-d structures" ) if len(self) != len(other): raise ValueError("Lengths must match") # nans propagate if mask is None: mask = self._mask if other is libmissing.NA: mask |= True else: mask = self._mask | mask if other is libmissing.NA: # if other is NA, the result will be all NA and we can't run the # actual op, so we need to choose the resulting dtype manually if op_name in {"floordiv", "rfloordiv", "mod", "rmod", "pow", "rpow"}: dtype = "int8" else: dtype = "bool" result = np.zeros(len(self._data), dtype=dtype) else: with np.errstate(all="ignore"): result = op(self._data, other) # divmod returns a tuple if op_name == "divmod": div, mod = result return ( self._maybe_mask_result(div, mask, other, "floordiv"), self._maybe_mask_result(mod, mask, other, "mod"), ) return self._maybe_mask_result(result, mask, other, op_name) name = f"__{op_name}__" return set_function_name(boolean_arithmetic_method, name, cls) BooleanArray._add_logical_ops() BooleanArray._add_comparison_ops() BooleanArray._add_arithmetic_ops()
[ "1778029840@qq.com" ]
1778029840@qq.com
40830d2e202a0447d24f36b58b901c90eba955bd
d1e3399db6973d639082bd24865bc0df538c0d8d
/ricommender_backend/settings.py
a51b80864b9dc2f358ec683a497db12f165cc5bd
[ "MIT" ]
permissive
reeechart/ricommender
a0c505f8eab6b7c381a41b919d3f5c3da02f61a2
c5cdf1cb9db27b9fc4a2553aee2b705b9ad0b95a
refs/heads/master
2020-04-22T12:13:35.198868
2019-05-12T16:42:25
2019-05-12T16:42:25
170,365,307
0
0
null
null
null
null
UTF-8
Python
false
false
3,359
py
""" Django settings for ricommender_backend project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'ricommender_backend.authentication', 'ricommender_backend.musicstreamer', ] 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 = 'ricommender_backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', '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 = 'ricommender_backend.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': os.environ.get('DATABASE_NAME'), }, } # Password validation # https://docs.djangoproject.com/en/2.1/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', }, ] # Django REST Framework REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20, } # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
[ "ferdinandusrichard@yahoo.co.id" ]
ferdinandusrichard@yahoo.co.id
b1cbde3a104f2e0b81d5ab63350c31dd2307980a
0a4432a13600e025937af3b2554ae048321a50bb
/sphinx/conf.py
e717ad87e5ed58f5acf5bbcd3588642b18e4451a
[ "Apache-2.0" ]
permissive
PourroyJean/ProgrammingNote
343c6a7fa3324b85cb7ed88e1bb794599d645c80
33fc7e64b3e5f44d1acde266df280f944d56674b
refs/heads/master
2023-01-08T17:52:39.833582
2020-06-09T08:09:08
2020-06-09T08:09:08
87,910,140
2
0
Apache-2.0
2022-12-27T15:01:06
2017-04-11T08:35:30
Jupyter Notebook
UTF-8
Python
false
false
4,880
py
# -*- coding: utf-8 -*- # # Notes Jean documentation build configuration file, created by # sphinx-quickstart on Fri May 12 14:54:18 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinxjp.themes.revealjs'] html_theme = 'revealjs' html_use_index = False # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ['.txt', '.md'] # The master toctree document. master_doc = 'index' # General information about the project. project = u'Notes Jean' copyright = u'2017, Jean Pourroy' author = u'Jean Pourroy' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'1' # The full version, including alpha/beta/rc tags. release = u'1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'fr' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'NotesJeandoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'NotesJean.tex', u'Notes Jean Documentation', u'Jean Pourroy', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'notesjean', u'Notes Jean Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'NotesJean', u'Notes Jean Documentation', author, 'NotesJean', 'One line description of project.', 'Miscellaneous'), ] source_parsers = { '.md': 'recommonmark.parser.CommonMarkParser', }
[ "jean@Nano-ubuntu-VM.ielbyy3bjwuuredtcfjnooi3gd.ax.internal.cloudapp.net" ]
jean@Nano-ubuntu-VM.ielbyy3bjwuuredtcfjnooi3gd.ax.internal.cloudapp.net
40d836471602038f8e490438807b48014491d9e2
df97d5b25d40b54e0714ed9c0a6dd7a579011e2e
/mikadocms/flikr_grabber.py
966050a532ec3be0269d2f1bc60375d21d2ae39b
[]
no_license
mikadosoftware/mikadoCMS
90ac1910b06f32bc3e808d1df656ba38a30e781c
7bb1ca4f66b74d4529a601540e1bf469f44d3b01
refs/heads/master
2021-01-17T00:20:34.489198
2018-06-13T15:27:53
2018-06-13T15:27:53
8,103,422
0
0
null
2013-05-03T23:07:59
2013-02-08T23:27:27
JavaScript
UTF-8
Python
false
false
2,740
py
#!/usr/bin/env python #! -*- coding: utf-8 -*- ### Copyright Paul Brian 2013 # This program is licensed, without under the terms of the # GNU General Public License version 2 (or later). Please see # LICENSE.txt for details ### """ :author: paul@mikadosoftware.com <Paul Brian> Flikr.com provides a useful outlet for using photographs on a website with minimal cost, and importantly, fuss. 1. visit http://www.flickr.com/search/advanced/ Search for a photo (by tag / text) but click "creative commons" and "commercial" use. 2. Find the right photo URL 3. run ``python flickr_grabber.py <URL>`` 4. I will grab the page and make a best guess as to the original photo URL 5. """ import requests from bs4 import BeautifulSoup import sys from bookmaker import lib import conf from optparse import OptionParser import logging import webbrowser import urllib import os class myError(Exception): pass ######### PHOTO_STORE = "./photos" testurl = "http://www.flickr.com/photos/comedynose/4230176889/" def extract_photo_url(url): r = requests.get(url) soup = BeautifulSoup(r.text) likelicandidate = soup.find(property='og:image') resultstr = """ From page %s We have likely candidate of %s or these: """ resultstr = resultstr % (url, str(likelicandidate)) for imgtag in soup.find_all("img"): resultstr += str(imgtag) return (likelicandidate, resultstr) def get_photo(url): """ """ tgt = os.path.join(PHOTO_STORE, os.path.basename(url)) urllib.urlretrieve(url, tgt) ######### def parse_args(): parser = OptionParser() parser.add_option("--config", dest="confpath", help="path to ini file") parser.add_option("--flikrpage", dest="flikrpage", help="url to embedded photo") parser.add_option("--flikrphoto", dest="flikrphoto", help="url to stadnalone photo (mutually xlusive with glikrpage") (options, args) = parser.parse_args() return (options, args) def main(opts, args): """ """ if opts.confpath: confd = conf.get_config(opts.confpath) lgr.debug(pprint.pformat(confd)) else: confd = {} if opts.flikrpage: likelicandidate, resultstr = extract_photo_url(opts.flikrpage) print likelicandidate print resultstr if opts.flikrphoto: get_photo(opts.flikrphoto) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) opts, args = parse_args() try: main(opts, args) except Exception, e: print "We can trap a lot up here" raise e
[ "paul@mikadosoftware.com" ]
paul@mikadosoftware.com
5dfb79becde51feb01c67400ff548446d6963775
0cb38adedbe3a5192076de420e1aa0fd10ae3311
/return_merchandise_authorizations/admin.py
213dea63a59221b56ba699e6a457f59ff5076d67
[]
no_license
fogcitymarathoner/rma
73ada816b98f068b6c00b2e1fcf39461259453fa
133d6026f99820d0702f0578b8a3b4574671f888
refs/heads/master
2021-01-11T00:32:47.797673
2016-10-10T18:34:54
2016-10-10T18:35:11
70,516,821
0
0
null
null
null
null
UTF-8
Python
false
false
756
py
from django.contrib import admin from return_merchandise_authorizations.models import Rma from return_merchandise_authorizations.models import Item from return_merchandise_authorizations.models import RmaAttachment class ItemInline(admin.TabularInline): model = Item class AttachInline(admin.TabularInline): model = RmaAttachment class RmaAdmin(admin.ModelAdmin): list_display = ('date', 'customer', 'case_number', 'reference_number', 'address') search_fields = ('case_number', 'reference_number', 'address', 'issue') inlines = [ ItemInline, AttachInline ] # admin.site.register(Rma, RmaAdmin) class ItemAdmin(admin.ModelAdmin): list_display = ('note', 'quantity') # admin.site.register(Item, ItemAdmin)
[ "marc@fogtest.com" ]
marc@fogtest.com
2e2f74124954a3985bfb08d9d40e0bc56bc5fff2
6e373b40393fb56be4437c37b9bfd218841333a8
/Level_6/Lecture_9/enroll/forms.py
a24e95e08208751aa12e95e489b7e6bdfa3638eb
[]
no_license
mahto4you/Django-Framework
6e56ac21fc76b6d0352f004a5969f9d4331defe4
ee38453d9eceea93e2c5f3cb6895eb0dce24dc2b
refs/heads/master
2023-01-22T01:39:21.734613
2020-12-04T03:01:17
2020-12-04T03:01:17
318,383,854
0
0
null
null
null
null
UTF-8
Python
false
false
659
py
from django.contrib.auth.models import User from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm class SignUpForm(UserCreationForm): password2 = forms.CharField(label='Confirm Password (again)', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] labels ={'email':'Email'} class EditUserProfileForm(UserChangeForm): password = None class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login', 'is_active'] labels = {'email':'Email'}
[ "mahto4you@gmail.com" ]
mahto4you@gmail.com
9e0d2453761f2903b984c6806664e6a9cfb0d256
acac3cf012920dc027ee4343a2e27f02338b342f
/pattern_matcher/dto/project_dto.py
0f5eca12d949e8f11e254de62cc59310aa4eb2a3
[]
no_license
HYUNMIN-KIM/flask_start
ff60592d27cdc510402b6b18f7c8642db929de44
8897e00dd29e5f7b3db5d1cec6d597a8edb2980e
refs/heads/master
2023-01-19T01:32:27.202743
2020-11-18T03:52:17
2020-11-18T03:52:17
291,651,373
0
0
null
null
null
null
UTF-8
Python
false
false
625
py
""" Project 전체에 대한 DTO 사이즈가 매우 큼 지식관리및학습서버와 대화작업서버간의 데이터 교환을 위해 사용됨 """ from pattern_matcher.dto import triggering_pattern_dto class ProjectDTO: def __int__(self): self.triggering_pattern_dto_list = triggering_pattern_dto() # getter @property def triggering_pattern_dto_list(self): return self.triggering_pattern_dto_list @triggering_pattern_dto_list.setter def triggering_pattern_dto_list(self, triggering_pattern_dto_list): self.triggering_pattern_dto_list = triggering_pattern_dto_list
[ "hogay88@wisenut.co.kr" ]
hogay88@wisenut.co.kr
ce174f06a5f69d56fb0614a1766754e87ea39d0d
0a983eebf91ad9a4342c8be92e1223b5d6ac28e1
/setup.py
13acd1717a2d8232655e0886d603d21d4dc7db71
[ "MIT" ]
permissive
davidkwast/db_tools
7bb1c6eeb01be81863e33edc38c60df8b31785b9
6881a3ce1d5bfb8634e01fc797d5e1dec6cd4891
refs/heads/master
2020-03-26T06:03:43.874788
2018-09-04T23:16:18
2018-09-04T23:16:18
144,587,472
0
0
null
null
null
null
UTF-8
Python
false
false
306
py
from setuptools import setup setup(name='db_tools', version='0.0', description='Python database tools', url='https://github.com/davidkwast/db_tools', author='David Kwast', author_email='david@kwast.me', license='MIT', packages=['db_tools'], zip_safe=False)
[ "david@kwast.me" ]
david@kwast.me
9265eec49a0e583e02e5cb8418f517c93695b206
be25988b4b92e16144315b3f3a45bb31c9036d87
/FinalProject.py
a4cc0cff617ba3e9e95bdafd188cff1566c19015
[]
no_license
cormag128/Python_Checkers
c658cd3ce9bbc03e770df6faed5ec1acb83326e1
4068b25a54d195a223c7bf73dfc4d4e18ac6c1cb
refs/heads/master
2021-01-19T21:23:50.391239
2017-05-03T00:58:52
2017-05-03T00:58:52
88,652,979
1
0
null
2017-04-30T19:49:40
2017-04-18T17:38:32
Python
UTF-8
Python
false
false
6,292
py
# Final Project: Checkers AI # Written by Thomas Walters and Trevor Jenkins # The purpose of this project is to demonstrate a complex state-based # program using heuristic programming to create a Checkers AI capable of # beating a human in checkershttps://askubuntu.com/questions/827005/how-to-install-eric-6-on-ubuntu-16-04https://askubuntu.com/questions/827005/how-to-install-eric-6-on-ubuntu-16-04https://askubuntu.com/questions/827005/how-to-install-eric-6-on-ubuntu-16-04. # Import random module for use later in program. import random # Class to output different errors that could be encountered during game. class Errors: NotValid = "The space entered is not a valid move." ShortMove = "Move must start at current position and finish at another square." WrongPiece = "Player must move their own piece." OccupiedSpace = "Player must move to an empty space." MoveTooLong = "Player must move exactly two spaces." BackwardMove = "Only king can move backward." MustJump = ("Player must jump opponent in this move, and must do multiple jumps" "if they are possible.") KingPiece = "Move terminates immediately if piece enters king's row." JumpMove = "If a move starts with a jump, only jumps can be performed." InvalidCapture = "Player can only capture opponent's pieces." InvalidMove = "Please move to an adjacent empty space, or jump the opponent." # Class to populate and print board. class Board(): board = [" " * 8 for i in range(8)] error = Errors def __init__(self, width, height): self.width = width self.height = height def __repr__(self): print(self.board) #function to place pieces on the board, stri is the name of the pieces def placepieces(self, stri): #if we want to place white pieces but on bottom 3 rows, use letters array for distinguishing #checkers pieces wnum = 0; bnum = 0; letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m'] if stri == "W": i = self.height - 3 j = 0 while i < self.height: j = 0 while j < self.width: if i % 2 == 0: if j % 2 == 1: if wnum < 10: self.board[i][j] = "W%s" % letters[wnum] wnum += 1 else: self.board[i][j] = "W%s" % letters[wnum] wnum += 1 else: pass else: if j % 2 == 1: pass else: if wnum < 10: self.board[i][j] = "W%s" % letters[wnum] wnum += 1 else: self.board[i][j] = "W%s" % letters[wnum] wnum += 1 j += 1 i += 1 #else we want the black pieces, but on top 3 rows else: i = 0 j = 0 while i < 3: j = 0 while j < self.width: if i % 2 == 0: if j % 2 == 1: if bnum < 10: self.board[i][j] = "B%s" % letters[bnum] bnum += 1 else: self.board[i][j] = "B%s" % letters[bnum] bnum += 1 else: pass else: if j % 2 == 1: pass else: if bnum < 10: self.board[i][j] = "B%s" % letters[bnum] bnum += 1 else: self.board[i][j] = "B%s" % letters[bnum] bnum += 1 j += 1 i += 1 def setup(self): #slashes used as a placeholder for empty spaces self.board = [["//" for m in range(8)] for k in range(8)] # place white team checkers self.placepieces("W") #place black team checkers self.placepieces("B") #print the board itself out, also prints out piece names etc. def printboard(self): i = 0 while i < self.height: j = 0 print "---------------------------------------" while j < self.width: print "|%s|" % (self.board[i][j]), j += 1 print "" i += 1 print "---------------------------------------" def move(self,str,move): #find the location of the checker we are looking for, could be a function #that returns to a checkers class with wval, hval, and str for variables? i = 0 j = 0 wval = 0 hval = 0 while i < self.height: j = 0; while j < self.width: if self.board[i][j] == str: hval = i wval = j j += 1 i += 1 #white movement could be split into functions still needs checking for edges # needs to handle kings/queens, and no jump handling, jump function could # be made and replace the occupied space errors where a jump is possible if(str.startswith("W")): #moving up and to the right if move == 9: if self.board[hval - 1][wval + 1] == "//": self.board[hval - 1][wval + 1] = self.board[hval][wval] self.board[hval][wval] = "//" board.printboard() #error handling else: print ("%s") % (self.error.OccupiedSpace) # moving up and to the left elif move == 7: if self.board[hval - 1][wval - 1] == "//": self.board[hval - 1][wval - 1] = self.board[hval][wval] self.board[hval][wval] = "//" board.printboard() # error handling else: print ("%s") % (self.error.OccupiedSpace) # error handling for other moves elif move == 1: print ("%s") % (self.error.BackwardMove) elif move == 3: print ("%s") % (self.error.BackwardMove) else: print ("%s") % (self.error.InvalidMove) #black movement could be split into functions, still needs checking for edges # needs to handle kings/queens, and no jump handling, jump function could # be made and replace the occupied space errors where a jump is possible elif (str.startswith("B")): # moving down and to the left if move == 1: if self.board[hval + 1][wval - 1] == "//": self.board[hval + 1][wval - 1] = self.board[hval][wval] self.board[hval][wval] = "//" board.printboard() #error handling else: print ("%s") % (self.error.OccupiedSpace) # moving down and to the right elif move == 3: if self.board[hval + 1][wval + 1] == "//": self.board[hval + 1][wval + 1] = self.board[hval][wval] self.board[hval][wval] = "//" board.printboard() # error handling else: print ("%s") % (self.error.OccupiedSpace) # error handling elif move == 7: print ("%s") % (self.error.BackwardMove) elif move == 9: print ("%s") % (self.error.BackwardMove) else: print ("%s") % (self.error.InvalidMove) #start of main function area #build a board that is 8x8, place checkers and print it out board = Board(8, 8) board.setup() board.printboard()
[ "noreply@github.com" ]
cormag128.noreply@github.com
bb69649a492b5bb2e5ee249630dca2d8b04e8c78
8f1996c1b5a0211474c7fa287be7dc20a517f5f0
/batch/batch/cloud/driver.py
96349e4c4d578c9209d5ffabef4590256096a62d
[ "MIT" ]
permissive
johnc1231/hail
9568d6effe05e68dcc7bf398cb32df11bec061be
3dcaa0e31c297e8452ebfcbeda5db859cd3f6dc7
refs/heads/main
2022-04-27T10:51:09.554544
2022-02-08T20:05:49
2022-02-08T20:05:49
78,463,138
0
0
MIT
2022-03-01T15:55:25
2017-01-09T19:52:45
Python
UTF-8
Python
false
false
936
py
from hailtop import aiotools from gear import Database from gear.cloud_config import get_global_config from ..inst_coll_config import InstanceCollectionConfigs from ..driver.driver import CloudDriver from .azure.driver.driver import AzureDriver from .gcp.driver.driver import GCPDriver async def get_cloud_driver( app, db: Database, machine_name_prefix: str, namespace: str, inst_coll_configs: InstanceCollectionConfigs, credentials_file: str, task_manager: aiotools.BackgroundTaskManager, ) -> CloudDriver: cloud = get_global_config()['cloud'] if cloud == 'azure': return await AzureDriver.create( app, db, machine_name_prefix, namespace, inst_coll_configs, credentials_file, task_manager ) assert cloud == 'gcp', cloud return await GCPDriver.create( app, db, machine_name_prefix, namespace, inst_coll_configs, credentials_file, task_manager )
[ "noreply@github.com" ]
johnc1231.noreply@github.com
c9982973398a7bada2df68e8686fc6deee8ab7a5
3251eb404404da4f2cd49d7a77baf67c928453a2
/src/membership/migrations/0003_coordinator_coordinator_image.py
469ac79a801237f480cb16c68c332d19318926e5
[ "MIT" ]
permissive
gatortechuf/gatortechuf.com
6575abd26ce1382cfcb6255a28e1d202910c86ba
8d0ad5f0772a42113c41bf454e96c2fa2c22d1f3
refs/heads/master
2020-05-22T06:49:09.580887
2018-02-03T17:42:02
2018-02-03T17:42:02
61,415,657
2
0
MIT
2018-02-03T17:42:03
2016-06-18T03:47:11
Python
UTF-8
Python
false
false
489
py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-02-28 18:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('membership', '0002_leader_leader_image'), ] operations = [ migrations.AddField( model_name='coordinator', name='coordinator_image', field=models.ImageField(blank=True, upload_to='membership'), ), ]
[ "ryandsheppard95@gmail.com" ]
ryandsheppard95@gmail.com
7796231c8f937912e9ccd9dd1399da035526bee6
55c0254b9889235844ca2fcfa5b80e6aedeb4841
/Book_app/wsgi.py
ea116599419347d50d5b310f5c940541109e1334
[]
no_license
AKSHAY-KR99/book_project
a75761a40c544fe4ad38ebcdd01b9d524e5f8ea8
019b316ec97395ac080be86333d7902b7c590271
refs/heads/master
2023-05-30T05:09:12.888518
2021-06-15T11:03:47
2021-06-15T11:03:47
377,130,492
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
""" WSGI config for Book_app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Book_app.settings') application = get_wsgi_application()
[ "ashayakr4@gmail.com" ]
ashayakr4@gmail.com
2ffa30e97c07a6799d516290ff2c899a4253a39e
eff8f2e795566c7aad10e9e3e7b0ffcafcc19145
/Set_difference().py
727190aca895eb0eb82fe4954ad9530732eca9d6
[]
no_license
Siddu02june/HackerRank-Sets
b27aa2f3679a6f3324d4daa3c5dffe28f08ebed7
a5a3b56d1bfbdd8b58b2df246e397000deaddbf6
refs/heads/main
2023-05-31T08:10:31.756639
2021-06-14T09:24:10
2021-06-14T09:24:10
376,763,510
0
0
null
null
null
null
UTF-8
Python
false
false
269
py
#Set_difference() E = int(input()) English = list(input().split()[:E]) F = int(input()) French = list(input().split()[:F]) print(len(set(English)-set(French))) ''' Input (stdin) 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Your Output (stdout) 4 Expected Output 4 '''
[ "noreply@github.com" ]
Siddu02june.noreply@github.com
6249e0ffb60185954c5323d646f6ee5e4b97a4cc
2be8a9f06d4003d12c0a727fb83d284c31a53050
/HoudiniHotBox17.0/lib/PastFbx.py
a984bb3fb35778efa1d77ea747bb869b4f43016f
[]
no_license
LiuLiangFx/SmileHotBOX
7551d9578b2defe612950cb8e3bffdb85024cede
8bd8eac69b3c2a9824b9aa4488ca77789bea8d85
refs/heads/master
2021-01-01T10:22:26.959731
2020-02-09T03:16:32
2020-02-09T03:16:32
239,236,801
0
0
null
2020-02-09T02:47:18
2020-02-09T02:47:18
null
UTF-8
Python
false
false
3,133
py
import hou class PastFbx: def __init__(self): pass def checkNode(self,node, name,temp1 =0): for childrenNode in node.parent().children(): if childrenNode.name() == name: temp1 =childrenNode return temp1 def checkInput(self,qian,hou1,temp=0): if hou1.inputs() ==(): pass else: for node in hou1.inputs(): if node == qian: temp =hou1 else: temp =0 return temp def creatNode(self,node,temp ): for mergeName in temp: serachNode = self.checkNode(node, mergeName) if serachNode : houNode = self.checkInput(node, serachNode ) if houNode ==0: serachNode.setInput(100,node) node = serachNode else: node = houNode else: merge = node.createOutputNode("merge",mergeName) node = merge def run(self): plane = hou.ui.paneTabOfType(hou.paneTabType.NetworkEditor) pos = plane.selectPosition() pos1 = pos node = plane.currentNode() fl1=open('list.txt', 'r') a= len( fl1.readlines()) check = 0 fl1.close() for index in range(a): pos[0] +=1 try: null = node.createNode("object_merge") except: b = node.parent() null =b.createNode("object_merge") null.setPosition(pos) fl1=open('list.txt', 'r') path = fl1.readlines()[index][0:-1] allPath= path.split("++") null.parm("objpath1").set(allPath[0]) null.parm("xformtype").set("local") attNode = null.createOutputNode("attribcreate") attNode.parm("name1").set("shop_materialpath") attNode.parm("type1").set("index") attNode.parm("string1").set("/shop/"+ allPath[-1]) attNode.parm("class1").set("primitive") catchNode = attNode.createOutputNode("catche_tool_1.0.1") catchNode.bypass(1) currentNode =catchNode self.creatNode(currentNode,allPath[1:-1] ) comping =int((index*1.0/(a-1))*100 ) fl1.close() print "CreatNode for " + null.name()+","+" Comping: " + str(comping)+"%" print "\nCopy node success!!!!"
[ "change52092@yahoo.com" ]
change52092@yahoo.com
659788c034719b344f80307e0abf95f56aae99d2
d16f2636a1157fde2eda16064b89dc6299d6c1fa
/main.py
67691a8900c0347a4823718220af8a4e5fbfb262
[]
no_license
razer89/Calculator
a762dd200074c7bd143fe087bf3752b92777f5c1
cd2477c641f9f1ae08f72aea5f93bc5854dc240b
refs/heads/main
2023-07-04T04:09:32.166568
2021-08-10T13:36:09
2021-08-10T13:36:09
382,019,184
0
0
null
null
null
null
UTF-8
Python
false
false
318
py
num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) action = str(input("Choose action: Add(a), Sub(s), Mult(m) Div(d) ->")) print("The result is ",end="") if action == "a": print(num1+num2) elif action == "s": print(num1-num2) elif action == "m": print(num1*num2) else: print(num1/num2)
[ "49878506+razer89@users.noreply.github.com" ]
49878506+razer89@users.noreply.github.com
7e6dccde1c6ea2ba3cbd360b3009d30db942726a
b1e7481f8b5bf40c2547c95b1863e25b11b8ef78
/Kai/python/modules/JetMETLogic.py
9fdf533765af3ae52ed238853b1aaaeac74dfcea
[ "Apache-2.0" ]
permissive
NJManganelli/FourTopNAOD
3df39fd62c0546cdbb1886b23e35ebdc1d3598ad
c86181ae02b1933be59d563c94e76d39b83e0c52
refs/heads/master
2022-12-22T22:33:58.697162
2022-12-17T01:19:36
2022-12-17T01:19:36
143,607,743
1
1
Apache-2.0
2022-06-04T23:11:42
2018-08-05T11:40:42
Python
UTF-8
Python
false
false
48,234
py
from __future__ import division, print_function import ROOT import math from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection, Object from PhysicsTools.NanoAODTools.postprocessing.framework.eventloop import Module from PhysicsTools.NanoAODTools.postprocessing.tools import * #DeltaR, match collection methods from FourTopNAOD.Kai.tools.toolbox import * class JetMETLogic(Module): def __init__(self, passLevel, era="2017", subera=None, isData=True, weightMagnitude=1, fillHists=False, btagging=['DeepJet', 'M'], MET=[45, 50], HT=[450,500], ZWidth=15, jetPtVar = "pt_nom", jetMVar = "mass_nom", verbose=False, probEvt=None, mode="Flag", debug=False): # genEquivalentLuminosity=1, genXS=1, genNEvents=1, genSumWeights=1, era="2017", btagging=['DeepCSV','M'], lepPt=25, GenTop_LepSelection=None): """ Jet, MET, HT logic that performs lepton cleaning and jet selection. Optionally can do b-tagging, but mode without this requirement can be enabled/disabled passLevel is the level at which the module should trigger "True" to pass the event along to further modules. Available: 'all', 'baseline', 'selection' Era is a string with the year of data taking or corresponding MC sample ("2017", "2018") Subera is a string with the subera of data-taking, only for use in combination with isData=True and TriggerChannel ("B", "E", etc.) isData is a boolean for when it's a data sample, as these are handled differently (trigger exclusivity and tier selection) from Monte Carlo. TriggerChannel is a string with the trigger channel ("ElMu" for e-mu channel/dataset, regardless of which is higher pT, "El" for single-electron channel/dataset). fillHists is a boolean for filling histograms. Regarding data, internally there are 'tiers' associated with the trigger tuples. For MC, if the event fires any trigger from any tier, it should be accepted. For data, given that events can be duplicated across data streams ('SingleMuon' and 'MuonEG'), triggers are divided into tiers. The goal is to only select a data event from the highest available tier of triggers that it fires, and veto that event in appropriate data streams when it corresponds to a lower trigger selection. For example, let an event fire both a single muon trigger (tier 3) and a mu-mu trigger (tier 1), but not an e-mu trigger (tier 0). In the double muon dataset, the event is selected because it fired the tier 1 trigger in the list (and not the tier 0 triggers). In the single muon dataset, the event is veto'd, because it fired the tier 1 trigger as well as the tier 3. A different event that only fired the tier 3 trigger is appropriately picked up on the single muon dataset, and while it may exist in the double muon dataset, it will only be becasue of a trigger that we have not checked for, and so we must not have picked it up in that dataset""" self.passLevel = passLevel self.writeHistFile=True self.fillHists = fillHists if self.fillHists and not self.writeHistFile: self.writeHistFile=True self.verbose=verbose self.probEvt = probEvt self.isData = isData self.weightMagnitude = weightMagnitude self.btagging = btagging self.era = era if probEvt: #self.probEvt = probEvt print("Skipping events until event #{0:d} is found".format(probEvt)) self.verbose = True #Bits for status flag checking self.flagbits = {'isPrompt':0b000000000000001, 'isDecayedLeptonHadron':0b000000000000010, 'isTauDecayProduct':0b000000000000100, 'isPromptTauDecaypprProduct':0b000000000001000, 'isDirectTauDecayProduct':0b000000000010000, 'isDirectPromptTauDecayProduct':0b000000000100000, 'isDirectHadronDecayProduct':0b000000001000000, 'isHardProcess':0b000000010000000, 'fromHardProcess':0b000000100000000, 'isHardProcessTauDecayProduct':0b000001000000000, 'isDirectHardProcessTauDecayProduct':0b000010000000000, 'fromHardProcessBeforeFSR':0b000100000000000, 'isFirstCopy':0b001000000000000, 'isLastCopy':0b010000000000000, 'isLastCopyBeforeFSR':0b100000000000000 } #Bits for Event Selection Variables self.passbits = {'PV_minNDoF': 0b00000000000000000001, 'PV_maxAbsZ': 0b00000000000000000010, 'PV_maxRho': 0b00000000000000000100, 'MET_globalSuperTightHalo2016Filter': 0b00000000000000001000, 'MET_goodVertices': 0b00000000000000010000, 'MET_HBHENoiseFilter': 0b00000000000000100000, 'MET_HBHENoiseIsoFilter': 0b00000000000001000000, 'MET_EcalDeadCellTriggerPrimitiveFilter':0b00000000000010000000, 'MET_BadPFMuonFilter': 0b00000000000100000000, 'MET_ecalBadCalibFilterV2': 0b00000000001000000000, 'MET_pt': 0b00000000010000000000, 'unused1': 0b00000000100000000000, 'Lepton_ZWindow': 0b00000001000000000000, 'Jet_nJet25': 0b00000010000000000000, 'Jet_nJet20': 0b00000100000000000000, 'HT': 0b00001000000000000000, 'Jet_nBJet_2DCSV': 0b00010000000000000000, 'Jet_nBJet_2DJet': 0b00100000000000000000, 'unused2': 0b01000000000000000000, 'unused3': 0b10000000000000000000, } #bits for Object Selection Variables - Jets self.jetbits = {'lepClean': 0b000000001, 'maxEta': 0b000000010, 'jetID': 0b000000100, 'pt25': 0b000001000, 'pt20': 0b000010000, 'unused': 0b000100000, 'DCSV': 0b001000000, 'DJET': 0b010000000, 'BTag_WP': 0b100000000 } # Thresholds for Event and Jet levels self.jet_threshold_bits = {} self.jet_threshold_bits['baseline'] = self.jetbits['lepClean'] + self.jetbits['maxEta'] + self.jetbits['jetID'] + \ self.jetbits['pt20'] print("Baseline bits are {0:09b}".format(self.jet_threshold_bits['baseline'])) self.jet_threshold_bits['selection'] = self.jetbits['lepClean'] + self.jetbits['maxEta'] + self.jetbits['jetID'] + \ self.jetbits['pt20'] print("Selection bits are {0:09b}".format(self.jet_threshold_bits['selection'])) self.evt_threshold_bits = {} # self.evt_threshold_bits['baseline'] = 0b00001100011111111111 # self.evt_threshold_bits['selection'] = 0b00001100011111111111 self.evt_threshold_bits['baseline'] = self.passbits['PV_minNDoF'] + self.passbits['PV_maxAbsZ'] +\ self.passbits['PV_maxRho'] + self.passbits['MET_globalSuperTightHalo2016Filter'] +\ self.passbits['MET_goodVertices'] + self.passbits['MET_HBHENoiseFilter'] + \ self.passbits['MET_HBHENoiseIsoFilter'] + \ self.passbits['MET_EcalDeadCellTriggerPrimitiveFilter'] + \ self.passbits['MET_BadPFMuonFilter'] + self.passbits['MET_ecalBadCalibFilterV2'] + \ self.passbits['MET_pt'] + self.passbits['Jet_nJet20'] + self.passbits['HT'] self.evt_threshold_bits['selection'] = self.passbits['PV_minNDoF'] + self.passbits['PV_maxAbsZ'] +\ self.passbits['PV_maxRho'] + self.passbits['MET_globalSuperTightHalo2016Filter'] +\ self.passbits['MET_goodVertices'] + self.passbits['MET_HBHENoiseFilter'] + \ self.passbits['MET_HBHENoiseIsoFilter'] + \ self.passbits['MET_EcalDeadCellTriggerPrimitiveFilter'] + \ self.passbits['MET_BadPFMuonFilter'] + self.passbits['MET_ecalBadCalibFilterV2'] + \ self.passbits['MET_pt'] + self.passbits['Jet_nJet20'] + self.passbits['HT'] #flags for MET filters self.FlagsDict = {"2016" : { "isData" : ["globalSuperTightHalo2016Filter"], "Common" : ["goodVertices", "HBHENoiseFilter", "HBHENoiseIsoFilter", "EcalDeadCellTriggerPrimitiveFilter", "BadPFMuonFilter" ], "NotRecommended" : ["BadChargedCandidateFilter", "eeBadScFilter" ] }, "2017" : { "isData" : ["globalSuperTightHalo2016Filter"], "Common" : ["goodVertices", "HBHENoiseFilter", "HBHENoiseIsoFilter", "EcalDeadCellTriggerPrimitiveFilter", "BadPFMuonFilter", "ecalBadCalibFilterV2" ], "NotRecommended" : ["BadChargedCandidateFilter", "eeBadScFilter" ] }, "2018" : { "isData" : ["globalSuperTightHalo2016Filter"], "Common" : ["goodVertices", "HBHENoiseFilter", "HBHENoiseIsoFilter", "EcalDeadCellTriggerPrimitiveFilter", "BadPFMuonFilter", "ecalBadCalibFilterV2" ], "NotRecommended" : ["BadChargedCandidateFilter", "eeBadScFilter" ] } } self.Flags = self.FlagsDict[era] #Btagging dictionary #FIXMEFIXMEFIXME self.bTagWorkingPointDict = { '2016':{ 'DeepCSV':{ 'L': 0.2217, 'M': 0.6321, 'T': 0.8953, 'Var': 'btagDeepB' }, 'DeepJet':{ 'L': 0.0614, 'M': 0.3093, 'T': 0.7221, 'Var': 'btagDeepFlavB' } }, '2017':{ 'CSVv2':{ 'L': 0.5803, 'M': 0.8838, 'T': 0.9693, 'Var': 'btagCSVV2' }, 'DeepCSV':{ 'L': 0.1522, 'M': 0.4941, 'T': 0.8001, 'Var': 'btagDeepB' }, 'DeepJet':{ 'L': 0.0521, 'M': 0.3033, 'T': 0.7489, 'Var': 'btagDeepFlavB' } }, '2018':{ 'DeepCSV':{ 'L': 0.1241, 'M': 0.4184, 'T': 0.7527, 'Var': 'btagDeepB' }, 'DeepJet':{ 'L': 0.0494, 'M': 0.2770, 'T': 0.7264, 'Var': 'btagDeepFlavB' } } } #2016selection required !isFake(), nDegreesOfFreedom> 4 (strictly),|z| < 24 (in cm? fractions of acentimeter?), and rho =sqrt(PV.x**2 + PV.y**2)< 2 #Cuts are to use strictly less than and greater than, i.e. PV.ndof > minNDoF, not >= self.PVCutDict = { '2016':{ 'minNDoF': 4, 'maxAbsZ': 24.0, 'maxRho': 2 }, '2017':{ 'minNDoF': 4, 'maxAbsZ': 24.0, 'maxRho': 2 }, '2018':{ 'minNDoF': 4, 'maxAbsZ': 24.0, 'maxRho': 2 } } self.PVCut = self.PVCutDict[era] #Weight variations if self.isData: self.weightList = ["NONE"] else: # self.weightList = ["NONE", "EWo", "EWS", "PUo", "EP"] self.weightList = ["NOM"] #NOM will be XS weight * PU weight * L1Prefiring weight? No Lepton weights, yet #BTagging method, algorithm name, and chosen selection working point self.BTName = btagging[0] self.BTMeth = self.bTagWorkingPointDict[era][btagging[0]] self.BTWP = self.bTagWorkingPointDict[era][btagging[0]][btagging[1]] self.BTAlg = self.bTagWorkingPointDict[era][btagging[0]]["Var"] self.MET = MET self.HT = HT self.ZWidth = ZWidth # self.invertZWindow = invertZWindow # self.invertZWindowEarlyReturn = invertZWindowEarlyReturn self.jetPtVar = jetPtVar self.jetMVar = jetMVar self.mode = mode self.debug = debug if self.verbose: print("BTMeth " + str(self.BTMeth)) print("BTWP " + str(self.BTWP)) print("BTAlg " + str(self.BTAlg)) print("Minimum lepton Pt: " + str(self.lepPt)) print("Minimum MET[Baseline, Selection]: " + str(self.MET)) print("Minimum HT[Baseline, Selection]: " + str(self.HT)) print("Z Window Width for veto bit: " + str(self.ZWidth)) # print("Inverted Z window: " + str(self.invertZWindow)) # print("Inverted Z window early return: " + str(self.invertZWindowEarlyReturn)) #event counters self.counter = 0 self.BitsBins = 20 self.BitsMin = 0 self.BitsMax = 20 def beginJob(self, histFile=None,histDirName=None): if self.fillHists == False and self.writehistFile == False: Module.beginJob(self, None, None) else: if histFile == None or histDirName == None: raise RuntimeError("fillHists set to True, but no histFile or histDirName specified") ###Inherited from Module prevdir = ROOT.gDirectory self.histFile = histFile self.histFile.cd() self.dir = self.histFile.mkdir( histDirName + "_JetMETLogic") prevdir.cd() self.objs = [] # self.JetMETLogic_Freq = {} # self.JetMETLogic_Correl = {} self.JetMETLogic_FailBits = {} self.JetMETLogic_FailFirst = {} for lvl in ["baseline", "selection"]: # self.JetMETLogic_Freq[lvl] = ROOT.TH1D("JetMETLogic_Freq_{}".format(lvl), # "HLT Paths Fired and Vetoed at {} level (weightMagnitude={}); Type; Events".format(lvl, self.weightMagnitude), # 1, 0, 0) # self.JetMETLogic_Correl[lvl] = ROOT.TH2D("JetMETLogic_Correl_{}".format(lvl), # "Fired HLT Path Correlations at {} level (weightMagnitude={}); Path; Path ".format(lvl, self.weightMagnitude), # self.PathsBins, self.PathsMin, self.PathsMax, self.PathsBins, self.PathsMin, self.PathsMax) self.JetMETLogic_FailBits[lvl] = ROOT.TH1D("JetMETLogic_FailBits_{}".format(lvl), "Failed JetMETLogic selection (any bits) at {} level (weightMagnitude={}); Path; Least significant bit power".format(lvl, self.weightMagnitude), self.BitsBins, self.BitsMin, self.BitsMax) self.JetMETLogic_FailFirst[lvl] = ROOT.TH1D("JetMETLogic_FailFirst_{}".format(lvl), "Failed JetMETLogic selection (power of least significant bit) at {} level (weightMagnitude={}); Path; Least significant bit power".format(lvl, self.weightMagnitude), self.BitsBins, self.BitsMin, self.BitsMax) for lvl in ["baseline", "selection"]: # self.addObject(self.JetMETLogic_Freq[lvl]) # self.addObject(self.JetMETLogic_Correl[lvl]) self.addObject(self.JetMETLogic_FailBits[lvl]) self.addObject(self.JetMETLogic_FailFirst[lvl]) # #Initialize labels to keep consistent across all files (only for labeled histograms, since introduction of 'extra' events in the histo counters (despite 0 weight) # for lvl in ["baseline", "selection"]: # for bitPos in xrange(self.BitsMin, self.BitsMax): # # self.JetMETLogic_Correl[lvl].Fill(trig.trigger + " (T{})".format(trig.tier), trig.trigger + " (T{})".format(trig.tier), 0.0) # # self.JetMETLogic_FailBits[lvl].Fill(bitPos+1, 0, 0.0) # # self.JetMETLogic_FailFirst[lvl].Fill(bitPos+1, 0, 0.0) # # for cat in ["Vetoed", "Fired", "Neither"]: # # self.JetMETLogic_Freq[lvl].Fill(cat, 0.0) # def endJob(self): # if hasattr(self, 'objs') and self.objs != None: # prevdir = ROOT.gDirectory # self.dir.cd() # for obj in self.objs: # obj.Write() # prevdir.cd() # if hasattr(self, 'histFile') and self.histFile != None: # self.histFile.Close() def beginFile(self, inputFile, outputFile, inputTree, wrappedOutputTree): self.branchList = inputTree.GetListOfBranches() if "Jet_{0:s}".format(self.jetPtVar) not in self.branchList: print("Warning: expected branch Jet_{0:s} to be present, but it is not. If not added in a module preceding this one, there will be a crash.".format(self.jetPtVar)) if "Jet_{0:s}".format(self.jetMVar) not in self.branchList: print("Warning: expected branch Jet_{0:s} to be present, but it is not. If not added in a module preceding this one, there will be a crash.".format(self.jetMVar)) self.out = wrappedOutputTree self.varTuple = [('Jet_OSV_baseline', 'i', 'Passes JetMETLeptonLogic at baseline level', 'nJet'), ('Jet_OSV_selection', 'i', 'Passes JetMETLogic at selection level', 'nJet'), ('ESV_JetMETLogic_baseline', 'i', 'Passes JetMETLogic at event level baseline,'\ ' bits correspond to levels of baseline in JetMETLogic', None), ('ESV_JetMETLogic_nJet_baseline', 'i', 'Number of jets passing baseline requirements', None), ('ESV_JetMETLogic_HT_baseline', 'D', 'Scalar sum of selected jets\' Pt', None), ('ESV_JetMETLogic_H_baseline', 'D', 'Scalar sum of selected jets\' P', None), ('ESV_JetMETLogic_HT2M_baseline', 'D', 'Scalar sum of selected jets\' Pt except 2 highest b-tagged if they are medium or tight', None), ('ESV_JetMETLogic_H2M_baseline', 'D', 'Scalar sum of selected jets\' P except 2 highest b-tagged if they are medium or tight', None), ('ESV_JetMETLogic_HTb_baseline', 'D', 'Scalar sum of Pt for medium and tight b-tagged jets', None), ('ESV_JetMETLogic_HTH_baseline', 'D', 'Hadronic centrality, HT/H', None), ('ESV_JetMETLogic_HTRat_baseline', 'D', 'Ratio of Pt for two highest b-tagged jets to HT', None), ('ESV_JetMETLogic_dRbb_baseline', 'D', 'DeltaR between the two highest b-tagged jets', None), ('ESV_JetMETLogic_DiLepMass_baseline', 'D', 'Invariant mass of same-flavour leptons (0 default)', None), ('ESV_JetMETLogic_selection', 'i', 'Passes JetMETLogic at event level selection,'\ ' bits correspond to levels of selection in JetMETLogic', None), ('ESV_JetMETLogic_nJet_selection', 'i', 'Number of jets passing selection requirements', None), ('ESV_JetMETLogic_HT_selection', 'D', 'Scalar sum of selected jets\' Pt', None), ('ESV_JetMETLogic_H_selection', 'D', 'Scalar sum of selected jets\' P', None), ('ESV_JetMETLogic_HT2M_selection', 'D', 'Scalar sum of selected jets\' Pt except 2 highest b-tagged if they are medium or tight', None), ('ESV_JetMETLogic_H2M_selection', 'D', 'Scalar sum of selected jets\' P except 2 highest b-tagged if they are medium or tight', None), ('ESV_JetMETLogic_HTb_selection', 'D', 'Scalar sum of Pt for medium and tight b-tagged jets', None), ('ESV_JetMETLogic_HTH_selection', 'D', 'Hadronic centrality, HT/H', None), ('ESV_JetMETLogic_HTRat_selection', 'D', 'Ratio of Pt for two highest b-tagged jets to HT', None), ('ESV_JetMETLogic_dRbb_selection', 'D', 'DeltaR between the two highest b-tagged jets', None), ('ESV_JetMETLogic_DiLepMass_selection', 'D', 'Invariant mass of same-flavour leptons (0 default)', None), ] self.deprecated = [('ESV_JetMETLogic_nJet', 'I', 'Number of jets passing selection requirements', None), ('ESV_JetMETLogic_nJetBTL', 'I', 'Number of jets passing selection requirements and loose b-tagged', None), ('ESV_JetMETLogic_nJetBTM', 'I', 'Number of jets passing selection requirements and medium b-tagged', None), ('ESV_JetMETLogic_nJetBTT', 'I', 'Number of jets passing selection requirements and tight b-tagged', None), ] if self.mode == "Flag": if not self.out: raise RuntimeError("No Output file selected, cannot flag events for JetMETLogic module") else: for name, valType, valTitle, lVar in self.varTuple: self.out.branch("{}".format(name), valType, lenVar=lVar, title=valTitle) elif self.mode == "Pass" or self.mode == "Fail" or self.mode == "Plot": pass if self.isData: self.XSweight = self.dataWeightFunc elif "genWeight" not in self.branchList: self.XSweight = self.backupWeightFunc print("Warning in TriggerAndLeptonLogic: expected branch genWeight to be present, but it is not."\ "The weight magnitude indicated will be used, but the sign of the genWeight must be assumed positive!") else: self.XSweight = self.genWeightFunc def analyze(self, event): #called by the eventloop per-event """process event, return True (go to next module) or False (fail, go to next event)""" #Increment counter and skip events past the maxEventsToProcess, if larger than -1 self.counter +=1 # if -1 < self.maxEventsToProcess < self.counter: # return False # if self.probEvt: # if event.event != self.probEvt: # return False ############################################### ### Collections and Objects and isData check### ############################################### #Bits for passing different cuts in the event, make final decision at the end, the loop is going to be slow anyway, thanks to PostProcessor ESV_baseline = 0 ESV_selection = 0 PV = Object(event, "PV") otherPV = Collection(event, "OtherPV") SV = Collection(event, "SV") electrons = Collection(event, "Electron") muons = Collection(event, "Muon") taus = Collection(event, "Tau") jets = Collection(event, "Jet") # fatjets = Collection(event, "FatJet") # subjets = Collection(event, "SubJet") weight = self.XSweight(event) # * PU weight, L1Prefiring weight, etc. if not self.isData: generator = Object(event, "Generator") btagweight = Object(event, "btagWeight") #contains .CSVV2 and .DeepCSVB float weights if self.era == "2017": met = Object(event, "METFixEE2017") else: met = Object(event, "MET") HLT = Object(event, "HLT") Filters = Object(event, "Flag") #Set up dictionary for all the weights to be used. # theWeight = {} #Begin weight calculations. Some won't work properly with cutflow, so they'll be running weights # ["NONE", "EWo", "EWS", "PUo", "EP"] btagSFs = {} for jet in jets: pass # for WLweight in self.weightList: # if WLweight == "NONE": # theWeight[WLweight] = 1 # elif WLweight == "EWo": # theWeight[WLweight] = math.copysign(self.evtWeightBase, generator.weight) # elif WLweight == "EWS": # theWeight[WLweight] = math.copysign(self.evtWeightAlt, generator.weight) # elif WLweight == "GWo": # theWeight[weight] = generator.weight # elif weight == "PUo": # theWeight[weight] = event.puWeight #puWeightUp, puWeightDown # elif weight == "EP": # theWeight[weight] = math.copysign(self.evtWeightBase, generator.weight)*event.puWeight # else: # theWeight[weight] = -1 # self.cutflow[weight].Fill("> preselection", theWeight[weight]) ###################### ### Primary Vertex ### ###################### #Require ndof > minNDoF, |z| < maxAbsZ, and rho < maxRho # if PV.ndof <= self.PVCut['minNDoF'] or abs(PV.z) >= self.VPCut['maxAbsZ'] or math.sqrt(PV.x**2 + PV.y**2) >= self.PVCut['maxRho']: # return False if PV.ndof > self.PVCut['minNDoF']: ESV_baseline += self.passbits['PV_minNDoF'] ESV_selection += self.passbits['PV_minNDoF'] if abs(PV.z) < self.PVCut['maxAbsZ']: ESV_baseline += self.passbits['PV_maxAbsZ'] ESV_selection += self.passbits['PV_maxAbsZ'] if math.sqrt(PV.x**2 + PV.y**2) < self.PVCut['maxRho']: ESV_baseline += self.passbits['PV_maxRho'] ESV_selection += self.passbits['PV_maxRho'] ########### ### MET ### ########### #Check additional flag(s) solely for Data if self.isData: passFilters = getattr(Filters, self.Flags["isData"][0]) if passFilters: ESV_baseline += self.passbits['MET_globalSuperTightHalo2016Filter'] ESV_selection += self.passbits['MET_globalSuperTightHalo2016Filter'] else: #Default to true for MC ESV_baseline += self.passbits['MET_globalSuperTightHalo2016Filter'] ESV_selection += self.passbits['MET_globalSuperTightHalo2016Filter'] #Ensure MC and Data pass all recommended filters for 2017 and 2018 for fi, flag in enumerate(self.Flags["Common"]): passFilters = getattr(Filters, flag) if passFilters: ESV_baseline += self.passbits['MET_{}'.format(flag)] ESV_selection += self.passbits['MET_{}'.format(flag)] if met.pt >= self.MET[0]: #baseline level ESV_baseline += self.passbits['MET_pt'] if met.pt >= self.MET[1]: #selection level ESV_selection += self.passbits['MET_pt'] # for weight in self.weightList: # self.cutflow[weight].Fill("> MET > {0:d}".format(self.MET), theWeight[weight]) if not self.isData: pass # gens = Collection(event, "GenPart") # genjets = Collection(event, "GenJet") # genfatjets = Collection(event, "GenJetAK8") # gensubjets = Collection(event, "SubGenJetAK8") # genmet = Object(event, "GenMET") #These two are grabbed earlier # generator = Object(event, "Generator") #stored earlier for weights access # btagweight = Object(event, "btagWeight") #contains .CSVV2 and .DeepCSVB float weights #This doesn't exist yet # LHEReweightingWeight = Collection(event, "LHEReweightingWeight") #These might fail because some of the samples lack weights... axe them for now, check later when actually needed. # LHE = Object(event, "LHE") # PSWeights = Collection(event, "PSWeight") # LHEWeight = getattr(event, "LHEWeight_originalXWGTUP") # LHEScaleWeight = Collection(event, "LHEScaleWeight") # LHEPdfWeight = Collection(event, "LHEPdfWeight") #BIG Weights lesson learned: you cannot use Collection, and possibly, you cannot even assign the variable and iterate through it using indices or #pythonic methods. Thus, to ge the 3rd LHEScaleWeight, should use 3rdLHEScaleWeight = getattr(event, "LHEScaleWeight")[2] instead, indexing after acquis. muon_baseline = [] muon_selection = [] for idx, muon in enumerate(muons): if muon.OSV_baseline > 0: muon_baseline.append((idx, muon)) if muon.OSV_selection > 0: muon_selection.append((idx, muon)) electron_baseline = [] electron_selection = [] for idx, electron in enumerate(electrons): if electron.OSV_baseline > 0: electron_baseline.append((idx, electron)) if electron.OSV_selection > 0: electron_selection.append((idx, electron)) leptons_baseline = electron_baseline + muon_baseline leptons_selection = electron_selection + muon_selection if self.debug: if self.passLevel == 'baseline': if len(leptons_baseline) > 2: print("Mayday!") if leptons_baseline[0][1].charge * leptons_baseline[1][1].charge > 0: print("Charging up!") if self.passLevel == 'selection': if len(leptons_selection) > 2: print("Mayday!") if leptons_selection[0][1].charge * leptons_selection[1][1].charge > 0: print("Charging up!") #passbit if outside the Z window in same-flavor event or all in different-flavor event if (len(electron_baseline) > 1 or len(muon_baseline) > 1): DiLepMass_baseline = (leptons_baseline[0][1].p4() + leptons_baseline[1][1].p4()).M() if abs( DiLepMass_baseline - 91.0) > self.ZWidth: ESV_baseline += self.passbits['Lepton_ZWindow'] else: #opposite-flavor ESV_baseline += self.passbits['Lepton_ZWindow'] DiLepMass_baseline = -1 #Should see no difference in invariant mass except when a collection drops below length 1, given the TriggerAndLeptonLogic Module in LeptonLogic.py if (len(electron_selection) > 1 or len(muon_selection) > 1): DiLepMass_selection = (leptons_selection[0][1].p4() + leptons_selection[1][1].p4()).M() if abs( DiLepMass_selection - 91.0) > self.ZWidth: ESV_selection += self.passbits['Lepton_ZWindow'] else: #opposite-flavor ESV_selection += self.passbits['Lepton_ZWindow'] DiLepMass_selection = -1 ############ ### Jets ### ########### jetsToClean_selection = set([lep[1].jetIdx for lep in leptons_selection]) selJets_selection = [] selBTsortedJets_selection = [] jetbits_selection = [0]*len(jets) jetsToClean_baseline = set([lep[1].jetIdx for lep in leptons_baseline]) selJets_baseline = [] selBTsortedJets_baseline = [] jetbits_baseline = [0]*len(jets) selJets_bugged = [] for idx, jet in enumerate(jets): if idx not in jetsToClean_baseline: jetbits_baseline[idx] += self.jetbits['lepClean'] if abs(jet.eta) < 2.5: jetbits_baseline[idx] += self.jetbits['maxEta'] if jet.jetId >= 2: jetbits_baseline[idx] += self.jetbits['jetID'] if getattr(jet, self.jetPtVar) > 25: jetbits_baseline[idx] += self.jetbits['pt25'] if getattr(jet, self.jetPtVar) > 20: jetbits_baseline[idx] += self.jetbits['pt20'] if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepCSV']['Var']) > self.bTagWorkingPointDict[self.era]['DeepCSV']['L']: jetbits_baseline[idx] += self.jetbits['DCSV'] if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepJet']['Var']) > self.bTagWorkingPointDict[self.era]['DeepJet']['L']: jetbits_baseline[idx] += self.jetbits['DJET'] if getattr(jet, self.BTAlg) > self.BTWP: jetbits_baseline[idx] += self.jetbits['BTag_WP'] if (jetbits_baseline[idx] & self.jet_threshold_bits['baseline']) >= self.jet_threshold_bits['baseline']: selJets_baseline.append((idx, jet)) selBTsortedJets_baseline.append((idx, jet)) # #BTagging input disabled without highest bit! Use DeepJet Loose... # if jetbits_baseline[idx] >= 0b010010111: if idx not in jetsToClean_selection: jetbits_selection[idx] += self.jetbits['lepClean'] if abs(jet.eta) < 2.5: jetbits_selection[idx] += self.jetbits['maxEta'] if jet.jetId >= 2: #dropped to 2==Tight due to bug in 4==TightLepVeto ID regarding muon energy fractions jetbits_selection[idx] += self.jetbits['jetID'] if getattr(jet, self.jetPtVar) > 25: jetbits_selection[idx] += self.jetbits['pt25'] if getattr(jet, self.jetPtVar) > 20: jetbits_selection[idx] += self.jetbits['pt20'] if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepCSV']['Var']) > self.bTagWorkingPointDict[self.era]['DeepCSV']['M']: jetbits_selection[idx] += self.jetbits['DCSV'] if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepJet']['Var']) > self.bTagWorkingPointDict[self.era]['DeepJet']['M']: jetbits_selection[idx] += self.jetbits['DJET'] if getattr(jet, self.BTAlg) > self.BTWP: jetbits_selection[idx] += self.jetbits['BTag_WP'] if (jetbits_selection[idx] & self.jet_threshold_bits['selection']) >= self.jet_threshold_bits['selection']: selJets_selection.append((idx, jet)) selBTsortedJets_selection.append((idx, jet)) nJets_baseline = len(selJets_baseline) nJets_selection = len(selJets_selection) #BTagging algo used for sorting, still selBTsortedJets_baseline.sort(key=lambda j : getattr(j[1], self.BTAlg), reverse=True) selBTsortedJets_selection.sort(key=lambda j : getattr(j[1], self.BTAlg), reverse=True) #B-tagged jets # selBTLooseJets = [jetTup for jetTup in selBTsortedJets if getattr(jetTup[1], self.BTAlg) > self.BTMeth['L']] # selBTMediumJets = [jetTup for jetTup in selBTLooseJets if getattr(jetTup[1], self.BTAlg) > self.BTMeth['M']] # selBTTightJets = [jetTup for jetTup in selBTMediumJets if getattr(jetTup[1], self.BTAlg) > self.BTMeth['T']] # selBTJets = [jetTup for jetTup in selBTsortedJets if getattr(jetTup[1], self.BTAlg) > self.BTWP] # nJets = len(selJets) # nBTLoose = len(selBTLooseJets) # nBTMedium = len(selBTMediumJets) # nBTTight = len(selBTTightJets) # nBTSelected = len(selBTJets) nJets25_baseline = [bits for bits in jetbits_baseline if (bits & self.jetbits['pt25'] > 0)] nBJetsDeepCSV_baseline = [bits for bits in jetbits_baseline if (bits & self.jetbits['DCSV'] > 0)] nBJetsDeepJet_baseline = [bits for bits in jetbits_baseline if (bits & self.jetbits['DJET'] > 0)] #Just 3 jets in baseline if nJets_baseline > 2: ESV_baseline += self.passbits['Jet_nJet20'] if len(nJets25_baseline) > 2: ESV_baseline += self.passbits['Jet_nJet25'] #Require 2 loose tagged jets if len(nBJetsDeepCSV_baseline) > 1: ESV_baseline += self.passbits['Jet_nBJet_2DCSV'] if len(nBJetsDeepJet_baseline) > 1: ESV_baseline += self.passbits['Jet_nBJet_2DJet'] nJets25_selection = [bits for bits in jetbits_selection if (bits & self.jetbits['pt25'] > 0)] nBJetsDeepCSV_selection = [bits for bits in jetbits_selection if (bits & self.jetbits['DCSV'] > 0)] nBJetsDeepJet_selection = [bits for bits in jetbits_selection if (bits & self.jetbits['DJET'] > 0)] #4 jets in selection if nJets_selection > 3: ESV_selection += self.passbits['Jet_nJet20'] if len(nJets25_selection) > 3: ESV_selection += self.passbits['Jet_nJet25'] #Require 2 medium tagged jets if len(nBJetsDeepCSV_selection) > 1: ESV_selection += self.passbits['Jet_nBJet_2DCSV'] if len(nBJetsDeepJet_selection) > 1: ESV_selection += self.passbits['Jet_nBJet_2DJet'] #HT and other calculations HT_baseline = 0 H_baseline = 0 HT2M_baseline = 0 H2M_baseline = 0 HTb_baseline = 0 HTH_baseline = 0 HTRat_baseline = 0 dRbb_baseline = -1 for j, jet in selBTsortedJets_baseline: HT_baseline += getattr(jet, self.jetPtVar) jetP4_baseline = ROOT.TLorentzVector() jetP4_baseline.SetPtEtaPhiM(getattr(jet, self.jetPtVar), getattr(jet, "eta"), getattr(jet, "phi"), getattr(jet, self.jetMVar) ) H_baseline += jetP4_baseline.P() #Only use deepjet if j > 1 and len(nBJetsDeepJet_baseline) > 1: HT2M_baseline += getattr(jet, self.jetPtVar) H2M_baseline += jetP4_baseline.P() if jetbits_baseline[j] & self.jetbits['DJET']: HTb_baseline += getattr(jet, self.jetPtVar) if HT_baseline >= self.HT[0]: ESV_baseline += self.passbits['HT'] if len(selBTsortedJets_baseline) > 3: #redundant, but only so long as 4 jet cut is in place jet1_baseline = selBTsortedJets_baseline[0][1] jet2_baseline = selBTsortedJets_baseline[1][1] dRbb_baseline = deltaR(jet1_baseline, jet2_baseline) HTRat_baseline = (jet1_baseline.pt + jet2_baseline.pt)/HT_baseline HTH_baseline = HT_baseline/H_baseline else: dRbb_baseline = -1 HTRat_baseline = -0.1 HTH_baseline = -0.1 #HT and other calculations HT_selection = 0 H_selection = 0 HT2M_selection = 0 H2M_selection = 0 HTb_selection = 0 HTH_selection = 0 HTRat_selection = 0 dRbb_selection = -1 for j, jet in selBTsortedJets_selection: HT_selection += getattr(jet, self.jetPtVar) jetP4_selection = ROOT.TLorentzVector() jetP4_selection.SetPtEtaPhiM(getattr(jet, self.jetPtVar), getattr(jet, "eta"), getattr(jet, "phi"), getattr(jet, self.jetMVar) ) H_selection += jetP4_selection.P() #Only use deepjet if j > 1 and len(nBJetsDeepJet_selection) > 1: HT2M_selection += getattr(jet, self.jetPtVar) H2M_selection += jetP4_selection.P() if jetbits_selection[j] & self.jetbits['DJET']: HTb_selection += getattr(jet, self.jetPtVar) if HT_selection >= self.HT[1]: ESV_selection += self.passbits['HT'] if len(selBTsortedJets_selection) > 3: #redundant, but only so long as 4 jet cut is in place jet1_selection = selBTsortedJets_selection[0][1] jet2_selection = selBTsortedJets_selection[1][1] dRbb_selection = deltaR(jet1_selection, jet2_selection) HTRat_selection = (jet1_selection.pt + jet2_selection.pt)/HT_selection HTH_selection = HT_selection/H_selection else: dRbb_selection = -1 HTRat_selection = -0.1 HTH_selection = -0.1 #################################### ### Variables for branch filling ### #################################### branchVals = {} branchVals['Jet_OSV_baseline'] = jetbits_baseline branchVals['Jet_OSV_selection'] = jetbits_selection branchVals['ESV_JetMETLogic_baseline'] = ESV_baseline #Do a bit comparison at the end? branchVals['ESV_JetMETLogic_selection'] = ESV_selection #do bit comparison at the end, but maybe still keep bits around... branchVals['ESV_JetMETLogic_nJet_baseline'] = nJets_baseline branchVals['ESV_JetMETLogic_nJet_selection'] = nJets_selection # branchVals['ESV_JetMETLogic_nJetBTL'] = nBTLoose # branchVals['ESV_JetMETLogic_nJetBTM'] = nBTMedium # branchVals['ESV_JetMETLogic_nJetBTT'] = nBTTight branchVals['ESV_JetMETLogic_HT_baseline'] = HT_baseline branchVals['ESV_JetMETLogic_H_baseline'] = H_baseline branchVals['ESV_JetMETLogic_HT2M_baseline'] = HT2M_baseline branchVals['ESV_JetMETLogic_H2M_baseline'] = H2M_baseline branchVals['ESV_JetMETLogic_HTb_baseline'] = HTb_baseline branchVals['ESV_JetMETLogic_HTH_baseline'] = HTH_baseline branchVals['ESV_JetMETLogic_HTRat_baseline'] = HTRat_baseline branchVals['ESV_JetMETLogic_dRbb_baseline'] = dRbb_baseline branchVals['ESV_JetMETLogic_DiLepMass_baseline'] = DiLepMass_baseline branchVals['ESV_JetMETLogic_HT_selection'] = HT_selection branchVals['ESV_JetMETLogic_H_selection'] = H_selection branchVals['ESV_JetMETLogic_HT2M_selection'] = HT2M_selection branchVals['ESV_JetMETLogic_H2M_selection'] = H2M_selection branchVals['ESV_JetMETLogic_HTb_selection'] = HTb_selection branchVals['ESV_JetMETLogic_HTH_selection'] = HTH_selection branchVals['ESV_JetMETLogic_HTRat_selection'] = HTRat_selection branchVals['ESV_JetMETLogic_dRbb_selection'] = dRbb_selection branchVals['ESV_JetMETLogic_DiLepMass_selection'] = DiLepMass_selection #################################### ### Event pass values calculated ### #################################### passVals = {} passVals['ESV_JetMETLogic_pass_all'] = True passVals['ESV_JetMETLogic_pass_baseline'] = ( (branchVals['ESV_JetMETLogic_baseline'] & self.evt_threshold_bits['baseline']) >= self.evt_threshold_bits['baseline']) passVals['ESV_JetMETLogic_pass_selection'] = ( (branchVals['ESV_JetMETLogic_selection'] & self.evt_threshold_bits['selection']) >= self.evt_threshold_bits['selection']) ####################### ### Fill histograms ### ####################### if self.fillHists: for lvl in ["baseline", "selection"]: if passVals['ESV_JetMETLogic_pass_{}'.format(lvl)]: pass else: # self.addObject(self.JetMETLogic_Freq[lvl]) # self.addObject(self.JetMETLogic_Correl[lvl]) foundFirstFail = False for bitPos, bitVal in enumerate(self.passbits.values()): if (bitVal & self.evt_threshold_bits[lvl] == 0) or (bitVal & branchVals['ESV_JetMETLogic_{}'.format(lvl)] > 0): #First skip values that aren't set in the evt_threshold, we can't fail on them, then additionally skip values that are passed in regard to those thresholds, using the comparison with bits in ESV_JetMETLogic_{lvl} continue #This is triggered when we have a bit that is in the threshold and was not met by the event, so it's a failure self.JetMETLogic_FailBits[lvl].Fill(bitPos+1, weight) if not foundFirstFail: self.JetMETLogic_FailFirst[lvl].Fill(bitPos+1, weight) #And if we made it to this point, we skip filling any further bits in the second histo by flipping the flag below foundFirstFail = True ########################## ### Write out branches ### ########################## if self.out and self.mode == "Flag": for name, valType, valTitle, lVar in self.varTuple: self.out.fillBranch(name, branchVals[name]) return True elif self.mode == "PassFail": if passVals['ESV_JetMETLogic_pass_{}'.format(self.passLevel)]: return True else: return False elif self.mode == "Plot": #Do something? #Do pass through if plotting, make no assumptions about what should be done with the event return True else: raise NotImplementedError("No method in place for JetMETLogic module in mode '{0}'".format(self.mode)) def genWeightFunc(self, event): #Default value is currently useless, since the tree reader array tool raises an exception anyway return math.copysign(self.weightMagnitude, getattr(event, "genWeight", 1)) def backupWeightFunc(self, event): return self.weightMagnitude def dataWeightFunc(self, event): return 1
[ "nmang001@ucr.edu" ]
nmang001@ucr.edu
d86790151df1e4863c98a6064062d24f7876ecb4
192cc298bc78889873fc932041c543bdc7b54bbb
/Cashier program.py
05d4371d74c7fd8262e8a02db5d9de3ddfc59112
[]
no_license
winter4w/Cashier-Program
01af06ccbd9d06fa509861e9a57094ad8ed100d6
8126ae412d7de21e95a415b5242508cb6d9df126
refs/heads/master
2020-09-22T16:41:06.845507
2019-12-02T06:59:42
2019-12-02T06:59:42
225,275,559
1
0
null
null
null
null
UTF-8
Python
false
false
2,397
py
import os import time import sys import math class Cashier(): def getDollars(self, a): dol = int(math.floor(a)) return dol def getQuarters(self, a): qua = int(math.floor(a / .25)) return qua def getDimes(self, a): dim = int(math.floor(a / .10)) return dim def getNickels(self, a): nic = int(math.floor(a / .05)) return nic def getPennies(self, a): pen = int(a / .01 +.1) return pen def newChange(self, a, coin_value , numberofcoins): return a - coin_value * numberofcoins myChange = Cashier() while True: print("") print("Enter the amount due in dollars and cents: ") amountDue = float(raw_input("$")) print("") amountReceived = float(raw_input("Enter the amount received: $")) print("") change = amountReceived - amountDue if amountDue > amountReceived: print("The customer has payed less than the cost") else: dolSolve = myChange.getDollars(change) change = myChange.newChange(change, 1, dolSolve) quaSolve = myChange.getQuarters(change) change = myChange.newChange(change, .25, quaSolve) dimSolve = myChange.getDimes(change) change = myChange.newChange(change, .10, dimSolve) nicSolve = myChange.getNickels(change) change = myChange.newChange(change, .05, nicSolve) penSolve = myChange.getPennies(change) print("Give the customer") print(str(dolSolve) + " Dollars") print(str(quaSolve) + " Quarters") print(str(dimSolve) + " Dimes") print(str(nicSolve) + " Nickels") print(str(penSolve) + " Pennies") print("") choiceQuit = raw_input ("If you will like to quit this program type 'quit' otherwise press enter:") os.system('cls') if choiceQuit == "quit": break else: True os.system('cls') print("The Program is now closeing!") print ("5") time.sleep(1) os.system('cls') print("The Program is now closeing!") print ("4") time.sleep(1) os.system('cls') print("The Program is now closeing!") print ("3") time.sleep(1) os.system('cls') print("The Program is now closeing!") print ("2") time.sleep(1) os.system('cls') print("The Program is now closeing!") print ("1") sys.exit()
[ "winter4w@users.noreply.github.com" ]
winter4w@users.noreply.github.com
abb8c70131d77c3c5abbae2840f52ba202b21851
fb56624f35821c0714b516c30831953da8f8d131
/run_fm_exp/scripts/select_params_ps.py
6067d585576b36567a88aa013e419cab74d70423
[]
no_license
jyhsia5174/pos-bias-exp-code
b27e31f6604420afae4aa4f2c9e6161ae7705bc4
913a00e6707482fd2122ec2c957e0dc8ebc3e7cc
refs/heads/master
2022-12-26T20:09:50.893942
2020-10-05T07:23:04
2020-10-05T07:23:04
222,909,534
1
0
null
null
null
null
UTF-8
Python
false
false
1,266
py
import os, sys root = sys.argv[1] flag = 1 if sys.argv[2] == 'auc' else 0 log_paths = [os.path.join(root, f) for f in os.listdir(root) if f.endswith('log')] records = {} for lp in log_paths: records[lp] = [0., 1000., 0.] # iter, min_logloss, max_auc with open(lp) as f: for i, line in enumerate(f): if i < 2: continue line = line.strip().split(' ') line = [s for s in line if s != ''] iter_num = float(line[0]) logloss = float(line[-2]) auc = float(line[-1]) if flag: if auc > records[lp][-1]: records[lp][0] = iter_num records[lp][1] = logloss records[lp][2] = auc else: if logloss < records[lp][1]: records[lp][0] = iter_num records[lp][1] = logloss records[lp][2] = auc if flag: params = sorted(records.items(), key=lambda x: x[-1][-1], reverse=flag)[0] else: params = sorted(records.items(), key=lambda x: x[-1][-2], reverse=flag)[0] print(params[0].split('/')[-1].split('.')[0], params[0].split('/')[-1].split('.')[2], int(params[1][0]), params[1][1], params[1][2],)
[ "d08944012@ntu.edu.tw" ]
d08944012@ntu.edu.tw
7e41be08a3a77a30cf7becf9259474bda1cdf940
6bde544edbda4291b8fd10533e3ec0cca4855a1f
/problem_2.py
ac9fd9e6bef2503460e546c4ca2608d9b641bf76
[]
no_license
ekdeguzm/project_euler_problem_2
5d2ba3806a1679e188eee293ada334e53f5175bc
6ba89ca7b181236d4c916bd31aeedbb2ceb8665a
refs/heads/main
2023-08-24T23:50:26.581516
2021-09-29T06:57:09
2021-09-29T06:57:09
411,562,145
0
0
null
null
null
null
UTF-8
Python
false
false
680
py
# Probem 2 of Project Euler # Python 3.9.5 # Even Fibonacci numbers # Create Fibonacci list and even Fibonacci list fib_list = [] even_fib_list = [] # Create Fibonacci sequence def fibonacci(n): a, b = 0, 1 for x in range(1, n): a, b = b, a + b return b for i in range(1, 34): fib_list.append(fibonacci(i)) # Print Fibonacci seq no more than 4,000,000 print(fib_list) # Get the even values from fib_list and add it it into the even list for value in fib_list: if value % 2 == 0: even_fib_list.append(value) else: None print("Updated list", even_fib_list) # Add values from even_fib_list together print(sum(even_fib_list))
[ "noreply@github.com" ]
ekdeguzm.noreply@github.com
50b929b62405be6ed8aacd6a49a420bd9ba63219
23ac56d6e024a69ae9f6f9e471ddefd71c9f0243
/reverse_list.py
3ce059eb10cf84065d68099596ca3be2bda56c8f
[]
no_license
erenat77/data_structure_in_Python
c70538f2c510b5525b230f84f7b455a0524d7313
216b173ab27cbbd3440c783efbd671be47645457
refs/heads/master
2020-08-11T10:16:48.352675
2019-11-05T01:03:07
2019-11-05T01:03:07
214,548,248
0
0
null
null
null
null
UTF-8
Python
false
false
169
py
l = [1,2,5,4,8,9,87,9,9,6,4,5] # recursive solution def rev(l): if len(l)<=1 : return l else: return [l[-1]] + rev(l[:-1]) rev(l) #easy solution print(l[::-1])
[ "noreply@github.com" ]
erenat77.noreply@github.com
d7e5e857f01d9f595c4e22550aeb3ed978f814ef
f7378f4038882c3de627a7d1262790f649f5e89b
/dataset.py
77564e166a38e75ee487cdf75078cb3d77632132
[]
no_license
edui/imogiz-mobileunet
176301a5238b0ab354b2fcf0a666c2820cbc165d
49757428b9fc320211b417450f2e883d9d444225
refs/heads/main
2023-08-10T18:32:55.037061
2021-09-27T22:39:39
2021-09-27T22:39:39
408,748,322
0
0
null
null
null
null
UTF-8
Python
false
false
4,710
py
import random import re from glob import glob import cv2 import numpy as np import pandas as pd from PIL import Image import torch from torch.utils.data import Dataset import torchvision from config import IMG_DIR def _mask_to_img(mask_file): img_file = re.sub('^{}/masks'.format(IMG_DIR), '{}/images'.format(IMG_DIR), mask_file) img_file = re.sub('\.ppm$', '.jpg', img_file) return img_file def _img_to_mask(img_file): mask_file = re.sub('^{}/images'.format(IMG_DIR), '{}/masks'.format(IMG_DIR), img_file) # mask_file = re.sub('\.jpg$', '.ppm', mask_file) return mask_file def get_img_files_eval(): mask_files = sorted(glob('{}/masks/*.jpg'.format(IMG_DIR))) return np.array([_mask_to_img(f) for f in mask_files]) def get_img_files(): mask_files = sorted(glob('{}/masks/*.jpg'.format(IMG_DIR))) # mask_files = mask_files[:10000] sorted_mask_files = [] # Sorting out for msk in mask_files: # Sort out black masks msk_img = cv2.imread(msk) if len(np.where(msk_img == 1)[0]) == 0: continue # Sort out night images img_path = re.sub('^{}/masks'.format(IMG_DIR), '{}/images'.format(IMG_DIR), msk) img = cv2.imread(img_path) gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) higher_img = gray_image[0:120, :] if np.average(higher_img) > 100: # Day image, so append sorted_mask_files.append(msk) # return np.array([_mask_to_img(f) for f in mask_files]) return np.array([_mask_to_img(f) for f in sorted_mask_files]) class MaskDataset(Dataset): def __init__(self, img_files, transform, mask_transform=None, mask_axis=0): self.img_files = img_files self.mask_files = [_img_to_mask(f) for f in img_files] self.transform = transform if mask_transform is None: self.mask_transform = transform else: self.mask_transform = mask_transform self.mask_axis = mask_axis def __getitem__(self, idx): img = cv2.imread(self.img_files[idx]) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) mask = cv2.imread(self.mask_files[idx]) mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) mask = mask[:, :, self.mask_axis] seed = random.randint(0, 2 ** 32) # Apply transform to img random.seed(seed) img = Image.fromarray(img) img = self.transform(img) # Apply same transform to mask random.seed(seed) mask = Image.fromarray(mask) mask = self.mask_transform(mask) return img, mask def __len__(self): return len(self.img_files) class MogizDataset(Dataset): def __init__(self, ds_dir, ds_name, transform, mask_transform=None, mask_axis=0): self.df = pd.read_csv(ds_dir + ds_name, header=None) self.ds_dir = ds_dir self.transform = transform if mask_transform is None: self.mask_transform = transform else: self.mask_transform = mask_transform self.mask_axis = mask_axis def __getitem__(self, idx): image_name = self.df.iloc[idx, 0] mask_name = self.df.iloc[idx, 1] joint_name = self.df.iloc[idx, 2] height = torch.from_numpy( np.array([self.df.iloc[idx, 3]/100])).type(torch.FloatTensor) weight = torch.from_numpy( np.array([self.df.iloc[idx, 4]/100])).type(torch.FloatTensor) img = cv2.imread(self.ds_dir + image_name) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) mask = cv2.imread(self.ds_dir + mask_name) mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) mask = mask[:, :, self.mask_axis] # For Heatmaps #joint = np.load(self.ds_dir + joint_name).astype('int64') #joint = torch.from_numpy(joint) joint = height # not used seed = random.randint(0, 2 ** 32) # Apply transform to img random.seed(seed) img = Image.fromarray(img) img = self.transform(img) # Apply same transform to mask random.seed(seed) mask = Image.fromarray(mask) mask = self.mask_transform(mask) # return img, mask, height return {'i': img, 'l': mask, 'j': joint, 'h': height, 'w': weight} def __len__(self): return len(self.df) if __name__ == '__main__': pass # # mask = cv2.imread('{}/masks/Aaron_Peirsol_0001.ppm'.format(IMG_DIR)) # mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) # mask = mask[:, :, 0] # print(mask.shape) # plt.imshow(mask) # plt.show()
[ "edui.bin@gmail.com" ]
edui.bin@gmail.com
8cfa0564a630a016ac91663a5dbcade279afd639
144b54b91cbd541421c12df1074920c1bd635780
/utils.py
71aca180b475fef8fb48cacb903d2616b5893e9b
[ "MIT" ]
permissive
jajcayn/re_hippocampal_model
777956b93476051202e10c908f419c69e9349c0e
5dc984cec0591d27ed6dedf8e8e2ddd8e07b20c7
refs/heads/main
2023-04-19T05:29:14.064024
2021-04-21T09:37:45
2021-04-21T09:37:45
353,683,773
0
0
null
null
null
null
UTF-8
Python
false
false
3,481
py
""" Helper functions """ import logging from functools import partial from multiprocessing import Pool, cpu_count import matplotlib import matplotlib.pyplot as plt from matplotlib.lines import Line2D from tqdm import tqdm def run_in_parallel( partial_function, iterable, workers=cpu_count(), length=None, assert_ordered=False, ): """ Wrapper for running functions in parallel with tqdm bar. :param partial_function: partial function to be evaluated :type partial_function: :class:`_functools.partial` :param iterable: iterable comprised of arguments to be fed to partial function :type iterable: iterable :param workers: number of workers to be used :type workers: int :param length: Length of the iterable / generator. :type length: int|None :param assert_ordered: whether to assert order of results same as the iterable (imap vs imap_unordered) :type assert_ordered: bool :return: list of values returned by partial function :rtype: list """ total = length if total is None: try: total = len(iterable) except (TypeError, AttributeError): pass # wrap method in order to get original exception from a worker process partial_function = partial(_worker_fn, fn=partial_function) pool = Pool(workers) imap_func = pool.imap_unordered if not assert_ordered else pool.imap results = [] for result in tqdm(imap_func(partial_function, iterable), total=total): results.append(result) pool.close() pool.join() return results def _worker_fn(item, fn): """ Wrapper for worker method in order to get original exception from a worker process and to log correct exception stacktrace. :param item: item from iterable :param fn: partial function to be evaluated :type fn: :class:`_functools.partial` """ try: return fn(item) except Exception as e: logging.exception(e) raise class AnchoredHScaleBar(matplotlib.offsetbox.AnchoredOffsetbox): """ Creates horizontal scale bar in the matplotlib figures. Taken from https://stackoverflow.com/a/43343934. """ def __init__( self, size=1, extent=0.03, label="", loc=2, ax=None, pad=0.6, borderpad=0.5, ppad=0, sep=4, txtsize=16, prop=None, frameon=False, linekw={}, **kwargs ): if not ax: ax = plt.gca() trans = ax.get_xaxis_transform() size_bar = matplotlib.offsetbox.AuxTransformBox(trans) line = Line2D([0, size], [0, 0], **linekw) vline1 = Line2D([0, 0], [-extent / 2.0, extent / 2.0], **linekw) vline2 = Line2D([size, size], [-extent / 2.0, extent / 2.0], **linekw) size_bar.add_artist(line) size_bar.add_artist(vline1) size_bar.add_artist(vline2) txt = matplotlib.offsetbox.TextArea( label, minimumdescent=False, textprops={"size": txtsize} ) self.vpac = matplotlib.offsetbox.VPacker( children=[size_bar, txt], align="center", pad=ppad, sep=sep ) matplotlib.offsetbox.AnchoredOffsetbox.__init__( self, loc, pad=pad, borderpad=borderpad, child=self.vpac, prop=prop, frameon=frameon, **kwargs )
[ "nikola.jajcay@gmail.com" ]
nikola.jajcay@gmail.com
d2d8d1a76517bf0cbfed79f32e7b7f96acb604a2
a7a8e79ba13962d792d9aa1ee758f095083044b9
/gened.py
6eedddca46433cccfb8e35171c9c33fc5f66edd9
[]
no_license
vannjo02/Gen_eds
96744091a8f08504fe68739ecee5e8b7b1b17b4a
5fda16f2531e38358fdfadadf890037c4ad56fe5
refs/heads/master
2021-01-20T09:55:02.222524
2017-05-04T19:15:36
2017-05-04T19:15:36
90,300,687
0
0
null
null
null
null
UTF-8
Python
false
false
2,804
py
from flask import Flask, render_template, request import psycopg2 from flask_bootstrap import Bootstrap import os app = Flask(__name__) Bootstrap(app) conn = psycopg2.connect(os.environ['DATABASE_URL']) print('READY') @app.route('/') def index(): reqlst = ["Human Expression—Primary Texts", "Intercultural", "Historical", "Natural World—Nonlab", "Religion", "Human Expression", "Skills", "Human Behavior", "Human Behavior—Social Science Methods", "Quantitative", "Natural World—Lab", "Biblical Studies", "Wellness"] cur=conn.cursor() cur.execute("select number, title, count(requirement.description) as count from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) group by number, title order by count desc limit 5") res=cur.fetchall() print(res) return render_template('index.html', reqs=reqlst, res = res) @app.route('/requirement/') def requirement(): reqs=tuple(request.args.getlist('option')) cur=conn.cursor() cur.execute("select number, title from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) where requirement.description in %s group by number, title having count(requirement.description) >= %s", (reqs, len(reqs))) res=cur.fetchall() print(res) return render_template('requirement.html', courses=res, reqs = reqs) @app.route('/course/<crs>') def course(crs): cur = conn.cursor() cur.execute("select requirement.description from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) where course.number = %s", (crs,)) res = cur.fetchall() print(res) cur.execute("select title, course.description from course where course.number = %s", (crs,)) info = cur.fetchall()[0] print(info) return render_template('course.html', course = res, info = info, crs = crs) @app.route('/search/') def search(): query = tuple(request.args.getlist('input'))[0].title() search= "%" + query + "%" cur = conn.cursor() cur.execute("select number, title from course where course.title like %s", (search,)) search = cur.fetchall() print("Results", search) fulfills = [] for course in search: cur.execute("select requirement.description from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) where course.number = %s", (course[0],)) tmp = [] for req in cur.fetchall(): tmp.append(req[0]) fulfills.append(tmp) print("Reqs list", fulfills) return render_template('search.html', search = search, lst = fulfills, query = query) if __name__ == '__main__': app.run(debug='True')
[ "vannjo02@luther.edu" ]
vannjo02@luther.edu
9ffedfdbb5aa841be3b526cd48ec2b1a4d37799e
459e0f34dfbc818763edf153152711a11c2efbe3
/pythonscript/billing.py
65cc9ddd17973536698c22abf0b14a204bd7a018
[]
no_license
tariqcoupa/experiments
15523c7f60edcb3078169fb9f407915f859ef91d
3323add34d66ebc76d91124c7358abd639d9317a
refs/heads/master
2021-04-05T23:52:21.718538
2018-03-03T12:31:49
2018-03-03T12:31:49
124,418,067
0
0
null
2018-03-08T16:26:12
2018-03-08T16:26:12
null
UTF-8
Python
false
false
566
py
#!/usr/bin/python import SoftLayer import json import sys client = SoftLayer.Client(username='prod.tariq', api_key='53c53cba25872849417fcc1794f9acdeb91c6680f597ddf76488aa4e4d999e51') object_mask = "mask[id]" object_mask2 = """mask[hostname,billingItem.nextInvoiceTotalRecurringAmount]""" user_info = client['Account'].getHardware(mask=object_mask) mgr = SoftLayer.HardwareManager(client) for json_dict in user_info: for key,value in json_dict.iteritems(): hardware_info = mgr.get_hardware(hardware_id=value,mask=object_mask2) print hardware_info
[ "tarsidd@gmail.com" ]
tarsidd@gmail.com
65e87e100e5ca37ed1bf10f7336709b79e1b9140
b558b4348ff88bb670bf1a318d3c22d48ebf5627
/src/manage.py
7325504ca062609d3ef47b1c19939d4ae8762ec9
[]
no_license
rnjane/Flight-Booking-API
540fe63d47a6ac622633b8560603ce34600857e2
05f974c1f6b3dafe18b7cdc417f11f314271625b
refs/heads/develop
2022-12-10T13:21:57.567096
2019-02-04T11:06:11
2019-02-04T11:06:11
162,910,819
0
0
null
2022-12-08T01:34:12
2018-12-23T17:26:58
Python
UTF-8
Python
false
false
546
py
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookingproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
[ "robert.njane@andela.com" ]
robert.njane@andela.com
0f6b34fbcc11d1d36e1186122b4196348d01de41
15d3a10db27128c06f84c30fa8d64b2e1c629fd9
/express/express/api_exception.py
50d8121033b83ac36e6070744f39d492bda13465
[]
no_license
yiyuhao/exp
7cba6650e3113ba05698f90a7baf75b680dd6435
866a90b2e6f0d113559b0674f514cdd56020f7d6
refs/heads/master
2020-03-19T20:20:04.799355
2018-07-15T14:55:24
2018-07-15T14:55:24
136,897,007
0
0
null
null
null
null
UTF-8
Python
false
false
431
py
# -*- coding: utf-8 -* from rest_framework.views import exception_handler def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = response.status_code return response
[ "yiyuhao@mixadx.com" ]
yiyuhao@mixadx.com
a3b8ebb9edc3184f04b98b58d25d2ad29b4d644c
3b21c2a5422dc2b900f65894849e7e2e765fc7cc
/CameraField.py
8e4d25c66f759a3b7ebfd2a2dfdccca52657da95
[]
no_license
mrbhjv/dft_python
2c519dcdb5100511376c35db63c0248628fb9b3e
480fffd81374f37f6a62c362fb551b2021772429
refs/heads/master
2020-04-24T09:04:28.412581
2011-07-21T12:23:47
2011-07-21T12:23:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,204
py
import naoqi from naoqi import ALProxy import numpy import DynamicField import math_tools class NaoCameraField(DynamicField.DynamicField): "Camera field" def __init__(self): "Constructor" DynamicField.DynamicField.__init__(self, dimension_bounds = [[40],[30],[15]]) self._vision_proxy = ALProxy("ALVideoDevice", "nao.ini.rub.de", 9559) self._gvm_name = "nao vision" self._gvm_name = self._vision_proxy.subscribe(self._gvm_name, 0, 12, 30) # switch off auto white balance self._vision_proxy.setParam(12, 0) # select the bottom camera self._vision_proxy.setParam(18, 1) self._name = "nao_camera_field" def __del__(self): self._gvm_name = self._vision_proxy.unsubscribe(self._gvm_name) def _step_computation(self): naoimage = self._vision_proxy.getImageRemote(self._gvm_name) hsv_image = numpy.fromstring(naoimage[6], dtype=numpy.uint8) hue = hsv_image[::3].reshape(120,160) saturation = hsv_image[1::3].reshape(120,160) hue = numpy.rot90(hue, 3) saturation = numpy.rot90(saturation, 3) sizes = self.get_input_dimension_sizes() max_activation_level = 5.0 hue = math_tools.linear_interpolation_2d_custom(hue, [sizes[0], sizes[1]]) saturation = math_tools.linear_interpolation_2d_custom(saturation, [sizes[0], sizes[1]]) hue = numpy.round(hue * ((sizes[2] - 1)/255.)).astype(numpy.int) saturation = saturation * (2 * max_activation_level / 255.) - max_activation_level for i in range(sizes[0]): for j in range(sizes[1]): color = hue[i][j] self._activation[i][j] = -max_activation_level self._activation[i][j][color] = saturation[i][j] self._activation[0,:,:] = -max_activation_level self._activation[sizes[0]-1,:,:] = -max_activation_level self._activation[:,0,:] = -max_activation_level self._activation[:,sizes[1]-1,:] = -max_activation_level self._output_buffer = self.compute_thresholded_activation(self._activation) class GaussCameraField(DynamicField.DynamicField): "Camera field" def __init__(self): "Constructor" DynamicField.DynamicField.__init__(self, dimension_bounds = [[40],[30],[15]]) self._activation += math_tools.gauss_3d([40,30,15], 9.0, [2.0,2.0,2.0], [10,20,0]) self._output_buffer = self.compute_thresholded_activation(self._activation) def _step_computation(self): pass class DummyCameraField(DynamicField.DynamicField): "Camera field" def __init__(self): "Constructor" DynamicField.DynamicField.__init__(self, dimension_bounds = [[40],[30],[15]]) camera_field_file = open("snapshots/camera_field.txt", 'r') activation = numpy.fromfile(camera_field_file, sep=', ') camera_field_file.close() activation = activation.reshape(160,120,50) self._activation = math_tools.linear_interpolation_nd(activation, [40, 30, 15]) self._output_buffer = self.compute_thresholded_activation(self._activation) def _step_computation(self): pass
[ "mathis.richter@ini.rub.de" ]
mathis.richter@ini.rub.de
d9c4b8a7de6dbd3755b12d629a970ee4b0778798
49197a748adea1618a2cece7a1ae057006da090c
/jgodwin/micro/micro.py
f1132e04bc3d6e7e46ac6817121583f752dcc324
[]
no_license
psava/cwp12
0bbb1f213c66737509280fc4b0ac5c53b52d017a
3f47c1bf358caa5ebe608ab88fc12b85fd489220
refs/heads/master
2021-01-10T21:24:57.572992
2012-10-10T15:52:18
2012-10-10T15:52:18
2,213,082
3
2
null
null
null
null
UTF-8
Python
false
false
17,263
py
from rsf.cluster import * import random,fdmod def getpar(): par = { ############################### # Model/Image dimensions ############################### #'nx':501, 'ox':0, 'dx':0.002, 'lx':'x', 'ux':'km', #'ny':151, 'oy':0, 'dy':0.002, 'ly':'y', 'uy':'km', #'nz':351, 'oz':0, 'dz':0.002, 'lz':'z', 'uz':'km', 'nx':251, 'ox':0, 'dx':0.005, 'lx':'x', 'ux':'km', 'ny':75, 'oy':0, 'dy':0.005, 'ly':'y', 'uy':'km', 'nz':176, 'oz':0, 'dz':0.005, 'lz':'z', 'uz':'km', ############################### # Wavelet parameters ############################### 'nt':4001, 'ot':0, 'dt':0.001, 'lt':'t', 'ut':'s', 'frq':45, # Peak frequency for Ricker wavelet 'kt':100, # Wavelet start position (wavelets are delayd for zero-phase) ############################### # Modeling code parameters ############################### 'cfl': True, 'dabc':True, # Use absorbing boundary condition? 'nb':80, # How many cells for absorbing boundary? 'abcone':True, # Use additional ramp condition for boundaries? (Use default) 'dsou':False, # Use displacement source (acoustic-only) 'expl':False, # Use exploding reflector (acoustic-only) 'free':False, # Use free surface (generate multiples) 'jdata':1, # Interval between time-iterations before saving data at recv 'snap':True, # Save wavefield snapshots? 'verb':True, # Verbose output? 'jsnap':1, # Interval between time-iterations before saving wfld snapshot 'debug':False, # Debugging output (elastic-only)? 'nbell':5, # Size of interpolation for injection 'ssou':False, # Use stress-source (elastic-only) 'ompchunk':1, # OpenMP chunk size (use default) 'ompnth':2, # Number of OpenMP threads to use (4 works best) ############################### # Thomsen parameters for models ############################### 'vp':1.5, 'ro':2.0, ############################### # Miscellaneous parameters ############################### 'height':10, 'nht': 80, 'nhx': 40, 'nhz': 40, } fdmod.param(par) par['nframe']=5 par['iframe']=4 # ------------------------------------------------------------ # End user parameters -- NO EDITS BELOW # ------------------------------------------------------------ par['kz']=2./3.*par['nz'] return par def windowreceivers(rr,groups,keys,par): for group,gpars in groups.items(): nwin = gpars['nr'] owin = gpars['or'] dwin = gpars['dr'] Flow('rr-'+group,gpars['group'],'window n2=%d f2=%d j2=%d squeeze=n' % (nwin,owin,dwin)) Plot('rr-'+group,fdmod.rrplot('plotcol=%d plotfat=10' % gpars['color'],par)) Flow(rr,['rr-'+group for group in keys], 'cat axis=2 ${SOURCES[1:%d]}' % len(groups)) Plot(rr,['rr-'+group for group in keys],'Overlay') def triangulate(image,tcube,noisy,clean,groups,keys,hypocenters,subgroups,snapshots,par): ii = 0 Fork(nodes=1,time=3,ipn=1) for group in keys: gpars = groups[group] nwin = gpars['nr'] Flow('da-'+group,noisy, ''' window n1=%d f1=%d squeeze=n | ''' % (nwin,ii) + '''put o1=%(oz)g d1=%(dz)g ''' % par) Result('da-'+group+'_',clean, ''' window n1=%d f1=%d squeeze=n | ''' % (nwin,ii) + ''' put o1=0 d1=1 | transp | wiggle poly=y pclip=99 title="" labelsz=6 labelfat=3 titlesz=12 titlefat=3 label2="\F2 trace\F3 " label1="\F2 time\F3" ''' ) Result('da-'+group, '''put o1=0 d1=1 | transp | wiggle poly=n pclip=100 title="" transp=%(transp)d labelsz=6 labelfat=3 titlesz=12 titlefat=3 yreverse=%(yreverse)d %(custom)s label2="\F2 trace\F3 " label1="\F2 time\F3" ''' % gpars) backproject('da-'+group,'rr-'+group,'vp-2d','ro-2d','_wa-'+group,par) Flow('wa-%s'%group,'_wa-%s'%group, ''' transp plane=23 | transp plane=12 ''' % par) Result('wa-%s' % group,'_wa-%s' % group, 'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) + fdmod.cgrey('pclip=100',par)) for i in range(snapshots[0],snapshots[0]+snapshots[1]*snapshots[2],snapshots[2]): Plot('wa-%s-%d' % (group,i),'_wa-%s' % group,'window n3=1 f3=%d | ' % (i) + fdmod.cgrey('pclip=100',par)) Result('wa-%s-%d' % (group,i),['wa-%s-%d' % (group,i),'rr-2d'],'Overlay') subgroupwflds = [] for sub in subgroups: for j in range(0,nwin,sub): if sub + j <= nwin: Flow('da-%s-%d-%d' % (group,sub,j),'da-%s' % group, ''' window n1=%d f1=%d squeeze=n ''' % (sub,j)) Flow('rr-%s-%d-%d' % (group,sub,j),'rr-%s' % group, ''' window n2=%d f2=%d squeeze=n ''' % (sub,j)) else: Flow('da-%s-%d-%d' % (group,sub,j),'da-%s' % group, ''' window f1=%d squeeze=n ''' % (j)) Flow('rr-%s-%d-%d' % (group,sub,j),'rr-%s' % group, ''' window f2=%d squeeze=n ''' % (j)) backproject('da-%s-%d-%d' % (group,sub,j), 'rr-%s-%d-%d' % (group,sub,j), 'vp-2d','ro-2d','_wa-%s-%d-%d' % (group,sub,j),par) # Go from z-x-t to t-z-x Flow('wa-%s-%d-%d'% (group,sub,j),'_wa-%s-%d-%d'%(group,sub,j), ''' transp plane=23 | transp plane=12 ''' % par) Result('wa-%s-%d-%d' % (group,sub,j),'_wa-%s-%d-%d' % (group,sub,j), 'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) + fdmod.cgrey('pclip=100',par)) subgroupwflds.append('_wa-%s-%d-%d' % (group,sub,j)) j = 0 for hypocenter in hypocenters: xi = hypocenter[0] zi = hypocenter[1] ti = hypocenter[2] Flow('hypo-%d-%s' % (j,group), '_wa-%s' % group, ''' window min1=%(oz)f min2=%(ox)f n1=%(nz)d n2=%(nx)d | ''' % par + ''' window n1=1 n2=1 f1=%d f2=%d ''' % (zi,xi)) for subgroupwfld in subgroupwflds: subgrouphypo = subgroupwfld.replace('_wa','hypo-%d' % j) Flow(subgrouphypo,subgroupwfld, ''' window n1=1 n2=1 f1=%d f2=%d ''' % (zi,xi)) j+= 1 ii += nwin Iterate() Join() for jhypo in range(len(hypocenters)): Flow('hypo-%d' % jhypo, ['hypo-%d-%s' % (jhypo,group) for group in keys], ''' cat axis=2 ${SOURCES[1:%d]} ''' % len(keys)) Result('hypo-%d' % jhypo, 'grey pclip=95') #Save('hypo-%d' % jhypo) for sub in subgroups: subwflds = [] for group in keys: for j in range(0,groups[group]['nr'],sub): subwflds.append('hypo-%d-%s-%d-%d' % (jhypo,group,sub,j)) Flow('hypo-%d-%d' % (jhypo,sub), subwflds, ''' cat axis=2 ${SOURCES[1:%d]} ''' % len(subwflds)) Result('hypo-%d-%d' % (jhypo,sub),'grey pclip=95') #Save('hypo-%d-%d' % (jhypo,sub)) for sub in subgroups: subwflds = ['wa-%s-%d-%d'% (group,sub,j) for group in keys for j in range(0,groups[group]['nr'],sub) ] Flow(tcube+'-sem-%d' % sub,subwflds, ''' semblance m=10 ${SOURCES[1:%d]} | transp plane=12 | transp plane=23 ''' % len(subwflds)) Flow(tcube+'-%d' % sub,subwflds, ''' add mode=p ${SOURCES[1:%d]} | transp plane=12 | transp plane=23 ''' % len(subwflds)) Result(tcube+'-sem-%d'% sub, 'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) + fdmod.cgrey('pclip=99.9 gainpanel=a',par)) Result(tcube+'-%d' % sub, 'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) + fdmod.cgrey('pclip=99.9 gainpanel=a',par)) Flow(image+'-%d' % sub,tcube+'-%d' % sub,'stack axis=3') #Flow(image+'-sem-%d' % sub,tcube+'-sem-%d' % sub,'thr thr=0.4 mode="hard" | stack axis=3') Flow(image+'-sem-%d' % sub,tcube+'-sem-%d' % sub,'stack axis=3') Plot(image+'-sem-box-%d' % sub,image+'-sem-%d' % sub, fdmod.cgrey('pclip=100 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par)) Plot(image+'-box-%d' % sub,image+'-%d' % sub, fdmod.cgrey('pclip=99.98 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par)) Plot(image+'-%d' % sub,fdmod.cgrey('pclip=99.98',par)) Result(image+'-%d' % sub,[image+'-%d' % sub,'ss-2d','box'],'Overlay') Result('image-box-%d' % sub,[image+'-box'+'-%d' % sub,'ss-2d-box'],'Overlay') Result('image-sem-box-%d' % sub,[image+'-sem-box-%d' % sub,'ss-2d-box'],'Overlay') Flow(tcube+'-sem',['wa-%s' % group for group in keys], ''' semblance m=10 ${SOURCES[1:%d]} | transp plane=12 | transp plane=23 ''' % len(keys)) Flow(tcube,['wa-%s'%group for group in keys], ''' add mode=p ${SOURCES[1:%d]} | transp plane=12 | transp plane=23 ''' % len(keys)) Result(tcube, 'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) + fdmod.cgrey('pclip=100 gainpanel=a',par)) Result(tcube+'-sem', 'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) + fdmod.cgrey('pclip=100 gainpanel=a',par)) for i in range(snapshots[0],snapshots[0]+snapshots[1]*snapshots[2],snapshots[2]): Plot(tcube+'-%d' % i,tcube,'window n3=%d f3=%d | ' % (1,i) + fdmod.cgrey('pclip=99.9 gainpanel=a',par)) Result(tcube+'-%d' % i , [tcube+'-%d' % i,'rr-2d'],'Overlay') Plot(tcube+'-sem-%d' % i,tcube+'-sem','window n3=%d f3=%d | ' % (1,i) + fdmod.cgrey('pclip=99.9 gainpanel=a',par)) Result(tcube+'-sem-%d' % i , [tcube+'-sem-%d' % i,'rr-2d'],'Overlay') Flow(image,tcube,'stack axis=3') #Flow(image+'-sem',tcube+'-sem','thr thr=0.4 mode="hard" | stack axis=3') Flow(image+'-sem',tcube+'-sem','stack axis=3') Plot(image+'-box',image,fdmod.cgrey('pclip=99.98 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par)) Plot(image+'-sem-box',image+'-sem',fdmod.cgrey('pclip=99.98 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par)) Plot(image,fdmod.cgrey('pclip=99.98',par)) Plot(image+'-sem',fdmod.cgrey('pclip=100',par)) Result(image,[image,'ss-2d','box'],'Overlay') Result(image+'-sem',[image+'-sem','ss-2d','box'],'Overlay') Result('image-box',[image+'-box','ss-2d-box'],'Overlay') Result('image-sem-box',[image+'-sem-box','ss-2d-box'],'Overlay') # ------------------------------------------------------------ # Setup functions for calling FD operators # ------------------------------------------------------------ # These operations are usually hidden, but having them here is more # transparent. All possible options are specified by the user. def backproject(data,receivers,velocity,density,wavefieldname,par): Flow(data+'-reversed',data,'sfreverse which=2 opt=i') awefd(data+'-junk',wavefieldname,data+'-reversed', velocity,density, receivers,receivers, par) def awefd(odat,owfl,idat,velo,dens,sou,rec,par): # call the acoustic wave equation code # see sfawe for a more detaile description of options Flow([odat,owfl],[idat,velo,dens,sou,rec], ''' awe ompchunk=%(ompchunk)d ompnth=%(ompnth)d snap=%(snap)d jsnap=%(jsnap)d dabc=%(dabc)d nb=%(nb)d dsou=%(dsou)d free=%(free)d expl=%(expl)d jdata=%(jdata)d cfl=%(cfl)d fmax=%(frq)f verb=%(verb)d vel=${SOURCES[1]} den=${SOURCES[2]} sou=${SOURCES[3]} rec=${SOURCES[4]} wfl=${TARGETS[1]} nqz=%(nz)d nqx=%(nx)d dqz=%(dz)f dqx=%(dx)f oqz=%(oz)f oqx=%(ox)f ''' % par) # ------------------------------------------------------------ def wavelet(waveletname,frequency,kt,par): partemp = par.copy() partemp['kt'] = kt partemp['frequency'] = frequency Flow(waveletname,None, ''' spike nsp=1 mag=1 n1=%(nt)d d1=%(dt)g o1=%(ot)g k1=%(kt)d | pad end1=%(nt)d | ricker1 frequency=%(frequency)g | window n1=%(nt)d | scale axis=123 | put label1=t | thr thr=0.001 ''' % partemp) # ------------------------------------------------------------ def makemicroseisms(ns,wav,sou,par): sources = [] wavelets = [] r = random.Random() r.seed(1234) locations = [] for i in range(ns): tag = '-%03d' % i xi = r.randrange(100,150) zi = r.randrange(50,60) ti = r.randrange(par['nt']/4,3*par['nt']/4) print 'Microseism %d %d %d %d' % (i,xi,zi,ti) locations.append((xi,zi,ti)) xsou = par['ox']+par['dx']*xi zsou = par['oz']+par['dz']*zi fdmod.point(sou+tag,xsou,zsou,par) wavelet(wav+tag,par['frq'],ti,par) sources.append(sou+tag) wavelets.append(wav+tag) Flow(wav+'_',wavelets,'cat axis=2 ${SOURCES[1:%d]}' % ns) Flow(sou,sources,'cat axis=2 ${SOURCES[1:%d]}' % ns) Plot('ss-2d',fdmod.ssplot('symbol=+ symbolsz=7 plotfat=5',par)) Plot('ss-2d-box','ss-2d', fdmod.ssplot('min1=0.4 max1=0.9 min2=0.2 max2=0.4 plotfat=5 symbol=+ symbolsz=9',par)) Flow( 'wava','wav_','add scale=10000000 | transp') Result('wava','transp |' + fdmod.waveplot('',par)) # These are bad locations, no microseisms here. locations.append((50,25,100)) locations.append((75,80,100)) return locations # ------------------------------------------------------------ def model(rr,par): Flow('zero-2d',None, ''' spike nsp=1 mag=0.0 n1=%(nz)d o1=%(oz)g d1=%(dz)g n2=%(nx)d o2=%(ox)g d2=%(dx)g | put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s ''' % par) Flow('vz-2d','zero-2d', ''' spike nsp=5 nsp=5 k1=10,40,70,100,130 l1=39,69,99,129,%(nz)d mag=0.2,0.4,0.6,0.8,1.0 n1=%(nz)d o1=%(oz)g d1=%(dz)g n2=%(nx)d o2=%(ox)g d2=%(dx)g | put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s | add add=%(vp)f ''' % par) Flow('fault-2d','zero-2d', ''' spike nsp=1 k1=40 mag=1.0 l1=%(nz)d k2=60 l2=%(nx)d p2=1 n1=%(nz)d o1=%(oz)g d1=%(dz)g n2=%(nx)d o2=%(ox)g d2=%(dx)g | put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s ''' % par) Flow('const-2d','zero-2d', ''' spike nsp=1 mag=1.0 k1=40 l1=%(nz)d k2=1 l2=59 n1=%(nz)d o1=%(oz)g d1=%(dz)g n2=%(nx)d o2=%(ox)g d2=%(dx)g | put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s ''' % par) Flow('vp-2d','vz-2d','window') Flow('ro-2d','zero-2d','math output="%(ro)g"' %par) fdmod.makebox('box',0.2,0.4,0.4,0.9,par) Plot('box',fdmod.bbplot('',par)) Plot('vp-2d',fdmod.cgrey('allpos=y pclip=100 bias=1.5 ',par)) Plot('ro-2d',fdmod.cgrey('bias=2. allpos=y',par)) Result('vp-2d','vp-2d ss-2d rr-2d box','Overlay') Result('ro-2d','ro-2d ss-2d','Overlay') def synthesize(data,rr,snapshots,par): # 2D acoustic modeling awefd(data,'wa-2d','wava','vp-2d','ro-2d','ss-2d',rr,par) Result(data,'transp |' + fdmod.dgrey('',par)) for i in range(snapshots[0],snapshots[0]+snapshots[1]*snapshots[2],snapshots[2]): Plot('wa-2d-%d' % i,'wa-2d','window n3=%d f3=%d | ' % (1,i) + fdmod.cgrey('pclip=99.9 gainpanel=a',par)) Result('wa-2d-%d' %i , ['wa-2d-%d' % i,rr],'Overlay') def addnoise(noisy,data,scale,snapshots,par): Flow(noisy,data, 'math output="0" | noise seed=123 | transp | bandpass flo=20 fhi=50 | transp | add scale=%f | add mode=a ${SOURCES[0]} | add scale=1e6' % scale) Result(noisy,'transp | grey pclip=99.9') backproject(noisy,'rr-2d','vp-2d','ro-2d','wa-%s'% noisy,par) Result('wa-%s' % noisy, 'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) + fdmod.cgrey('pclip=100',par))
[ "jgodwin@mines.edu" ]
jgodwin@mines.edu
584b1e5c22490eed08ae277c45d9260ee70e2553
2c7bc4e4289e7146c9a9b0af836fe4069521737a
/第一阶段/基础/第10章 文件和异常/10.3 异常/10.3.9 决定报告哪些错误.py
930fb4760e7056894619e2fdb20480984d046284
[ "Apache-2.0" ]
permissive
kwhua/nihao-
e2da2502cff9e4b0b21770e02d971d7ec857c6fa
0b69b0cda4f57831504d01b51bd2370f436db2b8
refs/heads/master
2022-12-19T04:23:49.757470
2020-09-24T07:53:35
2020-09-24T07:53:35
298,187,993
1
0
null
null
null
null
UTF-8
Python
false
false
922
py
''' 在什么情况下该向用户报告错误呢?在什么情况下又该在失败时一声不吭呢?如果用户知道 要分析哪些文件,他们希望在有文件没有文件等稀释出现一条消息,将其中的原因告诉他们. 如果客户只想看到结果,而不是要分析哪些文件,可能就需要在哪些文件不存在时告知他们. 向用户显示他不想看待的信息可能会降低程序的可用性.Python的错误处理结构让你能够细致地 控制与用户分享错误信息的程度,要分享多少信息由你决定. 编写得很好且经过详尽测试的代码不容易出现内部错误,入语法或逻辑错误,但只要程序依赖 于外部因素,如用户输入、存在指定的文件、有网络链接,就有可能出现异常。凭借经验可判断 该在程序的什么地方包含异常处理块,以及错误是该向用户提供多少相关的信息。 '''
[ "646013895@qq.com" ]
646013895@qq.com
2f6e56a99087d6e94afa25eea1ce94be32f3127d
d906d1eb4f590deabb3c90ba9bb9dd6b11cabc55
/web1/app.py
8e1d00b00346a5d0c80c0b5615f4f791fec19f93
[]
no_license
Lengoctruongson/lengoctruongson-fundametal-c4e21
83dfe671639faaf2bd2642f77b62df1c306db2f7
55affab6315f408f8c42a12b57775ec442a222f8
refs/heads/master
2020-03-26T20:02:56.120667
2018-10-09T16:41:34
2018-10-09T16:41:34
145,301,267
0
1
null
null
null
null
UTF-8
Python
false
false
1,569
py
#1. Creat a flask app from flask import Flask, render_template app = Flask(__name__) ps = [ "Trong đầm gì đẹp bằng sen aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "Lá xanh bông trắng lại chen nhị vàngbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "Nhị vàng bông trắng lá xanh ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" ] #2. Creat router @app.route("/") def homepage(): return render_template("homepage.html", title="Ca dao về sen", posts=ps) @app.route("/huy") def huypage(): return "Hello Huy" @app.route("/hello/<name>") def hello(name): return "Hello " + name @app.route("/posts/<int:position>") def post_detail(position): if position < 0 or position >= len(ps): return "Not found", 404 post = ps[position - 1] return render_template("post_detail.html", post=post) @app.route("/posts") def posts(): shortened_ps = [] for post in ps: shortened_ps.append(post[0:20]) return render_template("post_list.html", posts=shortened_ps) # @app.route("/add/<number1>/<number2>") # def add(number1,number2): # add = str(int(number1) + int(number2)) # return add @app.route("/add/<int:a>/<int:b>") def add(a,b): result = a+b return str(result) @app.route("/h1tag") def h1tag(): return "<h1>Heading 1 - Bigggg</h1><p>Hom nay toi buon</p>" #3. Run app print("Running app") if __name__ == "__main__": app.run(debug=True) # listening
[ "leson1871995@hgamil.com" ]
leson1871995@hgamil.com
3a3bf2a75f8238a4f8a98e775a43ea60086f6668
87521e0ce35095d06f8cd2e0890f8b73f9ec0511
/training_window.py
3a083317b9c5a9109bcbb974ec32216694347011
[]
no_license
chamara96/voice-command-rnn
20fa6446e44a72c78113528b598756b545c1529d
e6847af88e09e01ddf06f1d6cdd1b0835d30ba4f
refs/heads/main
2023-01-02T12:12:28.542385
2020-11-01T06:52:28
2020-11-01T06:52:28
308,967,152
0
0
null
null
null
null
UTF-8
Python
false
false
7,464
py
import sys from PIL import ImageTk, Image import time try: import Tkinter as tk except ImportError: import tkinter as tk try: import ttk py3 = False except ImportError: import tkinter.ttk as ttk py3 = True from tkinter import messagebox import neural_network import dataset_handling def update_thread(): # global is_stop time.sleep(5) is_train_end = 0 while not is_train_end: is_train_end = dataset_handling.end_train # text = "" w.Label_log.delete("1.0", tk.END) if is_stop == 1: break curr_epoch, total_epoches = neural_network.check_curr_epoch() w.TProgressbar1['value'] = int((curr_epoch) * 100 / total_epoches) filename = "checkpoints/log.txt" try: with open(filename) as f: text = f.read() except IOError: text = "" w.Label_log.insert("1.0", text) try: img = Image.open("checkpoints/fig.jpg") except IOError: img = Image.open("classes/wait.png") basewidth = 550 wpercent = (basewidth / float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) img = ImageTk.PhotoImage(img) w.Label_plot['image'] = img w.Label_plot.image = img sys.stdout.flush() print("Updated") time.sleep(2) messagebox.showinfo("Training", "Done..!") def init(top, gui, *args, **kwargs): global w, top_level, root w = gui top_level = top root = top def btn_stop(): destroy_window() sys.stdout.flush() is_stop = 0 def btn_update_view(): curr_epoch, total_epoches = neural_network.check_curr_epoch() w.TProgressbar1['value'] = int(curr_epoch * 100 / total_epoches) filename = "checkpoints/log.txt" try: with open(filename) as f: text = f.read() except IOError: text = "" w.Label_log.insert("1.0", text) try: img = Image.open("checkpoints/fig.jpg") except IOError: img = Image.open("classes/wait.png") basewidth = 550 wpercent = (basewidth / float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) img = ImageTk.PhotoImage(img) w.Label_plot['image'] = img w.Label_plot.image = img sys.stdout.flush() print("Updated") # time.sleep(2) def destroy_window(): global is_stop is_stop=1 print("QQWWEERR") # Function which closes the window. global top_level top_level.destroy() top_level = None sys.exit() def vp_start_gui(): '''Starting point when module is the main routine.''' global val, w, root root = tk.Tk() top = Toplevel1 (root) init(root, top) root.mainloop() w = None def create_Toplevel1(rt, *args, **kwargs): '''Starting point when module is imported by another module. Correct form of call: 'create_Toplevel1(root, *args, **kwargs)' .''' global w, w_win, root #rt = root root = rt w = tk.Toplevel (root) top = Toplevel1 (w) init(w, top, *args, **kwargs) return (w, top) def destroy_Toplevel1(): global w w.destroy() w = None class Toplevel1: def __init__(self, top=None): '''This class configures and populates the toplevel window. top is the toplevel containing window.''' _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = '#d9d9d9' # X11 color: 'gray85' _ana1color = '#d9d9d9' # X11 color: 'gray85' _ana2color = '#ececec' # Closest X11 color: 'gray92' self.style = ttk.Style() if sys.platform == "win32": self.style.theme_use('winnative') self.style.configure('.',background=_bgcolor) self.style.configure('.',foreground=_fgcolor) self.style.map('.',background= [('selected', _compcolor), ('active',_ana2color)]) top.geometry("1245x656+220+79") top.minsize(120, 1) top.maxsize(2650, 1005) top.resizable(0, 0) top.title("Training Model") top.configure(background="#d9d9d9") self.Labelframe1 = tk.LabelFrame(top) self.Labelframe1.place(x=20, y=40, height=600, width=600) self.Labelframe1.configure(relief='groove') self.Labelframe1.configure(foreground="black") self.Labelframe1.configure(text='''Log''') self.Labelframe1.configure(background="#d9d9d9") self.Label_log=tk.Text(self.Labelframe1) # self.Label_log = tk.Label(self.Labelframe1) self.Label_log.place(x=20, y=30, height=551, width=564 , bordermode='ignore') # self.Label_log.configure(anchor='nw') self.Label_log.configure(background="#d9d9d9") # self.Label_log.configure(disabledforeground="#a3a3a3") self.Label_log.configure(foreground="#000000") # self.Label_log.configure(text='''Label''') self.Labelframe2 = tk.LabelFrame(top) self.Labelframe2.place(x=630, y=40, height=600, width=600) self.Labelframe2.configure(relief='groove') self.Labelframe2.configure(foreground="black") self.Labelframe2.configure(text='''Training Curves''') self.Labelframe2.configure(background="#d9d9d9") self.Label_plot = tk.Label(self.Labelframe2) self.Label_plot.place(x=20, y=30, height=551, width=554 , bordermode='ignore') self.Label_plot.configure(anchor='nw') self.Label_plot.configure(background="#d9d9d9") self.Label_plot.configure(disabledforeground="#a3a3a3") self.Label_plot.configure(foreground="#000000") self.Label_plot.configure(text='''Label''') self.Button1 = tk.Button(top) self.Button1.place(x=1100, y=10, height=34, width=127) self.Button1.configure(activebackground="#ececec") self.Button1.configure(activeforeground="#000000") self.Button1.configure(background="#d9d9d9") self.Button1.configure(command=btn_stop) self.Button1.configure(disabledforeground="#a3a3a3") self.Button1.configure(foreground="#000000") self.Button1.configure(highlightbackground="#d9d9d9") self.Button1.configure(highlightcolor="black") self.Button1.configure(pady="0") self.Button1.configure(text='''Stop''') self.TProgressbar1 = ttk.Progressbar(top) self.TProgressbar1.place(x=20, y=10, width=600, height=22) self.TProgressbar1.configure(length="600") self.TProgressbar1.configure(value="10") # self.Button2 = tk.Button(top) # self.Button2.place(x=980, y=10, height=34, width=117) # self.Button2.configure(activebackground="#ececec") # self.Button2.configure(activeforeground="#000000") # self.Button2.configure(background="#d9d9d9") # self.Button2.configure(command=btn_update_view) # self.Button2.configure(disabledforeground="#a3a3a3") # self.Button2.configure(foreground="#000000") # self.Button2.configure(highlightbackground="#d9d9d9") # self.Button2.configure(highlightcolor="black") # self.Button2.configure(pady="0") # self.Button2.configure(text='''Update View''') if __name__ == '__main__': vp_start_gui()
[ "cmb.info96@gmail.com" ]
cmb.info96@gmail.com
3b2ebe81d2835ea42691bb7d5bff97c782a8bc00
59ac1d0f09ebfb527701031f3ab2cfbfb8055f51
/soapsales/employees/migrations/0003_auto_20200902_1721.py
0819efd6aafd9e48e4f311586f2596836d84ff10
[]
no_license
DUMBALINYOLO/erpmanu
d4eb61b66cfa3704bd514b58580bdfec5639e3b0
db979bafcc7481f60af467d1f48d0a81bbbfc1aa
refs/heads/master
2023-04-28T13:07:45.593051
2021-05-12T09:30:23
2021-05-12T09:30:23
288,446,097
1
1
null
null
null
null
UTF-8
Python
false
false
543
py
# Generated by Django 3.0.7 on 2020-09-02 15:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('employees', '0002_auto_20200902_0038'), ] operations = [ migrations.RenameField( model_name='employee', old_name='is_staff', new_name='is_admin', ), migrations.AlterField( model_name='employee', name='is_superuser', field=models.BooleanField(default=False), ), ]
[ "baridzimaximillem@gmail.com" ]
baridzimaximillem@gmail.com
835a35a0816d80e070b145914b614c4079752764
680d9e12f9916f68f84921e1b0328786454f2d50
/cmd_line_sample.py
3485a5f3ce5e52b1f0b411f971f00a44f69189b3
[]
no_license
vkarpov15/hydra-injector-py
24c791fd1bc3c90681b48f7515fc0e359fd14a94
3948b5056c4cf563db77c7172c6660daa7c62b19
refs/heads/master
2020-12-24T13:52:41.541934
2012-11-09T01:39:32
2012-11-09T01:39:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,353
py
# # cmd_line_sample.py # # Created on: November 3, 2012 # Author: Valeri Karpov # # An example usage of CommandLineInjector - a very general method for stripping # padding from a sample file. While this is a somewhat trivial example, it # highlights some of the more useful features of this library - managing object # ("square") life cycle, wiring two methods / "circles" together, constructing # squares from command line params, and a minimum of non-reusable boilerplate # from CommandLineInjector import * import inspect class FileReader: inject = ["infile"] def __init__(self, infile): self.filename = infile print infile def initialize(self): self.f = open(self.filename, "r") def close(self): self.f.close() def getLines(self): return self.f.readlines() class FileWriter: inject = ["outfile"] def __init__(self, outfile): self.filename = outfile print outfile def initialize(self): self.f = open(self.filename, "w") def close(self): self.f.close() def writeLine(self, line): self.f.write("%s\n" % line) def removePaddingFromFile(reader): lines = reader.getLines() newLines = [line.strip() for line in lines] return newLines def writeUnpaddedFile(writer, lines = "method:removePaddingFromFile"): for line in lines: writer.writeLine(line) #### This is boilerplate #### Sample run: python cmd_line_sample.py writeUnpaddedFile --f="../test" --outfile=../test2 class MyRunner: def run(self, method, params): return eval(method)(**params) def getSpecs(self, method): return inspect.getargspec(eval(method)) # Binding magic. Roughly translated: # 1) Whenever a method or class asks for something called "reader", it means # a FileReader where the constructor parameter "infile" is taken from # command line parameter -f # 2) Similar to above, "writer" is a FileWriter where all of its constructor # parameters are taken from command line parameter with same name # 3/4) Add the methods removePaddingFromFile and writeUnpaddedFile as callable # methods from command line # 5) Run using command line arguments using the runner from this scope CommandLineInjector().addClass("reader", FileReader, { "infile" : "f" }).addClass("writer", FileWriter).addMethod("removePaddingFromFile").addMethod("writeUnpaddedFile").run(MyRunner())
[ "valkar207@gmail.com" ]
valkar207@gmail.com
9f9308863eec758d41777158b11d291e1b437a83
9b63ade6dd9c166b2e9dc363de94d6a02149bc69
/app/core/migrations/0001_initial.py
dd8e72540712189dd4156237b574b3e1e3799370
[ "MIT" ]
permissive
nafeesahyounis/recipe-app-api
25244f7a12772a0281d99c03a0c6cf9b434ba849
ff9f42de65d9b0185d9ab9fb565e4a881831cb15
refs/heads/main
2023-03-07T13:00:00.005410
2021-02-24T10:02:04
2021-02-24T10:02:04
338,332,277
0
0
null
null
null
null
UTF-8
Python
false
false
1,709
py
# Generated by Django 3.1.6 on 2021-02-23 11:23 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(max_length=255, unique=True)), ('name', models.CharField(max_length=255)), ('is_active', models.BooleanField(default=True)), ('is_staff', models.BooleanField(default=False)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'abstract': False, }, ), ]
[ "nafeesah.youniss@gmail.com" ]
nafeesah.youniss@gmail.com
46e1519a37697b33c70c2f43ee6217c51755e86e
b169e1ac175f0acf5e48d58ce1acd04e6e4be158
/utils/logfile_parser.py
832d1045ea605bf6720390d8e3465002a8d2f63f
[]
no_license
bip5/osr_closed_set_all_you_need
20ec1380190d3a1eb13eebdeeddabaff4f91b019
0e57845f6a4a64f6a01a31dec6911c5cb5bf3c5d
refs/heads/main
2023-08-17T18:12:47.691043
2021-10-13T22:30:35
2021-10-13T22:30:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,967
py
import re import pandas as pd import os import numpy as np from matplotlib import pyplot as plt pd.options.display.width = 0 rx_dict = { 'model_dir': re.compile(r'model_dir=\'(.*?)\''), 'dataset': re.compile(r'dataset=\'(.*?)\''), 'loss': re.compile(r'loss=\'(.*?)\''), 'cs': re.compile(r'cs=(.*?),'), 'm': re.compile(r'rand_aug_m=([-+]?\d*)'), 'n': re.compile(r'rand_aug_n=([-+]?\d*)'), 'performance': re.compile("[-+]?\d*\.\d+|\d+"), 'split_idx': re.compile(r'split_idx=(\d)'), 'seed': re.compile(r'seed=(\d)'), 'runtime': re.compile(r'Total elapsed time \(h:m:s\): (.*?)\n'), 'label_smoothing': re.compile("label_smoothing=([-+]?\d*\.\d+|\d+)"), 'lr': re.compile(" lr=(\d*\.\d+|\d+)") # 'oscr': re.compile("label_smoothing=([-+]?\d*\.\d+|\d+)") } save_root_dir = '/work/sagar/open_set_recognition/sweep_summary_files/ensemble_pkls' def get_file(path): file = [] with open(path, 'rt') as myfile: for myline in myfile: # For each line, read to a string, file.append(myline) return file def parse_arpl_out_file(path, rx_dict, root_dir=save_root_dir, save_name='test.pkl', save=True, verbose=True): file = get_file(path=path) models = [] for i, line in enumerate(file): if line.find('Namespace') != -1: model = {} s = rx_dict['model_dir'].search(line).group(1) exp_id = s[s.find("("):s.find(")") + 1] model['exp_id'] = exp_id model['M'] = rx_dict['m'].search(line).group(1) model['N'] = rx_dict['n'].search(line).group(1) model['split_idx'] = rx_dict['split_idx'].search(line).group(1) model['seed'] = rx_dict['seed'].search(line).group(1) model['dataset'] = rx_dict['dataset'].search(line).group(1) model['loss'] = rx_dict['loss'].search(line).group(1) model['cs'] = rx_dict['cs'].search(line).group(1) model['lr'] = rx_dict['lr'].search(line).group(1) if rx_dict['label_smoothing'].search(line) is not None: model['label_smoothing'] = rx_dict['label_smoothing'].search(line).group(1) if line.find('Finished') != -1: line_ = file[i - 1] perfs = rx_dict['performance'].findall(line_)[:3] model['Acc'] = perfs[0] model['AUROC'] = perfs[1] model['OSCR'] = perfs[2] model['runtime'] = rx_dict['runtime'].search(line).group(1) models.append(model) data = pd.DataFrame(models) if verbose: print(data) if save: save_path = os.path.join(root_dir, save_name) data.to_pickle(save_path) else: return data def parse_multiple_files(all_paths, rx_dict, root_dir=save_root_dir, save_name='test.pkl', verbose=True, save=False): all_data = [] for path in all_paths: data = parse_arpl_out_file(path, rx_dict, save=False, verbose=False) data['fname'] = path.split('/')[-1] all_data.append(data) all_data = pd.concat(all_data) save_path = os.path.join(root_dir, save_name) if save: all_data.to_pickle(save_path) if verbose: print(all_data) return all_data save_dir = '/work/sagar/open_set_recognition/sweep_summary_files/ensemble_pkls' base_path = '/work/sagar/open_set_recognition/slurm_outputs/myLog-{}.out' # base_path = '/work/sagar/open_set_recognition/dev_outputs/logfile_{}.out' all_paths = [base_path.format(i) for i in [325905]] # all_paths = [base_path.format(i) for i in [507, 508, 509, 510, 511]] data = parse_multiple_files(all_paths, rx_dict, verbose=True, save=False, save_name='test.pkl') print(f"Mean Acc: {np.mean(data['Acc'].values.astype('float')):.2f}") print(f"Mean AUROC: {np.mean(data['AUROC'].values.astype('float')):.2f}") print(f"Mean OSCR: {np.mean(data['OSCR'].values.astype('float')):.2f}") print(len(data)) print(data['exp_id'].values)
[ "sagarvaze@dhcp24.robots.ox.ac.uk" ]
sagarvaze@dhcp24.robots.ox.ac.uk
27ca4ceae6de9d605e2bfc5c1fee240d3f1fe145
10300363f12e5a6a0ea6a69d0a6d210174499d60
/times.py
746272f2b9f1a029c66f51b8e55c0ba5edea3241
[]
no_license
nedbat/point_match
2da5cc12bf3f3866b35ec71ea227a5d21760ca97
a6c19ed1d206ec1ad02b13e15b8d761192b32593
refs/heads/master
2023-06-22T04:16:09.638622
2019-04-01T21:25:09
2019-04-01T21:25:09
100,109,656
3
1
null
null
null
null
UTF-8
Python
false
false
1,068
py
import random import timeit if 0: TRIES = 10000 for z in range(7): n = int(10**z) stmt='random.randint(1, 999999) in d' setup='import random; d = {{random.randint(1, 999999): 1 for _ in xrange({N:d})}}'.format(N=n) total = timeit.timeit(stmt=stmt, setup=setup, number=TRIES) print("{N:>9d}: {time:.7f}s".format(time=total/TRIES, N=n)) if 0: TRIES = 2000 for z in range(7): n = int(10**z) stmt='random.randint(1, 999999) in x' setup='import random; x = [random.randint(1, 999999) for _ in xrange({N:d})]'.format(N=n) total = timeit.timeit(stmt=stmt, setup=setup, number=TRIES) print("{N:>9d}: {time:.7f}s".format(time=total/TRIES, N=n)) if 1: TRIES = 200 for z in range(7): n = int(10**z) stmt='sorted(x)' setup='import random; x = [random.randint(1, 999999) for _ in xrange({N:d})]'.format(N=n) total = timeit.timeit(stmt=stmt, setup=setup, number=TRIES) print("{N:>9d}: {time:.7f}s".format(time=total/TRIES, N=n))
[ "ned@nedbatchelder.com" ]
ned@nedbatchelder.com
792a326fad5224ee15c058836faae17f70de5ca2
30174fca608e3fb20664acb27bcbf4fb037ca4f1
/foodrider/migrations/0016_auto_20200825_1822.py
c9ea4a488536f8777a044fb183d9e084b689fa35
[]
no_license
jabir15/foodrider
f32e88b8c9d612bace39cf475d6dfa41800c98d3
724828f39ddd05e612030dfea846a7a8b5b017a8
refs/heads/master
2023-04-16T17:54:58.326973
2021-05-02T10:07:51
2021-05-02T10:07:51
290,949,621
0
0
null
null
null
null
UTF-8
Python
false
false
438
py
# Generated by Django 3.1 on 2020-08-25 16:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('foodrider', '0015_auto_20200825_1820'), ] operations = [ migrations.AlterField( model_name='menuitemoption', name='discount_price', field=models.DecimalField(decimal_places=2, default='0.00', max_digits=7), ), ]
[ "jabir.hussain.aec@gmail.com" ]
jabir.hussain.aec@gmail.com
14d91c016f740d9564b17288e566a3efeee3fcfe
c77843e9d25458d4a848c41f7e88d942bcc0d7dc
/code/lib/nltk/eval.py
4b8ca39cbde7a5dadf32d3b17f5fbde666b8c66e
[]
no_license
sethwoodworth/wikipedia-style-edits
0cf99e9f184a8cafce8b8e3e92bbbd6dc0540659
b660ac52ee2c901bc5358e2af2fa8be2d43f6a4c
refs/heads/master
2021-01-22T03:12:54.954349
2008-10-15T21:32:23
2008-10-15T21:32:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,713
py
# Natural Language Toolkit: Evaluation # # Copyright (C) 2004 University of Pennsylvania # Author: Edward Loper <edloper@gradient.cis.upenn.edu> # Steven Bird <sb@csse.unimelb.edu.au> # URL: <http://lib.nltk.sf.net> # For license information, see LICENSE.TXT """ Utility functions for evaluating processing modules. """ import sets, math from lib.nltk.chktype import chktype def accuracy(reference, test): """ Given a list of reference values and a corresponding list of test values, return the percentage of corresponding values that are equal. In particular, return the percentage of indices C{0<i<=len(test)} such that C{test[i] == reference[i]}. @type reference: C{list} @param reference: An ordered list of reference values. @type test: C{list} @param test: A list of values to compare against the corresponding reference values. @raise ValueError: If C{reference} and C{length} do not have the same length. """ assert chktype(1, reference, []) assert chktype(2, test, []) if len(reference) != len(test): raise ValueError("Lists must have the same length.") num_correct = [1 for x,y in zip(reference, test) if x==y] return float(len(num_correct)) / len(reference) def precision(reference, test): """ Given a set of reference values and a set of test values, return the percentage of test values that appear in the reference set. In particular, return |C{reference}S{cap}C{test}|/|C{test}|. If C{test} is empty, then return C{None}. @type reference: C{Set} @param reference: A set of reference values. @type test: C{Set} @param test: A set of values to compare against the reference set. @rtype: C{float} or C{None} """ assert chktype(1, reference, sets.BaseSet) assert chktype(2, test, sets.BaseSet) if len(test) == 0: return None else: return float(len(reference.intersection(test)))/len(test) def recall(reference, test): """ Given a set of reference values and a set of test values, return the percentage of reference values that appear in the test set. In particular, return |C{reference}S{cap}C{test}|/|C{reference}|. If C{reference} is empty, then return C{None}. @type reference: C{Set} @param reference: A set of reference values. @type test: C{Set} @param test: A set of values to compare against the reference set. @rtype: C{float} or C{None} """ assert chktype(1, reference, sets.BaseSet) assert chktype(2, test, sets.BaseSet) if len(reference) == 0: return None else: return float(len(reference.intersection(test)))/len(reference) def f_measure(reference, test, alpha=0.5): """ Given a set of reference values and a set of test values, return the f-measure of the test values, when compared against the reference values. The f-measure is the harmonic mean of the L{precision} and L{recall}, weighted by C{alpha}. In particular, given the precision M{p} and recall M{r} defined by: - M{p} = |C{reference}S{cap}C{test}|/|C{test}| - M{r} = |C{reference}S{cap}C{test}|/|C{reference}| The f-measure is: - 1/(C{alpha}/M{p} + (1-C{alpha})/M{r}) If either C{reference} or C{test} is empty, then C{f_measure} returns C{None}. @type reference: C{Set} @param reference: A set of reference values. @type test: C{Set} @param test: A set of values to compare against the reference set. @rtype: C{float} or C{None} """ p = precision(reference, test) r = recall(reference, test) if p is None or r is None: return None if p == 0 or r == 0: return 0 return 1.0/(alpha/p + (1-alpha)/r) def log_likelihood(reference, test): """ Given a list of reference values and a corresponding list of test probability distributions, return the average log likelihood of the reference values, given the probability distributions. @param reference: A list of reference values @type reference: C{list} @param test: A list of probability distributions over values to compare against the corresponding reference values. @type test: C{list} of L{ProbDist} """ if len(reference) != len(test): raise ValueError("Lists must have the same length.") # Return the average value of dist.logprob(val). total_likelihood = sum([dist.logprob(val) for (val, dist) in zip(reference, test)]) return total_likelihood/len(reference) class ConfusionMatrix: """ The confusion matrix between a list of reference values and a corresponding list of test values. Entry [M{r},M{t}] of this matrix is a count of the number of times that the reference value M{r} corresponds to the test value M{t}. E.g.: >>> ref = 'DET NN VB DET JJ NN NN IN DET NN'.split() >>> test = 'DET VB VB DET NN NN NN IN DET NN'.split() >>> cm = ConfusionMatrix(ref, test) >>> print cm['NN', 'NN'] 3 Note that the diagonal entries (M{Ri}=M{Tj}) of this matrix corresponds to correct values; and the off-diagonal entries correspond to incorrect values. """ def __init__(self, reference, test): """ Construct a new confusion matrix from a list of reference values and a corresponding list of test values. @type reference: C{list} @param reference: An ordered list of reference values. @type test: C{list} @param test: A list of values to compare against the corresponding reference values. @raise ValueError: If C{reference} and C{length} do not have the same length. """ assert chktype(1, reference, []) assert chktype(2, test, []) if len(reference) != len(test): raise ValueError('Lists must have the same length.') # Get a list of all values. values = dict([(val,1) for val in reference+test]).keys() # Construct a value->index dictionary indices = dict([(val,i) for (i,val) in enumerate(values)]) # Make a confusion matrix table. confusion = [[0 for val in values] for val in values] max_conf = 0 # Maximum confusion for w,g in zip(reference, test): confusion[indices[w]][indices[g]] += 1 max_conf = max(max_conf, confusion[indices[w]][indices[g]]) #: A list of all values in C{reference} or C{test}. self._values = values #: A dictionary mapping values in L{self._values} to their indices. self._indices = indices #: The confusion matrix itself (as a list of lists of counts). self._confusion = confusion #: The greatest count in L{self._confusion} (used for printing). self._max_conf = 0 #: The total number of values in the confusion matrix. self._total = len(reference) #: The number of correct (on-diagonal) values in the matrix. self._correct = sum([confusion[i][i] for i in range(len(values))]) def __getitem__(self, (li,lj)): """ @return: The number of times that value C{li} was expected and value C{lj} was given. @rtype: C{int} """ i = self._indices[li] j = self._indices[lj] return self._confusion[i][j] def __repr__(self): return '<ConfusionMatrix: %s/%s correct>' % (self._correct, self._total) def __str__(self): return self.pp() def pp(self, show_percents=False, values_in_chart=True): """ @return: A multi-line string representation of this confusion matrix. @todo: add marginals? """ confusion = self._confusion if values_in_chart: values = self._values else: values = range(len(self._values)) # Construct a format string for row values valuelen = max([len(str(val)) for val in values]) value_format = '%' + `valuelen` + 's |' # Construct a format string for matrix entries if show_percents: entrylen = 6 entry_format = '%5.1f%%' else: entrylen = len(`self._max_conf`) entry_format = '%' + `entrylen` + 'd' # Write the column values. value_strings = [str(val) for val in values] s = '' for i in range(valuelen): s += (' '*valuelen)+' |' for val in value_strings: if i >= valuelen-len(val): s += val[i-valuelen+len(val)].rjust(entrylen+1) else: s += ' '*(entrylen+1) s += ' |\n' # Write a dividing line s += '%s-+-%s+\n' % ('-'*valuelen, '-'*((entrylen+1)*len(values))) # Write the entries. for i in range(len(values)): s += value_format % values[i] for j in range(len(values)): s += ' ' if show_percents: s += entry_format % (100.0*confusion[i][j]/self._total) else: s += entry_format % confusion[i][j] s += ' |\n' # Write a dividing line s += '%s-+-%s+\n' % ('-'*valuelen, '-'*((entrylen+1)*len(values))) # Write a key s += '(row = reference; col = test)\n' if not values_in_chart: s += 'Value key:\n' for i, value in enumerate(self._values): s += '%6d: %s\n' % (i, value) return s def key(self): values = self._values str = 'Value key:\n' indexlen = len(`len(values)-1`) key_format = ' %'+`indexlen`+'d: %s\n' for i in range(len(values)): str += key_format % (i, values[i]) return str def demo(): print '-'*75 reference = 'DET NN VB DET JJ NN NN IN DET NN'.split() test = 'DET VB VB DET NN NN NN IN DET NN'.split() print 'Reference =', reference print 'Test =', test print 'Confusion matrix:' print ConfusionMatrix(reference, test) print 'Accuracy:', accuracy(reference, test) print '-'*75 reference_set = sets.Set(reference) test_set = sets.Set(test) print 'Reference =', reference_set print 'Test = ', test_set print 'Precision:', precision(reference_set, test_set) print ' Recall:', recall(reference_set, test_set) print 'F-Measure:', f_measure(reference_set, test_set) print '-'*75 if __name__ == '__main__': demo()
[ "asheesh@fe7ecb3d-170a-0410-af80-b42c727aa7d5" ]
asheesh@fe7ecb3d-170a-0410-af80-b42c727aa7d5
08e5f8f4f69fbeabf6340c5094a824952f014325
8304e371eff46389acf84c250dbb95af7087d260
/sports_team_system/catalog/migrations/0016_auto_20200607_2019.py
8e6f4a76e130a18ecf1eca058b40590a4cfb6f52
[]
no_license
COYADI/System-Analysis
601dbda423ce6e1549ade2c8864dd53b1ae346d6
308b19f13123edeba4f53b91f2a76d3305b39813
refs/heads/master
2022-11-02T21:04:55.664105
2020-06-11T03:24:20
2020-06-11T03:24:20
254,568,785
0
15
null
2020-06-08T11:33:55
2020-04-10T07:12:24
HTML
UTF-8
Python
false
false
1,041
py
# Generated by Django 3.0.5 on 2020-06-07 12:19 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0015_auto_20200607_2018'), ] operations = [ migrations.AlterField( model_name='noticing', name='create_time', field=models.DateTimeField(default=datetime.datetime(2020, 6, 7, 20, 19, 20, 812109)), ), migrations.AlterField( model_name='training', name='create_time', field=models.DateTimeField(default=datetime.datetime(2020, 6, 7, 20, 19, 20, 808117)), ), migrations.AlterField( model_name='voting', name='create_time', field=models.DateTimeField(default=datetime.datetime(2020, 6, 7, 20, 19, 20, 810108)), ), migrations.AlterField( model_name='voting', name='expire_time', field=models.DateTimeField(blank=True, null=True), ), ]
[ "b06705020@ntu.edu.tw" ]
b06705020@ntu.edu.tw
4a3ade146a01bc93108ba525a191d0f4fc777c9b
811f4cdb25e26f3b27640aaa2e2bca93e660d2d7
/src/anomalib/models/components/flow/all_in_one_block.py
f2ab1e17c372351bdd22788c8bdee20d621f06a3
[ "CC-BY-SA-4.0", "CC-BY-SA-3.0", "CC-BY-NC-SA-4.0", "Python-2.0", "Apache-2.0" ]
permissive
openvinotoolkit/anomalib
4467dfc392398845e816387267cdf979ff76fe15
4abfa93dcfcb98771bc768b334c929ff9a02ce8b
refs/heads/main
2023-09-03T16:49:05.019269
2023-08-28T14:22:19
2023-08-28T14:22:19
423,775,360
2,325
454
Apache-2.0
2023-09-14T11:21:33
2021-11-02T09:11:38
Python
UTF-8
Python
false
false
12,649
py
"""All In One Block Layer.""" # Copyright (c) https://github.com/vislearn/FrEIA # SPDX-License-Identifier: MIT # Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import warnings from typing import Callable import torch import torch.nn.functional as F from FrEIA.modules import InvertibleModule from scipy.stats import special_ortho_group from torch import Tensor, nn def _global_scale_sigmoid_activation(input: Tensor) -> Tensor: """Global scale sigmoid activation. Args: input (Tensor): Input tensor Returns: Tensor: Sigmoid activation """ return 10 * torch.sigmoid(input - 2.0) def _global_scale_softplus_activation(input: Tensor) -> Tensor: """Global scale softplus activation. Args: input (Tensor): Input tensor Returns: Tensor: Softplus activation """ softplus = nn.Softplus(beta=0.5) return 0.1 * softplus(input) def _global_scale_exp_activation(input: Tensor) -> Tensor: """Global scale exponential activation. Args: input (Tensor): Input tensor Returns: Tensor: Exponential activation """ return torch.exp(input) class AllInOneBlock(InvertibleModule): """Module combining the most common operations in a normalizing flow or similar model. It combines affine coupling, permutation, and global affine transformation ('ActNorm'). It can also be used as GIN coupling block, perform learned householder permutations, and use an inverted pre-permutation. The affine transformation includes a soft clamping mechanism, first used in Real-NVP. The block as a whole performs the following computation: .. math:: y = V\\,R \\; \\Psi(s_\\mathrm{global}) \\odot \\mathrm{Coupling}\\Big(R^{-1} V^{-1} x\\Big)+ t_\\mathrm{global} - The inverse pre-permutation of x (i.e. :math:`R^{-1} V^{-1}`) is optional (see ``reverse_permutation`` below). - The learned householder reflection matrix :math:`V` is also optional all together (see ``learned_householder_permutation`` below). - For the coupling, the input is split into :math:`x_1, x_2` along the channel dimension. Then the output of the coupling operation is the two halves :math:`u = \\mathrm{concat}(u_1, u_2)`. .. math:: u_1 &= x_1 \\odot \\exp \\Big( \\alpha \\; \\mathrm{tanh}\\big( s(x_2) \\big)\\Big) + t(x_2) \\\\ u_2 &= x_2 Because :math:`\\mathrm{tanh}(s) \\in [-1, 1]`, this clamping mechanism prevents exploding values in the exponential. The hyperparameter :math:`\\alpha` can be adjusted. """ def __init__( self, dims_in, dims_c=[], subnet_constructor: Callable | None = None, affine_clamping: float = 2.0, gin_block: bool = False, global_affine_init: float = 1.0, global_affine_type: str = "SOFTPLUS", permute_soft: bool = False, learned_householder_permutation: int = 0, reverse_permutation: bool = False, ): """ Args: subnet_constructor: class or callable ``f``, called as ``f(channels_in, channels_out)`` and should return a torch.nn.Module. Predicts coupling coefficients :math:`s, t`. affine_clamping: clamp the output of the multiplicative coefficients before exponentiation to +/- ``affine_clamping`` (see :math:`\\alpha` above). gin_block: Turn the block into a GIN block from Sorrenson et al, 2019. Makes it so that the coupling operations as a whole is volume preserving. global_affine_init: Initial value for the global affine scaling :math:`s_\mathrm{global}`. global_affine_init: ``'SIGMOID'``, ``'SOFTPLUS'``, or ``'EXP'``. Defines the activation to be used on the beta for the global affine scaling (:math:`\\Psi` above). permute_soft: bool, whether to sample the permutation matrix :math:`R` from :math:`SO(N)`, or to use hard permutations instead. Note, ``permute_soft=True`` is very slow when working with >512 dimensions. learned_householder_permutation: Int, if >0, turn on the matrix :math:`V` above, that represents multiple learned householder reflections. Slow if large number. Dubious whether it actually helps network performance. reverse_permutation: Reverse the permutation before the block, as introduced by Putzky et al, 2019. Turns on the :math:`R^{-1} V^{-1}` pre-multiplication above. """ super().__init__(dims_in, dims_c) channels = dims_in[0][0] # rank of the tensors means 1d, 2d, 3d tensor etc. self.input_rank = len(dims_in[0]) - 1 # tuple containing all dims except for batch-dim (used at various points) self.sum_dims = tuple(range(1, 2 + self.input_rank)) if len(dims_c) == 0: self.conditional = False self.condition_channels = 0 else: assert tuple(dims_c[0][1:]) == tuple( dims_in[0][1:] ), f"Dimensions of input and condition don't agree: {dims_c} vs {dims_in}." self.conditional = True self.condition_channels = sum(dc[0] for dc in dims_c) split_len1 = channels - channels // 2 split_len2 = channels // 2 self.splits = [split_len1, split_len2] try: self.permute_function = {0: F.linear, 1: F.conv1d, 2: F.conv2d, 3: F.conv3d}[self.input_rank] except KeyError: raise ValueError(f"Data is {1 + self.input_rank}D. Must be 1D-4D.") self.in_channels = channels self.clamp = affine_clamping self.GIN = gin_block self.reverse_pre_permute = reverse_permutation self.householder = learned_householder_permutation if permute_soft and channels > 512: warnings.warn( ( "Soft permutation will take a very long time to initialize " f"with {channels} feature channels. Consider using hard permutation instead." ) ) # global_scale is used as the initial value for the global affine scale # (pre-activation). It is computed such that # global_scale_activation(global_scale) = global_affine_init # the 'magic numbers' (specifically for sigmoid) scale the activation to # a sensible range. if global_affine_type == "SIGMOID": global_scale = 2.0 - torch.log(torch.tensor([10.0 / global_affine_init - 1.0])) self.global_scale_activation = _global_scale_sigmoid_activation elif global_affine_type == "SOFTPLUS": global_scale = 2.0 * torch.log(torch.exp(torch.tensor(0.5 * 10.0 * global_affine_init)) - 1) self.global_scale_activation = _global_scale_softplus_activation elif global_affine_type == "EXP": global_scale = torch.log(torch.tensor(global_affine_init)) self.global_scale_activation = _global_scale_exp_activation else: raise ValueError('Global affine activation must be "SIGMOID", "SOFTPLUS" or "EXP"') self.global_scale = nn.Parameter(torch.ones(1, self.in_channels, *([1] * self.input_rank)) * global_scale) self.global_offset = nn.Parameter(torch.zeros(1, self.in_channels, *([1] * self.input_rank))) if permute_soft: w = special_ortho_group.rvs(channels) else: indices = torch.randperm(channels) w = torch.zeros((channels, channels)) w[torch.arange(channels), indices] = 1.0 if self.householder: # instead of just the permutation matrix w, the learned housholder # permutation keeps track of reflection vectors vk, in addition to a # random initial permutation w_0. self.vk_householder = nn.Parameter(0.2 * torch.randn(self.householder, channels), requires_grad=True) self.w_perm = None self.w_perm_inv = None self.w_0 = nn.Parameter(torch.FloatTensor(w), requires_grad=False) else: self.w_perm = nn.Parameter( torch.FloatTensor(w).view(channels, channels, *([1] * self.input_rank)), requires_grad=False ) self.w_perm_inv = nn.Parameter( torch.FloatTensor(w.T).view(channels, channels, *([1] * self.input_rank)), requires_grad=False ) if subnet_constructor is None: raise ValueError("Please supply a callable subnet_constructor" "function or object (see docstring)") self.subnet = subnet_constructor(self.splits[0] + self.condition_channels, 2 * self.splits[1]) self.last_jac = None def _construct_householder_permutation(self): """Computes a permutation matrix from the reflection vectors that are learned internally as nn.Parameters.""" w = self.w_0 for vk in self.vk_householder: w = torch.mm(w, torch.eye(self.in_channels).to(w.device) - 2 * torch.ger(vk, vk) / torch.dot(vk, vk)) for i in range(self.input_rank): w = w.unsqueeze(-1) return w def _permute(self, x, rev=False): """Performs the permutation and scaling after the coupling operation. Returns transformed outputs and the LogJacDet of the scaling operation.""" if self.GIN: scale = 1.0 perm_log_jac = 0.0 else: scale = self.global_scale_activation(self.global_scale) perm_log_jac = torch.sum(torch.log(scale)) if rev: return ((self.permute_function(x, self.w_perm_inv) - self.global_offset) / scale, perm_log_jac) else: return (self.permute_function(x * scale + self.global_offset, self.w_perm), perm_log_jac) def _pre_permute(self, x, rev=False): """Permutes before the coupling block, only used if reverse_permutation is set""" if rev: return self.permute_function(x, self.w_perm) else: return self.permute_function(x, self.w_perm_inv) def _affine(self, x, a, rev=False): """Given the passive half, and the pre-activation outputs of the coupling subnetwork, perform the affine coupling operation. Returns both the transformed inputs and the LogJacDet.""" # the entire coupling coefficient tensor is scaled down by a # factor of ten for stability and easier initialization. a *= 0.1 ch = x.shape[1] sub_jac = self.clamp * torch.tanh(a[:, :ch]) if self.GIN: sub_jac -= torch.mean(sub_jac, dim=self.sum_dims, keepdim=True) if not rev: return (x * torch.exp(sub_jac) + a[:, ch:], torch.sum(sub_jac, dim=self.sum_dims)) else: return ((x - a[:, ch:]) * torch.exp(-sub_jac), -torch.sum(sub_jac, dim=self.sum_dims)) def forward(self, x, c=[], rev=False, jac=True): """See base class docstring""" if self.householder: self.w_perm = self._construct_householder_permutation() if rev or self.reverse_pre_permute: self.w_perm_inv = self.w_perm.transpose(0, 1).contiguous() if rev: x, global_scaling_jac = self._permute(x[0], rev=True) x = (x,) elif self.reverse_pre_permute: x = (self._pre_permute(x[0], rev=False),) x1, x2 = torch.split(x[0], self.splits, dim=1) if self.conditional: x1c = torch.cat([x1, *c], 1) else: x1c = x1 if not rev: a1 = self.subnet(x1c) x2, j2 = self._affine(x2, a1) else: a1 = self.subnet(x1c) x2, j2 = self._affine(x2, a1, rev=True) log_jac_det = j2 x_out = torch.cat((x1, x2), 1) if not rev: x_out, global_scaling_jac = self._permute(x_out, rev=False) elif self.reverse_pre_permute: x_out = self._pre_permute(x_out, rev=True) # add the global scaling Jacobian to the total. # trick to get the total number of non-channel dimensions: # number of elements of the first channel of the first batch member n_pixels = x_out[0, :1].numel() log_jac_det += (-1) ** rev * n_pixels * global_scaling_jac return (x_out,), log_jac_det def output_dims(self, input_dims): return input_dims
[ "noreply@github.com" ]
openvinotoolkit.noreply@github.com
adcb107a99607a4473a99cbe4a62c8ecc5918f4d
f71118a9f24e09bba18d021f9c4a43a97dc4dead
/codes/scripts/make_gif_video.py
fc81e5647ff7ce75b5bb35f226bce946a93a1d56
[ "Apache-2.0" ]
permissive
BlueAmulet/BasicSR
d7420fd9d7b73bf0cd90a3201d84393f262e63be
7040913d8659a05af4c2428feb71c260efbf1e9c
refs/heads/lite
2021-07-10T14:48:26.037589
2020-07-23T01:59:27
2020-07-23T01:59:27
196,041,187
19
9
Apache-2.0
2020-09-01T17:39:00
2019-07-09T16:00:14
Python
UTF-8
Python
false
false
3,311
py
""" Add text to images, then make gif/video sequence from images. Since the created gif has low quality with color issues, use this script to generate image with text and then use `gifski`. Call `ffmpeg` to make video. """ import os.path import numpy as np import cv2 crt_path = os.path.dirname(os.path.realpath(__file__)) # configurations img_name_list = ['x1', 'x2', 'x3', 'x4', 'x5'] ext = '.png' text_list = ['1', '2', '3', '4', '5'] h_start, h_len = 0, 576 w_start, w_len = 10, 352 enlarge_ratio = 1 txt_pos = (10, 50) # w, h font_size = 1.5 font_thickness = 4 color = 'red' duration = 0.8 # second use_imageio = False # use imageio to make gif make_video = False # make video using ffmpeg is_crop = True if h_start == 0 or w_start == 0: is_crop = False # do not crop img_name_list = [x + ext for x in img_name_list] input_folder = os.path.join(crt_path, './ori') save_folder = os.path.join(crt_path, './ori') color_tb = {} color_tb['yellow'] = (0, 255, 255) color_tb['green'] = (0, 255, 0) color_tb['red'] = (0, 0, 255) color_tb['magenta'] = (255, 0, 255) color_tb['matlab_blue'] = (189, 114, 0) color_tb['matlab_orange'] = (25, 83, 217) color_tb['matlab_yellow'] = (32, 177, 237) color_tb['matlab_purple'] = (142, 47, 126) color_tb['matlab_green'] = (48, 172, 119) color_tb['matlab_liblue'] = (238, 190, 77) color_tb['matlab_brown'] = (47, 20, 162) color = color_tb[color] img_list = [] # make temp dir if not os.path.exists(save_folder): os.makedirs(save_folder) print('mkdir [{}] ...'.format(save_folder)) if make_video: # tmp folder to save images for video tmp_video_folder = os.path.join(crt_path, '_tmp_video') if not os.path.exists(tmp_video_folder): os.makedirs(tmp_video_folder) idx = 0 for img_name, write_txt in zip(img_name_list, text_list): img = cv2.imread(os.path.join(input_folder, img_name), cv2.IMREAD_UNCHANGED) base_name = os.path.splitext(img_name)[0] print(base_name) # crop image if is_crop: print('Crop image ...') if img.ndim == 2: img = img[h_start:h_start + h_len, w_start:w_start + w_len] elif img.ndim == 3: img = img[h_start:h_start + h_len, w_start:w_start + w_len, :] else: raise ValueError('Wrong image dim [{:d}]'.format(img.ndim)) # enlarge img if necessary if enlarge_ratio > 1: H, W, _ = img.shape img = cv2.resize(img, (W * enlarge_ratio, H * enlarge_ratio), \ interpolation=cv2.INTER_CUBIC) # add text font = cv2.FONT_HERSHEY_COMPLEX cv2.putText(img, write_txt, txt_pos, font, font_size, color, font_thickness, cv2.LINE_AA) cv2.imwrite(os.path.join(save_folder, base_name + '_text.png'), img) if make_video: idx += 1 cv2.imwrite(os.path.join(tmp_video_folder, '{:05d}.png'.format(idx)), img) img = np.ascontiguousarray(img[:, :, [2, 1, 0]]) img_list.append(img) if use_imageio: import imageio imageio.mimsave(os.path.join(save_folder, 'out.gif'), img_list, format='GIF', duration=duration) if make_video: os.system('ffmpeg -r {:f} -i {:s}/%05d.png -vcodec mpeg4 -y {:s}/movie.mp4'.format( 1 / duration, tmp_video_folder, save_folder)) if os.path.exists(tmp_video_folder): os.system('rm -rf {}'.format(tmp_video_folder))
[ "wxt1994@126.com" ]
wxt1994@126.com
65c961193678438ef37cfc7bff2d0c2383ddd805
d767da4400de5b0d17bab56eeb678b4ff1052913
/harifile.py
1b506a1cd942ed997fb8479f420f87147594750d
[]
no_license
HARI5KRISHNAN/newproject
9b792f8960bb0656b8e82e9d4a15284f0e72aff1
d3dec2ce5b025e730157cf83d9df82278d9dda93
refs/heads/master
2021-01-05T05:00:00.639829
2020-02-16T12:34:21
2020-02-16T12:34:21
240,888,234
0
0
null
null
null
null
UTF-8
Python
false
false
28
py
print("welocme to eduerka")
[ "root@ip-172-31-25-170.ap-southeast-1.compute.internal" ]
root@ip-172-31-25-170.ap-southeast-1.compute.internal
d9cb619d465d33a6f910d50958beb4ca360e904b
47a15501446aa286f89e9ac0f751945d6b86829b
/bqdc.py
261399d44024c3c85083a7f55f72e7373b1f8f09
[ "MIT" ]
permissive
karlo0/bqdc
219ddbf71c0b85a4419eb2759c3a7b57c87afe33
1aca9dcd2c519e9ade1988bdee47cf98d51c10f8
refs/heads/master
2023-08-24T00:42:19.044385
2023-08-14T23:43:35
2023-08-17T22:18:04
203,542,535
0
0
MIT
2023-08-17T22:18:05
2019-08-21T08:39:04
Python
UTF-8
Python
false
false
51,143
py
r""" bqdc.py Python Module to download, upload metadata (Datacatalog Tags, BigQuery table, field descriptions and schema) from Bigquery Tables and its attached tags in DataCatalog. It can synchronize table descriptions and field descriptions from within Bigquery and constructs tags in Datacatalog for this metadata. The main funcions are the following: - The download function stores metadata in an Excel .xlsx file - The upload function uses the metadata from an Excel .xlsx file (e.g. obtained from a previous download which has since then been updated) and uploads it to BigQuery and DataCatalog - The synchronize function downloads the metadata and uploads it again to BigQuery and DataCatalog. This can be used to synchronize table and field description metadata that is found in one of the two GCP apps to upload it to the other too, if it has not been there before Please check the jupyter notebooks for more detailed information. The module can only be used when the following conditions are met: - 2 tag templates in DataCatalog are specified: - A tag template that is used to attach tags to whole BigQuery tables, in the following referred to as table tag template - A tag template that is used to attach tags to fields of BigQuery tables, in the following referred to as field tag template - The table tag template is required to have an attribute with key name 'table_description', that is intended to store table descriptions similar to the attribute 'description' of the BigQuery 'Table' class - The field tag template is required to have an attribute with key name 'field_description', that is intended to store field/column descriptions similar to the attribute 'description' of the BigQuery 'SchemaField' class Version: 0.1 Author: Karsten Leonhardt Date: 21.08.2019 """ # Connect to the Google Data Catalog python modul from google.cloud import datacatalog_v1beta1 # Connect to the Google BigQuery python modul from google.cloud import bigquery # Connect to the Google Authentification python modul from google.oauth2 import service_account import pandas as pd from collections import OrderedDict import os import shutil import re import glob from functools import reduce class clients: type_table_ref_bq = bigquery.TableReference # BigQuery maximum string length bq_max_string_length = 1024 # DataCatalog maximum string length dc_max_string_length = 2000 # the current path CDIR = os.path.dirname(os.path.realpath(__file__)) def __init__(self, PROJECT_ID, PATH_SERVICE_ACCOUNT_KEY): self.P_ID = PROJECT_ID self.DS_ID = None """get credentials through service account file""" self.credentials = service_account.Credentials.from_service_account_file(PATH_SERVICE_ACCOUNT_KEY) """establish a datacatalog client""" self.dc_client = datacatalog_v1beta1.DataCatalogClient(credentials=self.credentials) """establish a BigQuery client""" self.bq_client = bigquery.Client(project=PROJECT_ID, credentials = self.credentials) class toolbox(clients): pattern_table_descr_bq_pure = re.compile(r"(?P<descr>^[\s\S]*?)\s*Table attributes") # max length of sheet names in Excel excel_max_sheet_name_length = 31 overview_sheet_name = 'metadata_of_tables' def __init__(self, PROJECT_ID, PATH_SERVICE_ACCOUNT_KEY = None, prefer_bq_for_downlad_update = True, logfile = '', do_print_log = False): """ This class establishes a connection to both Bigquery and Datacatalog clients and allows for the manipulation and creation of tags in Datacatalog attached to Bigquery tables and the manipulation of BigQuery table schemas. Parameters: ----------- PROJECT_ID: String Specifies the GCP Project ID of which resources in BigQuery and Datacatalog are requested. PATH_SERVICE_ACCOUNT_KEY: String, None (Default) The full path to the Json file containing the service account key. If no string is provided, it searches for a .json file in the current directory and tries to connect to the BQ and DC clients with this file. prefer_bq_for_download_update: False, True (Default) When set to true, the table description of BQ is prefered over the DC table description when it exists. logfile: String, '' (Default) When the specified string is not empty it will created in the current directory a logfile with the specified string as name. If not provided, no logfile is written do_print_log: True, False (Default) if 'True' print log status messages to the stdout aka the screen Return: ------- Instance of class 'toolbox' """ assert isinstance(PROJECT_ID, str), "The 'PROJECT_ID' argument requires a string to specify the project ID to the GCP project for which BigQuery and DataCatalog resources are requested." if PATH_SERVICE_ACCOUNT_KEY is None: service_key_list = glob.glob('*.json') if len(service_key_list) == 1: PATH_SERVICE_ACCOUNT_KEY = os.path.join(self.CDIR, service_key_list[0]) elif len(service_key_list) == 0: raise Exception("No service account key found in the current folder. Please initialise the object with the 'PATH_SERVICE_ACCOUNT_KEY' argument set to the full path (including the json filename with .json extension) of the service account key") else: raise Exception("There are more than one .json files in the current folder. Please initialise the object with the 'PATH_SERVICE_ACCOUNT_KEY' argument set to the full path (including the json filename with .json extension) of the service account key") super().__init__(PROJECT_ID, PATH_SERVICE_ACCOUNT_KEY) self.sheet = None self.ds_table_tags_df = None self.ds_field_tags_dicts = None self.table_instance_dc = None self.table_instance_bq = None self.__table_id = None self.__table_id_dc = '' self.__prefer_bq_for_downlad_update = prefer_bq_for_downlad_update self.__update = False self.__do_print_log = do_print_log if len(logfile) > 0: self.__do_log = True self.__log = '' self.__logfile = logfile else: self.__do_log = False def init_tag_templates(self, table_tag_template_str = None, field_tag_template_str = None, LOCATION_TAGS = 'us-central1', table_tag_fields_keys_ordered = [], field_tag_fields_keys_ordered = []): """ Initializes tag templates. The whole class requires 2 tag templates: - a tag template whose id is specified by the 'table_tag_template_str' argument and which is used to attach tags to tables themselves - a tag template whose id is specified by the 'field_tag_template_str' argument and which is used to attach tags to fields of tables table_tag_template_str: String, None (Default) specifies an ID of a tag template that is used to attach tags to tables. The default is None, however the initialisation fails when no string is provided field_tag_template_str: String, None (Default) specifies an ID of a tag template that is used to attach tags to fields of tables. The default is None, however the initialisation fails when no string is provided LOCATION_TAGS: String, 'us-central1' (Default) The location of the tags. At the moment only 'us-central1' is supported table_tag_fields_keys_ordered: List of Strings, Empty lis (Default) A list of the table tag template attribute keys ordered in a list. If this is not provided the internal ordering of the attribute keys is used to set up DataFrame columns field_tag_fields_keys_ordered: List of Strings, Empty lis (Default) A list of the field tag template attribute keys ordered in a list. If this is not provided the internal ordering of the attribute keys is used to set up DataFrame columns """ assert isinstance(table_tag_template_str, str), "A string must be passed for the 'table_tag_template_str' argument to specify an ID of a tag template that is used to attach tags to tables" assert isinstance(field_tag_template_str, str), "A string must be passed for the 'field_tag_template_str' argument to specify an ID of a tag template that is used to attach tags to fields of tables" self.TABLE_TAG_TEMPLATE_STR = table_tag_template_str self.FIELD_TAG_TEMPLATE_STR = field_tag_template_str TABLE_TAG_TEMPLATE_PATH=self.dc_client.tag_template_path(self.P_ID, LOCATION_TAGS, self.TABLE_TAG_TEMPLATE_STR) FIELD_TAG_TEMPLATE_PATH=self.dc_client.tag_template_path(self.P_ID, LOCATION_TAGS, self.FIELD_TAG_TEMPLATE_STR) try: self.table_tag_template = self.dc_client.get_tag_template(TABLE_TAG_TEMPLATE_PATH) except: msg = "Referencing the tag template used for attaching tags to whole tables failed" raise Exception(msg) try: self.field_tag_template = self.dc_client.get_tag_template(FIELD_TAG_TEMPLATE_PATH) except: msg = "Referencing the tag template used for attaching tags to fields of tables failed" raise Exception(msg) assert 'table_description' in self.table_tag_template.fields.keys(), "The tag template used for attaching tags to whole tables must contain an attribute with key ID = 'table_description'" assert 'field_description' in self.field_tag_template.fields.keys(), "The tag template used for attaching tags to fields of tables must contain an attribute with key ID = 'field_description'" self.__table_tag_fields_keys_ordered = self.__check_complete_ordered_list_of_keys(table_tag_fields_keys_ordered, self.table_tag_template.fields.keys()) self.__field_tag_fields_keys_ordered = self.__check_complete_ordered_list_of_keys(field_tag_fields_keys_ordered, self.field_tag_template.fields.keys()) self.__field_keys_to_ndx = {field_keys: k for k, field_keys in enumerate(self.__field_tag_fields_keys_ordered)} self.__upload_table_description_bq_init() pass def __check_complete_ordered_list_of_keys(self, ordered_keys_in, keys): set_keys_intersect = set(ordered_keys_in).intersection(set(keys)) set_remaining_keys = set(keys) - set_keys_intersect ordered_keys = [key for key in ordered_keys_in if key in set_keys_intersect] for key in set_remaining_keys: ordered_keys.append(key) return ordered_keys def set_dataset(self, DS_ID): self.DS_ID = DS_ID pass def get_table_instance_dc(self, table_id, return_instance = False): resource_name = "//bigquery.googleapis.com/projects/{}/datasets/{}/tables/{}".format(self.P_ID, self.DS_ID, table_id) self.table_instance_dc = self.dc_client.lookup_entry(linked_resource=resource_name) if self.__table_id != table_id: self.__table_id = table_id if return_instance: return self.table_instance_dc else: pass def get_table_instance_bq(self, table_x, return_instance = False): if(isinstance(table_x, self.type_table_ref_bq)): self.table_instance_bq = self.bq_client.get_table(table_x) elif(isinstance(table_x, str)): try: self.table_instance_bq = self.bq_client.get_table(self.P_ID+'.'+self.DS_ID+'.'+table_x) except: raise Exception('The table can not be found under the specified PROJECT_ID/DATASET_ID') pass else: raise Exception('String or table_reference required as argument') if self.__table_id != self.table_instance_bq.table_id: self.__table_id = self.table_instance_bq.table_id self.get_bq_schema_metadata() if return_instance: return self.table_instance_bq else: pass def list_all_tags_entry(self, entry = None): """ Prints all the tags attached to an entry (here an entry is a table instance) """ if entry is None: entry = self.table_instance_dc if entry is not None: for tag in self.dc_client.list_tags(entry.name): print(tag) else: raise Exception('\nNo datacatalog entry instance provided. Call method again as ''list_all_tags_entry(entry)'' with entry a datacatalog entry instance') pass def get_all_tags_table(self, entry = None, delete_tags_not_in_bq_schema = False, make_field_sheet_df = False): if entry is None: entry = self.table_instance_dc if entry is not None: tags = self.dc_client.list_tags(entry.name) update_table_instance_bq = False try: if self.__table_id != self.table_instance_bq.table_id: update_table_instance_bq = True except: update_table_instance_bq = True if update_table_instance_bq: self.get_table_instance_bq(self.__table_id) tag_columns = [] tag_list = [] if make_field_sheet_df: field_vals = [[] for i in range(len(self.__field_keys_to_ndx))] field_names = [] for tag in tags: if tag.template == self.field_tag_template.name: tag_column_lower = tag.column.lower() if tag_column_lower in self.schema_bq_df.index: tag_columns.append(tag_column_lower) tag_list.append(tag) if make_field_sheet_df: field_names.append(tag_column_lower) for attr in self.__field_keys_to_ndx.keys(): if attr in tag.fields.keys(): field_vals[self.__field_keys_to_ndx[attr]].append(tag.fields[attr].string_value) else: field_vals[self.__field_keys_to_ndx[attr]].append('') else: if delete_tags_not_in_bq_schema: self.dc_client.delete_tag(tag.name) else: tag_columns.append(tag.column) tag_list.append(tag) if make_field_sheet_df: field_tags_df = pd.DataFrame.from_dict(dict(zip(self.__field_tag_fields_keys_ordered, field_vals))).set_index(pd.Index(field_names)).applymap(lambda x: '' if x is None else x).astype(str).fillna('') self.sheet = self.schema_bq_df.join(field_tags_df,lsuffix='_bq', rsuffix='_dc').fillna('') n_cols = len(self.sheet.columns) self.sheet.insert(n_cols - 1,'field_description', [ row['field_description_dc'] if ( row['field_description_bq'] is None or len(row['field_description_bq']) == 0 ) else row['field_description_bq'] if ( len(row['field_description_dc']) == 0 or len(row['field_description_dc']) < len(row['field_description_bq']) ) else row['field_description_bq']+row['field_description_dc'][self.bq_max_string_length:] if len(row['field_description_bq']) == self.bq_max_string_length else row['field_description_dc'] for index, row in self.sheet.iterrows() ]) self.sheet = self.sheet.drop(columns=['field_description_dc', 'field_description_bq']).astype(str).fillna('').set_index('field_name') self.tags = dict(zip(tag_columns, tag_list)) if len(self.tags) == 0: self.tags = None else: raise Exception('\nNo datacatalog entry instance provided. Call method again as ''list_all_tags_entry(entry)'' with entry a datacatalog entry instance') pass def lookup_and_list_all_tags_entry(self, table_id): self.list_all_tags_entry(self.get_table_instance_dc(table_id)) pass def delete_all_tags_entry(self, entry = None): """ Deletes all the tags attached to an entry (here an entry is a table instance) """ if entry is None: entry = self.table_instance_dc if entry is not None: for tag in self.dc_client.list_tags(entry.name): self.dc_client.delete_tag(tag.name) else: raise Exception('\nNo datacatalog entry instance provided. Call method again as ''delete_all_tags_entry(entry)'' with entry a datacatalog entry instance') pass def get_bq_schema_metadata(self, table_instance_bq = None): if table_instance_bq is None: table_instance_bq = self.table_instance_bq if table_instance_bq is not None: self.schema_bq = table_instance_bq.schema[:] self.schema_bq_df = pd.DataFrame.from_records((schemafield._key()[0:4] for schemafield in self.schema_bq), columns = ['field_name', 'field_type', 'field_mode', 'field_description']).applymap(lambda x: '' if x is None else x).astype('str').assign(field_name_lower=lambda x: x.field_name.apply(lambda y: y.lower())).set_index('field_name_lower').fillna('') else: raise Exception('\nNo BigQuery table instance provided. Call method again as ''get_bq_schema_metadata(entry)'' with entry a BigQuery table instance') pass def update_field_tag(self, field_entry_dict, table_instance_dc = None, dict_tags = None): """ This function tries to find a field tag with a column field (which is the actual table field name \ and in the code below accessed by tag.column) equals the requested field name as specified with \ field_entry_dict['field_name']. If such a tag can be found in the DataCatalog for the table instance, then it checks whether the \ field attributes ( specified as the field values of the tag.fields[key] below, where key is a specific \ tag field attribute name (field_format, field_description, field_example)) of the DataCatalog tag have \ different values as the requested/new tag field attributes (which are specified as the values of \ field_entry_dict['field_attributes'][key] where key is again a tag field attribute name) Only if the new field attribute values differ from the ones in the tag already on Datacatalog, the tag will be updated. The function returns: - True: when the tag has either been updated or does not need to be updated - False: when the requested tag has not been found, indictating the tag needs to be newly created """ if table_instance_dc is None: table_instance_dc = self.table_instance_dc if dict_tags is None: dict_tags = self.tags found_tag = False if dict_tags is not None: field_name = field_entry_dict['field_name'] try: tag = dict_tags[field_name] found_tag = True except KeyError: pass update_tag = False if found_tag: for key, value in field_entry_dict['field_attributes'].items(): if len(value) > 0: if key in self.field_tag_template.fields.keys(): if tag.fields[key].string_value != value: tag.fields[key].string_value = value update_tag = True if update_tag: self.dc_client.update_tag(tag) return found_tag def create_field_tag(self, field_entry_dict, table_instance_dc = None, dict_tags = None): """ This function creates a field tag for a table instance (which is not the table name! \ An instance object is return by the datacatalog.lookup_entry function and the name member of that instance is used as the parent when creating the tag with datacatalog.create_tag. Input: - table_instance_dc: an instance of a table (we get the instance via the lookup_entry method\ of the datacatalog_v1beta1.DataCatalogClient class) - field_entry_dict: a dictionary containg the field attributes and corresponding values of the sadc_fieldstored as a dic """ if table_instance_dc is None: table_instance_dc = self.table_instance_dc if dict_tags is None: dict_tags = self.tags if(not self.update_field_tag(field_entry_dict, table_instance_dc = table_instance_dc, dict_tags = dict_tags)): new_field_tag = datacatalog_v1beta1.types.Tag() new_field_tag.template = self.field_tag_template.name create_tag = False field_name = field_entry_dict['field_name'] if(field_name != ''): for key, value in field_entry_dict['field_attributes'].items(): if len(value) > 0: if key in self.field_tag_template.fields.keys(): new_field_tag.fields[key].string_value = value create_tag = True if(create_tag): new_field_tag.column = field_name if create_tag: try: self.dc_client.create_tag(parent=table_instance_dc.name,tag=new_field_tag) except: self.to_log('\t\tProblem to write tag to field {} of table {}\n'.format(field_name, self.__table_id)) pass def update_table_tag(self, table_entry_dict, table_instance_dc = None, dict_tags = None): """ This function tries to find a table tag for the table instance. If such a tag can be found in the DataCatalog, then it checks whether the field attributes \ ( specified as the field values of the tag.fields[key] below, where key is a specific \ tag field attribute name (table_description, table_data_source)) of the DataCatalog tag have \ different values as the requested/new field attributes (which are specified as the values of \ table_entry_dict[key] where key is again a tag field attribute) Only if the new tag field attribute values differ from the ones in the tag already on Datacatalog, the tag will be updated. The function returns: - True: when the tag has either been updated or does not need to be updated - False: when the requested tag has not been found, indictating the tag needs to be newly created """ if table_instance_dc is None: table_instance_dc = self.table_instance_dc if dict_tags is None: dict_tags = self.tags found_tag = False if dict_tags is not None: try: tag = dict_tags[''] if tag.template == self.table_tag_template.name: found_tag = True except KeyError: pass update_tag = False if found_tag: for key, value in table_entry_dict.items(): if len(value) > 0: if key in self.table_tag_template.fields.keys(): if tag.fields[key].string_value != value: tag.fields[key].string_value = value update_tag = True if update_tag: self.dc_client.update_tag(tag) return found_tag def create_table_tag(self, table_entry_dict, table_instance_dc = None, dict_tags = None): if table_instance_dc is None: table_instance_dc = self.table_instance_dc if dict_tags is None: dict_tags = self.tags if(not self.update_table_tag(table_entry_dict, table_instance_dc, dict_tags)): new_table_tag = datacatalog_v1beta1.types.Tag() new_table_tag.template = self.table_tag_template.name create_tag = False for key, value in table_entry_dict.items(): if len(value) > 0: if key in self.table_tag_template.fields.keys(): new_table_tag.fields[key].string_value = value create_tag = True if create_tag: self.dc_client.create_tag(parent=table_instance_dc.name,tag=new_table_tag) pass def download(self, tables = None, DS_ID = None, PATH=None): """ Downloads metadata of tables in a dataset specified by DS_ID. - By default metadata for all tables in the dataset is downloaded in an Excel .xlsx file in a folder that has the name of the dataset. For each table a separate sheet of that .xlsx file is created containing the field_names, field_descriptions and more. - Specifying the parameter 'tables' allows to download metadata for a single or a list of tables. - For all tables in the dataset table tags metadata is written to a sheet with the name 'metadata_of_tables' - The PATH specifies the path where the metadata shall be written. Parameters ---------- tables: String, List of Strings, None (default) A String or List of Strings specifying the table_ids for which metadata should be downloaded. If not provided, metadata for all tables in the dataset is downloaded DS_ID: String, None (default) dataset_id for which metadata shall be downloaded. If no dataset_id is provided via DS_ID, the one specified by the member attribute .DS_ID is used which is by default 'sadc_generated'. PATH: String, None (default) The PATH where the metadata shall be written. """ assert isinstance(tables, list) or isinstance(tables, str) or tables is None, "'Tables' parameter must be String, List or None" assert isinstance(DS_ID, str) or DS_ID is None, "'DS_ID' parameter must be String or None" assert isinstance(PATH, str) or PATH is None, "'PATH' parameter must be String or None" DS_ID_old = self.DS_ID if DS_ID is None: DS_ID = self.DS_ID else: self.set_dataset(DS_ID) if DS_ID is not None: if not self.__update: self.to_log('# Download\n') if PATH is not None: PATH_OUT = os.path.join(PATH, DS_ID) else: PATH_OUT = os.path.join(self.CDIR, DS_ID) if not os.path.exists(PATH_OUT): os.makedirs(PATH_OUT) else: self.to_log('\n\t# Download\n') self.overview_sheet = construct_overview_sheet(self.table_tag_template, attributes = self.__table_tag_fields_keys_ordered) table_sheets = construct_table_sheets() if tables is None: tables = self.bq_client.list_tables("{}.{}".format(self.P_ID, self.DS_ID)) elif isinstance(tables, str): tables = [tables] for table in tables: try: self.__table_id = table.table_id except: self.__table_id = table self.to_log('\t{}'.format("Table '{}'".format(self.__table_id))) self.to_log('\t\t{}'.format('get BigQuery table instance')) self.get_table_instance_bq(self.__table_id) self.to_log('\t\t{}'.format('get DataCatalog table instance')) self.get_table_instance_dc(self.__table_id) self.to_log('\t\t{}'.format('get all tags and create dataframe with out of field tags and BigQuery schema')) self.get_all_tags_table(make_field_sheet_df = True) self.to_log('\t\t{}'.format('append fields dataframe to dict')) table_sheets.append(self.__table_id, self.sheet) self.to_log('\t\t{}'.format('append table tag to overview sheet variable')) self.append_to_overview_sheet() self.to_log('\n\t{}'.format('make Dictionary out of field metadata dataframes for all specified tables')) self.ds_field_tags_dicts = table_sheets.get_dict() self.to_log('\t{}'.format('make Dataframe out of table tag metadata for all specified tables')) self.ds_table_tags_df = self.overview_sheet.get_dataframe() if not self.__update: FULLPATH = os.path.join(PATH_OUT, DS_ID+'.xlsx') self.to_log('\twrite to {}\n'.format(FULLPATH)) with pd.ExcelWriter(FULLPATH) as writer: self.ds_table_tags_df.to_excel(writer, sheet_name=self.overview_sheet_name, header=True, index=True) for table_id, table_df in self.ds_field_tags_dicts.items(): table_df.to_excel(writer, sheet_name=self.shorten_string(table_id, self.excel_max_sheet_name_length), header=True, index=True) self.set_dataset(DS_ID_old) else: raise Exception("No Dataset specified. Please call the function as 'download(DS_ID=dataset_id)' again with dataset_id a string specifying a dataset ID") pass def append_to_overview_sheet(self): table_description_bq = self.table_instance_bq.description table_description_bq = self.clean_sentence_string(self.pure_table_description_bq(table_description_bq)) dict_table_descr_bq = None if len(table_description_bq) > 0: dict_table_descr_bq = {'table_description': table_description_bq} try: table_tag = self.tags[''] if self.__prefer_bq_for_downlad_update: if len(table_description_bq) > 0: self.overview_sheet.append(self.__table_id, table_tag, dict_table_descr_bq) else: self.overview_sheet.append(self.__table_id, table_tag) else: self.overview_sheet.append(self.__table_id, table_tag) except: self.overview_sheet.append(self.__table_id, alt_tag_vals = dict_table_descr_bq) pass def upload(self, tables = None, DS_ID = None, PATH = None, delete_old_tags_before_upload = False, delete_sheet_after_upload = True, upload_from_backup = False): """ uploads metadata of tables in a dataset specified by DS_ID. - By default metadata for all tables in the dataset is uploaded from an Excel .xlsx file in a folder that has the name of the dataset. For each table a separate sheet of that .xlsx file is created containing the field_names, field_descriptions and more. - Specifying the parameter 'tables' allows to download metadata for a single or a list of tables. - For all tables in the dataset table tags metadata is in a sheet with the name 'metadata_of_tables' - The PATH specifies the path where the Excel .xlsx file is contained. Parameters ---------- tables: String, List of Strings, None (default) A String or List of Strings specifying the table_ids for which metadata should be downloaded. If not provided, metadata for all tables in the dataset is downloaded DS_ID: String, None (default) dataset_id for which metadata shall be downloaded. If no dataset_id is provided via DS_ID, the one specified by the member attribute .DS_ID is used which is by default 'sadc_generated'. PATH: String, None (default) The PATH where the metadata shall be read from. delete_old_tags_before_upload: True, False (Default) If set to True it deletes all tags in the datacatalog for a table instance before writing new ones. If set False the tags in datacalog are updated with the new information but not deleted. delete_sheet_after_upload: False, True (Default) If True, the folder including the sheet that has been uploaded will be deleted. upload_from_backup: True, False (Default) if True, use the backup Excel sheets for upload """ assert isinstance(tables, list) or isinstance(tables, str) or tables is None, "'Tables' parameter must be String, List or None" assert isinstance(DS_ID, str) or DS_ID is None, "'DS_ID' parameter must be String or None" assert isinstance(PATH, str) or PATH is None, "'PATH' parameter must be String or None" DS_ID_old = self.DS_ID if DS_ID is None: DS_ID = self.DS_ID else: self.set_dataset(DS_ID) self.delete_old_tags_before_upload = delete_old_tags_before_upload if DS_ID is not None: if not self.__update: self.to_log('\n# Upload\n') if PATH is None: PATH = os.path.join(self.CDIR, DS_ID) if upload_from_backup: PATH = os.path.join(os.path.join(self.CDIR, 'backup_sheets'), DS_ID) excel_files = glob.glob(os.path.join(PATH, r"*.xlsx")) assert len(excel_files) > 0, "No .xlsx files under the path {}".format(PATH) FULLPATH = os.path.join(PATH, DS_ID+'.xlsx') try: self.ds_table_tags_df = pd.read_excel(FULLPATH, sheet_name=self.overview_sheet_name, index_col = 0, dtype = str).fillna('').astype(str).applymap(lambda x: x.strip()) except: msg = 'Reading {} was not successful. Check path and existence of file.'.format(FULLPATH) self.to_log('\t\n{}\n'.format(msg)) raise Exception(msg) if tables is None: tables = self.ds_table_tags_df.index.to_list() else: diff_keys_set = set(tables) - set(self.ds_table_tags_df.index) assert len(diff_keys_set) == 0, "The tables {} are not contained in the spreadsheet.".format(diff_keys_set) table_to_ndx = {table_id: k+1 for k, table_id in enumerate(self.ds_table_tags_df.index) if table_id in tables} self.ds_field_tags_dicts = pd.read_excel(FULLPATH, sheet_name=list(table_to_ndx.values()), index_col = 0, dtype = str) else: if tables is None: tables = self.ds_table_tags_df.index.to_list() else: diff_keys_set = set(tables) - set(self.ds_table_tags_df.index) assert len(diff_keys_set) == 0, "The tables {} are not contained in the spreadsheet.".format(diff_keys_set) self.to_log('\n\t# Upload\n') table_to_ndx = {table_id: table_id for table_id in self.ds_table_tags_df.index if table_id in tables} for table_id, k in table_to_ndx.items(): self.to_log('\t{}'.format("Table '{}'".format(table_id))) self.__table_id = table_id self.to_log('\t\t{}'.format('get BigQuery table instance')) self.get_table_instance_bq(table_id) self.to_log('\t\t{}'.format('get DataCatalog table instance')) self.get_table_instance_dc(table_id) self.to_log('\t\t{}'.format('get all tags')) self.get_all_tags_table(delete_tags_not_in_bq_schema=True) self.to_log('\t\t{}'.format('create table tag dictionary')) self.table_tag_dict = dict(self.ds_table_tags_df.loc[table_id]) self.to_log('\t\t{}'.format('upload table tag')) self.upload_table_tag() self.to_log('\t\t{}'.format('upload BigQuery table description')) self.__upload_table_description_bq() self.sheet = self.ds_field_tags_dicts[k].fillna('').astype(str).applymap(lambda x: x.strip()) self.to_log('\t\t{}'.format('upload BigQuery and DataCatalog field information')) self.upload_fields_sheet() if not self.__update and delete_sheet_after_upload and not upload_from_backup: shutil.rmtree(PATH) self.set_dataset(DS_ID_old) self.write_log() else: raise Exception("No Dataset specified. Please call the function as 'upload(DS_ID=dataset_id)' again with dataset_id a string specifying a dataset ID") pass def synchronize(self, tables = None, DS_ID = None): """ Synchronizes metadata between Bigquery and Datacatalog of tables in a dataset specified by DS_ID. - By default metadata for all tables in the dataset is downloaded in an Excel .xlsx file in a folder that has the name of the dataset. For each table a separate sheet of that .xlsx file is created containing the field_names, field_descriptions and more. - Specifying the parameter 'tables' allows to download metadata for a single or a list of tables. - For all tables in the dataset table tags metadata is written to a sheet with the name 'metadata_of_tables' Parameters ---------- tables: String, List of Strings, None (default) A String or List of Strings specifying the table_ids for which metadata should be downloaded. If not provided, metadata for all tables in the dataset is downloaded DS_ID: String, None (default) dataset_id for which metadata shall be downloaded. If no dataset_id is provided via DS_ID, the one specified by the member attribute .DS_ID is used which is by default 'sadc_generated'. """ assert isinstance(tables, list) or isinstance(tables, str) or tables is None, "'Tables' parameter must be String, List or None" assert isinstance(DS_ID, str) or DS_ID is None, "'DS_ID' parameter must be String or None" DS_ID_old = self.DS_ID if DS_ID is None: DS_ID = self.DS_ID else: self.set_dataset(DS_ID) if DS_ID is not None: self.to_log('\n# Synchronize\n') self.__update = True self.download(tables=tables, DS_ID = DS_ID) self.upload(tables=tables, DS_ID = DS_ID, delete_sheet_after_upload = False) self.__update = False else: raise Exception("No Dataset specified. Please call the function as 'synchronize(DS_ID=dataset_id)' again with dataset_id a string specifying a dataset ID") pass def upload_fields_sheet(self): for column_name, row in self.sheet.iterrows(): if len(column_name) > 0: try: # this tries to get a numeric key value for the column name by checking first whether\ # the column name is in the table schema of BQ # if it is not found means that this column field is no longer part of the schema # and skips over that entry num_index = self.schema_bq_df.index.get_loc(column_name.lower()) has_descr = False if 'field_description' in row.keys(): has_descr = True field_description = self.clean_sentence_string(row['field_description']) field_attributes_dc = {**{key: self.clean_string(row[key]) for key in row.keys() if key not in ['field_description']}, 'field_description': self.clean_sentence_string(row['field_description'])} else: field_attributes_dc = {key: self.clean_string(row[key]) for key in row.keys()} field_entry_dict = {'field_name': column_name.lower(), 'field_attributes': field_attributes_dc} self.create_field_tag(field_entry_dict) field_bq = self.schema_bq[num_index] field_bq_name = field_bq.name field_bq_field_type = field_bq.field_type field_bq_mode = field_bq.mode if has_descr: field_description_bq = self.shorten_string(field_description, self.bq_max_string_length) self.schema_bq[num_index] = bigquery.SchemaField(name=field_bq_name, field_type=field_bq_field_type, mode=field_bq_mode, description=field_description_bq) except KeyError: pass else: break self.check_non_matching_columns_bq_excel() self.table_instance_bq.schema = self.schema_bq num_trials = 1 update_schema = False while num_trials < 11 and not update_schema: try: self.table_instance_bq = self.bq_client.update_table(self.table_instance_bq, ["schema"]) update_schema = True except Exception as e: if hasattr(e, 'message'): err = e.message else: err = e num_trials = num_trials + 1 if num_trials == 11: self.to_log("\t\t\terror while trying to write schema to BigQuery:") self.to_log(err) self.to_log("\t\t\terror occured, this was the last attempt\n") else: self.to_log("\t\t\terror while trying to write schema to BigQuery:\n") self.to_log(err) self.to_log("\t\t\terror occured, start {}. attempt\n".format(num_trials)) pass def upload_table_tag(self): diff_keys_set = set(self.table_tag_dict.keys()) - set(self.table_tag_template.fields.keys()) assert len(diff_keys_set) == 0, "The attribute names {} are no attribute names of the tag template {}".format(diff_keys_set, self.table_tag_template.name) self.create_table_tag(self.table_tag_dict) def __upload_table_description_bq_init(self): """ This function is only executed during initialisation of the class instance to set parameter for the function upload_table_description_bq """ self.__table_attrs = [attr for attr in self.table_tag_template.fields.keys() if attr not in ['table_description']] max_str_len_extra_metadata_keys = reduce((lambda x,y: max(x,y)), map( lambda x: len(x) , self.table_tag_template.fields.keys()) ) self.__n_int_tab = 5 self.__max_n_tabs = (max_str_len_extra_metadata_keys+1)//self.__n_int_tab def __upload_table_description_bq(self): table_description = self.clean_sentence_string(self.table_tag_dict['table_description']) extra_metadata_string = '\n\nTable attributes:\n\n' has_extra_metadata = False for column in self.__table_attrs: if len(self.table_tag_dict[column]) > 0: has_extra_metadata = True column_first_part = column[6:9] if column[6:9] == 'gcp': column_first_part = 'GCP' else: column_first_part = column[6].upper() + column[7:9] n_tabs = self.__max_n_tabs - ((len(column)+1)//self.__n_int_tab) + 1 extra_metadata_string = extra_metadata_string + column_first_part \ + re.sub(r'_+',' ', column[9:]) + ":" + "\t"*n_tabs \ + self.table_tag_dict[column] if extra_metadata_string[-1] != '\n': extra_metadata_string = extra_metadata_string + "\n" if has_extra_metadata: self.table_instance_bq.description = table_description + extra_metadata_string else: self.table_instance_bq.description = table_description self.table_instance_bq = self.bq_client.update_table(self.table_instance_bq, ["description"]) pass def check_non_matching_columns_bq_excel(self, table_instance_dc = None, excel_column_names = None, bq_column_names = None): if table_instance_dc is None: table_instance_dc = self.table_instance_dc if excel_column_names is None: excel_column_names = self.sheet.index if bq_column_names is None: bq_column_names = self.schema_bq_df.index set_excel_column_fields = set(excel_column_names.map(lambda x: x.lower())) set_bq_column_fields = set(bq_column_names) set_not_in_bq = set_excel_column_fields.difference(set_bq_column_fields) set_not_in_excel = set_bq_column_fields.difference(set_excel_column_fields) if bool(set_not_in_bq) or bool(set_not_in_excel): self.to_log('\t\t\tFor the table at the BigQuery path\n \'{}\''.format(table_instance_dc.linked_resource)) self.to_log('\t\t\tIn the following list, entries prefixed with:') self.to_log('\t\t\t \'<\':\tare contained in the Excel spreadsheet but not in the BigQuery table schema (anymore).\n\t\t\tPlease delete them in the Excel spreadsheet!') self.to_log('\t\t\t \'>\':\tare contained in the BigQuery table schema but not in the Excel spreadsheet.\n\t\t\t\tPlease add them in the Excel spreadsheet!\n') if bool(set_not_in_bq): for column_name in set_not_in_bq: self.to_log('\t\t\t\t< {}'.format(column_name)) if bool(set_not_in_excel): if bool(set_not_in_bq): self.to_log('\n') for column_name in set_not_in_excel: self.to_log('\t\t\t\t> {}'.format(column_name)) def to_log(self, message = None): if isinstance(message, str): if self.__do_log: self.__log = self.__log + message if self.__do_print_log: print(message) pass def write_log(self): if self.__do_log: F = open(self.__logfile, "w") F.write(self.__log) self.__log = '' F.close() @staticmethod def clean_string(string): string = string.strip() if len(string) > 0: string = re.sub(r'\s+',' ', string) return string @classmethod def clean_sentence_string(cls, string): string = cls.clean_string(string) if len(string) > 0: string = string[0].upper() + string[1:] if string[-1] != r"." and string[-1] != r"]": string = string + r"." return string @staticmethod def shorten_string(string, n): if len(string) < n: return string else: return string[:n] @classmethod def pure_table_description_bq(cls, table_description_bq): if table_description_bq is not None: try: table_description_bq_pure = cls.pattern_table_descr_bq_pure.search(table_description_bq).group('descr') except: table_description_bq_pure = table_description_bq return table_description_bq_pure else: return '' class construct_overview_sheet: def __init__(self, tag_template, attributes = None): self.__dict_attributes = {item[0]: k for k, item in enumerate(tag_template.fields.items())} self.__num_el = len(self.__dict_attributes) self.__list_attributes = [[] for i in range(self.__num_el)] self.__list_table_id = [] if attributes is None: self.__attributes_ordered = list(tag_template.fields.keys()) else: assert isinstance(attributes, list), "'attributes' parameter must be a list" assert len(set(tag_template.fields.keys()) - set(attributes)) == 0, "The provided attributes are no permutation of the field keys of the provided tag_template" self.__attributes_ordered = attributes def append(self, table_id, tag = None, alt_tag_vals = None): assert isinstance(alt_tag_vals, dict) or alt_tag_vals is None, "'alt_tag_vals' must be of type dict or None" if alt_tag_vals is None: alt_tag_vals = {} self.__list_table_id.append(table_id) if tag is not None: for attr, index in self.__dict_attributes.items(): alt_val_not_avail = True if attr in alt_tag_vals.keys(): self.__list_attributes[index].append(alt_tag_vals[attr]) alt_val_not_avail = False if alt_val_not_avail: try: if(attr == 'table_description'): self.__list_attributes[index].append(toolbox.clean_sentence_string(tag.fields[attr].string_value)) else: self.__list_attributes[index].append(tag.fields[attr].string_value) except: self.__list_attributes[index].append('') else: for attr, index in self.__dict_attributes.items(): if attr in alt_tag_vals.keys(): self.__list_attributes[index].append(alt_tag_vals[attr]) else: self.__list_attributes[index].append('') def get_dataframe(self): return pd.DataFrame.from_dict({'table_id': self.__list_table_id, **{attr: self.__list_attributes[index] for attr, index in self.__dict_attributes.items()}}).fillna('').astype(str).applymap(lambda x: x.strip()).set_index('table_id')[self.__attributes_ordered] def set_datframe(self, return_df = False): self.df = self.get_dataframe() if return_df: return self.df else: pass class construct_table_sheets: def __init__(self): self.__list_table_id = [] self.__list_of_sheet_df = [] def append(self, table_id, sheet): self.__list_table_id.append(table_id) self.__list_of_sheet_df.append(sheet) def get_dict(self): return OrderedDict(zip(self.__list_table_id, self.__list_of_sheet_df)) def set_dict(self, return_dict = False): self.dict_sheets = self.get_dict() if return_dict: return self.dict_sheets else: pass
[ "karlo1986@gmx.de" ]
karlo1986@gmx.de
04c25ae249b069385ac6991f6b7f60b72769500e
6af5601738fbb38ace3454e88ddd773a64c72314
/exercises/petting_zoo/slither_inn.py
4d4d8bc226a6667de7e78e6aef1a069893f8b743
[]
no_license
morriscodez/critters-and-croquettes
82178ed673daa8f4988f40386ea9ca86f462c6d7
22368c14cea6a42bcaa9a800ca29242cfd29b741
refs/heads/main
2023-04-05T01:47:29.054819
2021-04-23T19:55:10
2021-04-23T19:55:10
360,280,011
0
0
null
2021-04-23T19:55:10
2021-04-21T19:13:45
Python
UTF-8
Python
false
false
166
py
class SlitherInn: def __init__(self, name): self.attraction_name = name self.description = "safe place to fall asleep" self.animals = []
[ "dylanrobertmorris@gmail.com" ]
dylanrobertmorris@gmail.com
7b535be1a7823f72cded96377305a79b7e8e5f84
a408ccea1036482792a79eee9f5b835c1e4a4c8e
/Bolivian_Lowlands/Scenarios/Scenario_2_new.py
fb9dec645e487634be15ef5054d543ff77a4d59e
[ "MIT" ]
permissive
CIE-UMSS/VLIR_Energy_Demand
ae399ace372a7e5263b3276bb1a0ecded937d227
3a9c7a034ac6ff668c7734597daf4696f62ef671
refs/heads/main
2023-09-01T01:33:37.832158
2021-09-25T20:51:11
2021-09-25T20:51:11
353,682,162
0
0
null
null
null
null
UTF-8
Python
false
false
8,569
py
# -*- coding: utf-8 -*- """ Created on Tue Sep 21 10:25:06 2021 @author: Clau """ ''' Paper: Energy sufficiency, lowlands. SCENARIO 2 ''' from core import User, np User_list = [] #Defining users H1 = User("low income", 73) User_list.append(H1) H2 = User("high income", 53) User_list.append(H2) Public_lighting = User("Public lighting ", 2) User_list.append(Public_lighting) HP = User("Health post", 1) User_list.append(HP) SA = User("School type A", 1) User_list.append(SA) Church = User("Church", 1) User_list.append(Church) WSS = User("water supply system", 1) User_list.append(WSS) Coliseum = User("Coliseum", 1) User_list.append(Coliseum) R = User("Restaurant", 1) User_list.append(R) GS = User("Grocery Store 1", 2) User_list.append(GS) EB = User("Entertainment Business", 3) User_list.append(EB) WS = User("Workshop", 2) User_list.append(WS) LAU = User("Lowlands agro-productive unit", 1) User_list.append(LAU) IW = User("Irrigation Water", 7) User_list.append(IW) #Appliances #Low Income Households H1_indoor_bulb = H1.Appliance(H1,3,7,2,120,0.2,10) H1_indoor_bulb.windows([1082,1440],[0,30],0.35) H1_outdoor_bulb = H1.Appliance(H1,1,13,2,600,0.2,10) H1_outdoor_bulb.windows([0,330],[1082,1440],0.35) H1_TV = H1.Appliance(H1,1,60,3,90,0.1,5) H1_TV.windows([750,840],[1082,1440],0.35,[0,30]) H1_Antenna = H1.Appliance(H1,1,8,3,90,0.1,5) H1_Antenna.windows([750,840],[1082,1440],0.35,[0,30]) H1_Phone_charger = H1.Appliance(H1,2,2,1,300,0.2,5) H1_Phone_charger.windows([1080,1440],[0,0],0.35) #High income households H2_indoor_bulb = H2.Appliance(H2,4,7,2,120,0.2,10) H2_indoor_bulb.windows([1082,1440],[0,30],0.35) H2_outdoor_bulb = H2.Appliance(H2,2,13,2,600,0.2,10) H2_outdoor_bulb.windows([0,330],[1082,1440],0.35) H2_TV = H2.Appliance(H2,2,60,2,120,0.1,5) H2_TV.windows([1082,1440],[0,60],0.35) H2_DVD = H2.Appliance(H2,1,8,2,40,0.1,5) H2_DVD.windows([1082,1440],[0,60],0.35) H2_Antenna = H2.Appliance(H2,1,8,2,80,0.1,5) H2_Antenna.windows([1082,1440],[0,60],0.35) H2_Radio = H2.Appliance(H2,1,36,2,60,0.1,5) H2_Radio.windows([390,450],[1082,1260],0.35) H2_Phone_charger = H2.Appliance(H2,4,2,2,300,0.2,5) H2_Phone_charger.windows([1110,1440],[0,30],0.35) H2_Freezer = H2.Appliance(H2,1,200,1,1440,0,30, 'yes',2) H2_Freezer.windows([0,1440],[0,0]) H2_Freezer.specific_cycle_1(5,15,200,15) H2_Freezer.specific_cycle_2(200,10,5,20) H2_Freezer.cycle_behaviour([480,1200],[0,0],[0,479],[1201,1440]) H2_Mixer = H2.Appliance(H2,1,50,3,30,0.1,1, occasional_use = 0.33) H2_Mixer.windows([420,450],[660,750],0.35,[1020,1170]) H2_Fan = H2.Appliance(H2,1,171,1,220,0.27,60) H2_Fan.windows([720,1080],[0,0]) H2_Laptop = H2.Appliance(H2,1,70,1,90,0.3,30) H2_Laptop.windows([960,1200],[0,0]) #Health post HP_indoor_bulb = HP.Appliance(HP,12,7,2,690,0.2,10) HP_indoor_bulb.windows([480,720],[870,1440],0.35) HP_outdoor_bulb = HP.Appliance(HP,1,13,2,690,0.2,10) HP_outdoor_bulb.windows([0,342],[1037,1440],0.35) HP_Phone_charger = HP.Appliance(HP,5,2,2,300,0.2,5) HP_Phone_charger.windows([480,720],[900,1440],0.35) HP_TV = HP.Appliance(HP,1,150,2,360,0.1,60) HP_TV.windows([480,720],[780,1020],0.2) HP_radio = HP.Appliance(HP,1,40,2,360,0.3,60) HP_radio.windows([480,720],[780,1020],0.35) HP_PC = HP.Appliance(HP,1,200,2,300,0.1,10) HP_PC.windows([480,720],[1050,1440],0.35) HP_printer = HP.Appliance(HP,1,100,1,60,0.3,10) HP_printer.windows([540,1020],[0,0],0.35) HP_fan = HP.Appliance(HP,2,60,1,240,0.2,60) HP_fan.windows([660,960],[0,0],0.35) HP_sterilizer_stove = HP.Appliance(HP,1,600,2,120,0.3,30) HP_sterilizer_stove.windows([540,600],[900,960],0.35) HP_needle_destroyer = HP.Appliance(HP,1,70,1,60,0.2,10) HP_needle_destroyer.windows([540,600],[0,0],0.35) HP_water_pump = HP.Appliance(HP,1,400,1,30,0.2,10) HP_water_pump.windows([480,510],[0,0],0.35) HP_Fridge = HP.Appliance(HP,3,150,1,1440,0,30, 'yes',3) HP_Fridge.windows([0,1440],[0,0]) HP_Fridge.specific_cycle_1(150,20,5,10) HP_Fridge.specific_cycle_2(150,15,5,15) HP_Fridge.specific_cycle_3(150,10,5,20) HP_Fridge.cycle_behaviour([580,1200],[0,0],[420,579],[0,0],[0,419],[1201,1440]) #School A SA_indoor_bulb = SA.Appliance(SA,6,7,2,120,0.25,30) SA_indoor_bulb.windows([480,780],[840,1140],0.2) SA_outdoor_bulb = SA.Appliance(SA,1,13,1,60,0.2,10) SA_outdoor_bulb.windows([1007,1080],[0,0],0.35) SA_TV = SA.Appliance(SA,1,60,2,120,0.1,5, occasional_use = 0.5) SA_TV.windows([480,780],[840,1140],0.2) SA_radio = SA.Appliance(SA,3,4,2,120,0.1,5, occasional_use = 0.5) SA_radio.windows([480,780],[840,1140],0.2) SA_DVD = SA.Appliance(SA,1,8,2,120,0.1,5, occasional_use = 0.5) SA_DVD.windows([480,780],[840,1140],0.2) #Public lighting Public_lighting_lamp_post = Public_lighting.Appliance(Public_lighting,12,40,2,310,0,300, 'yes', flat = 'yes') Public_lighting_lamp_post.windows([0,362],[1082,1440],0.1) #Church Ch_indoor_bulb = Church.Appliance(Church,10,26,1,210,0.2,60,'yes', flat = 'yes') Ch_indoor_bulb.windows([1200,1440],[0,0],0.1) Ch_outdoor_bulb = Church.Appliance(Church,7,26,1,240,0.2,60, 'yes', flat = 'yes') Ch_outdoor_bulb.windows([1200,1440],[0,0],0.1) Ch_speaker = Church.Appliance(Church,1,100,1,240,0.2,60) Ch_speaker.windows([1200,1350],[0,0],0.1) #Water supply system WSS_water_pump = WSS.Appliance(WSS,1,1700,2,60,0.2,10,occasional_use = 0.33) WSS_water_pump.windows([420,720],[840,1020],0.35) #Coliseum Lights = Coliseum.Appliance(Coliseum,25,150,2,310,0.1,300, 'yes', flat = 'yes') Lights.windows([0,336],[1110,1440],0.2) #Grocery Store GS_indoor_bulb = GS.Appliance(GS,2,7,2,120,0.2,10) GS_indoor_bulb.windows([1107,1440],[0,30],0.35) GS_outdoor_bulb = GS.Appliance(GS,1,13,2,600,0.2,10) GS_outdoor_bulb.windows([0,330],[1107,1440],0.35) GS_freezer = GS.Appliance(GS,1,200,1,1440,0,30,'yes',3) GS_freezer.windows([0,1440],[0,0]) GS_freezer.specific_cycle_1(200,20,5,10) GS_freezer.specific_cycle_2(200,15,5,15) GS_freezer.specific_cycle_3(200,10,5,20) GS_freezer.cycle_behaviour([480,1200],[0,0],[300,479],[0,0],[0,299],[1201,1440]) GS_Radio = GS.Appliance(GS,1,36,2,60,0.1,5) GS_Radio.windows([390,450],[1140,1260],0.35) #Restaurant R_indoor_bulb = R.Appliance(R,2,7,2,120,0.2,10) R_indoor_bulb.windows([1107,1440],[0,30],0.35) R_Blender = R.Appliance(R,1,350,2,20,0.375,5) R_Blender.windows([420,480],[720,780],0.5) R_freezer = R.Appliance(R,1,200,1,1440,0,30,'yes',3) R_freezer.windows([0,1440],[0,0]) R_freezer.specific_cycle_1(200,20,5,10) R_freezer.specific_cycle_2(200,15,5,15) R_freezer.specific_cycle_3(200,10,5,20) R_freezer.cycle_behaviour([480,1200],[0,0],[300,479],[0,0],[0,299],[1201,1440]) #Entertainment Business EB_indoor_bulb = EB.Appliance(EB,2,7,2,120,0.2,10) EB_indoor_bulb.windows([1107,1440],[0,30],0.35) EB_outdoor_bulb = EB.Appliance(EB,1,13,2,600,0.2,10) EB_outdoor_bulb.windows([0,330],[1107,1440],0.35) EB_Stereo = EB.Appliance(EB,1,150,2,90,0.1,5, occasional_use = 0.33) EB_Stereo.windows([480,780],[0,0],0.35) EB_TV = EB.Appliance(EB,1,60,2,120,0.1,5, occasional_use = 0.5) EB_TV.windows([480,780],[840,1140],0.2) EB_PC = EB.Appliance(EB,1,50,2,210,0.1,10) EB_PC.windows([480,780],[840,1140],0.35) EB_freezer = EB.Appliance(EB,1,200,1,1440,0,30,'yes',3) EB_freezer.windows([0,1440],[0,0]) EB_freezer.specific_cycle_1(200,20,5,10) EB_freezer.specific_cycle_2(200,15,5,15) EB_freezer.specific_cycle_3(200,10,5,20) EB_freezer.cycle_behaviour([480,1200],[0,0],[300,479],[0,0],[0,299],[1201,1440]) #Workshop WS_indoor_bulb = WS.Appliance(WS,2,7,2,120,0.2,10) WS_indoor_bulb.windows([1107,1440],[0,30],0.35) WS_welding_machine = WS.Appliance(WS,1,5500,1,60,0.5,30,occasional_use = 0.3) WS_welding_machine.windows([0,1440],[0,0],0.35) WS_grinding_machine = WS.Appliance(WS,1,750,1,480,0.125,60,occasional_use = 0.3) WS_grinding_machine.windows([0,1440],[0,0],0.35) WS_Radio = WS.Appliance(WS,1,36,2,60,0.1,5) WS_Radio.windows([390,450],[1140,1260],0.35) #trans LAU_GD = LAU.Appliance(LAU,1,9360,1,180,0.2,30,occasional_use = 0.33) LAU_GD.windows([420,1080],[0,0],0.35) LAU_VW = LAU.Appliance(LAU,1,1170,1,480,0.2,15,occasional_use = 0.82) LAU_VW.windows([420,1140],[0,0],0.35) LAU_BT = LAU.Appliance(LAU,1,370,2,900,0.2,180) LAU_BT.windows([360,930],[1080,1440],0.35) #Irrigation IW_water_pump = IW.Appliance(IW,1,1700,2,60,0.2,10,occasional_use = 0.33) IW_water_pump.windows([420,720],[840,1020],0.35)
[ "noreply@github.com" ]
CIE-UMSS.noreply@github.com
b49321d49f458783ff2e504b5b2c980bfaac3d46
d686dd84682038efe027d6ba14a77282b3786287
/src/e2e/parsers/downstream_config.py
69bad6b06ae6a14096171b4ec094793c8d511cee
[ "Apache-2.0", "MIT" ]
permissive
idiap/apam
2d7e2cfee9a4fab7e194f4aee059d8684d932210
b1ba6087dcb8d2b864b4a99979bb325fb17f3b99
refs/heads/main
2023-03-02T10:00:44.992938
2021-02-15T11:00:54
2021-02-15T11:00:54
335,578,798
14
1
null
null
null
null
UTF-8
Python
false
false
1,152
py
""" Parser for asr training options """ # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/ # Written by Apoorv Vyas <apoorv.vyas@idiap.ch> import argparse import sys def add_downstream_options(parser): parser.add_argument( '--ckpt', default='', type=str, help='Path to upstream pre-trained checkpoint, required if using other than baseline', required=True ) parser.add_argument( '--config', default='config/asr-downstream.yaml', type=str, help='Path to downstream experiment config.', required=True ) parser.add_argument( '--upconfig', default='default', type=str, help='Path to the option upstream config. Pass default to use from checkpoint', ) parser.add_argument( '--cpu', action='store_true', help='Disable GPU training.' ) return parser def print_downstream_options(args): sys.stderr.write(""" Downstream Config: Checkpoint: {ckpt} ASR Config: {config} Upconfig: {upconfig} CPU Training: {cpu} """.format(**vars(args)))
[ "philip.abbet@idiap.ch" ]
philip.abbet@idiap.ch
3ad493b7dfecdacdc6ea5bd86467d39b3b95ef44
8b9dfacd464558d1aacdef387ec3078a03d59158
/aruco_detect_master/aruco_detect.py
f4ac1f0f3472cc04ad87f0aa78aeb49df4970415
[]
no_license
Taospirit/HITsz_Course_Code
56bb4a4327b39d9c45405e367dafc4211b74930b
b2f33bb3e5ce31894b12bfbf2f42cbf482933ed0
refs/heads/master
2020-04-10T20:30:07.952396
2019-07-10T13:53:38
2019-07-10T13:53:38
161,269,766
2
0
null
null
null
null
UTF-8
Python
false
false
4,294
py
import cv2 as cv import cv2.aruco as aruco import numpy as np import copy # IMG_WIDTH = camera_matrix = np.array(([693.2, 0, 666.8], # 内参矩阵 [0, 693.4, 347.7], [0, 0, 1]), dtype=np.double) dist_coefs = np.array([-0.050791, 0.217163, 0.0000878, -0.000388, -0.246122], dtype=np.double) # k1 k2 p1 p2 k3 VIDEO_WIDTH, VIDEO_HEIGHT = 640, 480 SHOW_WIDTH = 550 def drawPolyLines(img, raw_point_list): point_list = [[elem[0], elem[1]] for elem in raw_point_list] pts = np.array(point_list, np.int32) pts = pts.reshape((-1, 1, 2)) cv.polylines(img, [pts], True, (0, 255, 255)) def saveVideo(cap_save, num): fourcc = cv.VideoWriter_fourcc(*'XVID') out = cv.VideoWriter('./aurco_test'+str(num)+'.avi', fourcc, 20.0, (VIDEO_WIDTH, VIDEO_HEIGHT)) while cap_save.isOpened(): ret, frame = cap_save.read() if ret: out.write(frame) cv.imshow('frame', frame) if cv.waitKey(1) & 0xFF == ord('s'): print ('End record video!') break else: print ('ret is False...break out!') break out.release() def detectMarkersOrigin(img_origin): frame = copy.deepcopy(img_origin) gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict) if ids is not None: id_show = [[ids[i][0], corners[i][0][0][0], corners[i][0][0][1]] for i in range(len(corners))] # print (len(ids), type(ids), ids) rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners, 0.05, camera_matrix, dist_coefs) for i in range(rvec.shape[0]): aruco.drawAxis(frame, camera_matrix, dist_coefs, rvec[i, :, :], tvec[i, :, :], 0.03) aruco.drawDetectedMarkers(frame, corners, ids) for elem in id_show: cv.putText(frame, 'id='+str(elem[0]), (elem[1], elem[2]), cv.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2, cv.LINE_AA) else: cv.putText(frame, "No Aruco_Markers in sight!", (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv.LINE_AA) cv.namedWindow('Marker_Detect', cv.WINDOW_NORMAL) cv.resizeWindow('Marker_Detect', (SHOW_WIDTH, int(SHOW_WIDTH*480/640))) cv.moveWindow('Marker_Detect', 50, 50) cv.imshow('Marker_Detect', frame) def detectMarkersMaster(img_origin): img = copy.deepcopy(img_origin) cv.namedWindow('Origin_Img', cv.WINDOW_NORMAL) cv.moveWindow('Origin_Img', 650, 50) cv.resizeWindow('Origin_Img', (SHOW_WIDTH, int(SHOW_WIDTH*480/640))) cv.imshow('Origin_Img', img) cv.namedWindow('Canny_Img', cv.WINDOW_NORMAL) cv.moveWindow('Canny_Img', 1250, 50) cv.resizeWindow('Canny_Img', (SHOW_WIDTH, int(SHOW_WIDTH*480/640))) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) edges = cv.Canny(gray, 100, 200) cv.imshow('Canny_Img', edges) drawing = np.zeros(img.shape[:], dtype=np.uint8) #TODO: lines_p = cv.HoughLinesP(edges, 0.5, np.pi / 180, 90, minLineLength=10, maxLineGap=15) if lines_p is not None: for line in lines_p: x1, y1, x2, y2 = line[0] cv.line(img, (x1, y1), (x2, y2), (0, 255, 0), 3, lineType=cv.LINE_AA) # cv.imshow('Hough_p', img) #寻找Harris角点 gray = np.float32(gray) dst = cv.cornerHarris(gray, 2, 3, 0.04) dst = cv.dilate(dst,None) img[dst > 0.01*dst.max()]=[0, 0, 255] cv.imshow('dst', img) # ret, dst = cv.threshold(dst,0.01*dst.max(),255,0) # dst = np.uint8(dst) # #找到重心 # ret, labels, stats, centroids = cv.connectedComponentsWithStats(dst) # #定义迭代次数 # criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 100, 0.001) # corners = cv.cornerSubPix(gray, np.float32(centroids),(5,5),(-1,-1),criteria) # #返回角点 # #绘制 # res = np.hstack((centroids,corners)) # res = np.int0(res) # img[res[:,1],res[:,0]]=[0,0,255] # img[res[:,3],res[:,2]] = [0,255,0] # cv.imwrite('./subpixel5.png',img) def main(): cap, num = cv.VideoCapture(1), 1 if not cap.isOpened(): print ('Failed to open the camera...') return -1 while cap.isOpened(): ret, img = cap.read() detectMarkersOrigin(img) detectMarkersMaster(img) key = cv.waitKey(1) & 0xff if key == 27: print ("close window for keyboard break") break if key == ord('s'): print ('Start to record video...') saveVideo(cap, num) num += 1 cap.release() cv.destroyAllWindows() if __name__ == "__main__": main()
[ "lintao209@outlook.com" ]
lintao209@outlook.com
d2880bfa73bd2dcfe254701168d1ff3a803181e6
04d30611d6ccc31b1e204bfa7f83efa50bab5ae6
/github_data_pipeline_api.py
483e28940fbc9a501a0cbd12166c7817c0f3d192
[]
no_license
jerryshenyizhou/crypto_github_data
957cdee889b0107960eb7669046857ec40b846cb
2c510b9fbbc3233f4f663c3b36aa42bdf47f764e
refs/heads/master
2021-09-05T21:46:36.994743
2018-01-31T07:12:40
2018-01-31T07:12:40
115,180,988
0
0
null
null
null
null
UTF-8
Python
false
false
11,659
py
# coding: utf-8 # In[2]: import datetime import json import warnings import pandas as pd import requests from pandas.io.json import json_normalize warnings.filterwarnings('ignore') import sys reload(sys) sys.setdefaultencoding('utf8') sys.path.append('./utils') from google_sheet_update import * # In[3]: # utility function, http request def getjson(url, auth=0): if auth == 0: with open('./utils/secret.json') as json_file: secret = json.load(json_file) auth = (str(secret['github']['username']), str(secret['github']['password'])) else: pass header = {'x-requested-with': 'XMLHttpRequest'} mainPage = requests.get(url, auth=auth) data = mainPage.json() return data # In[4]: # ingest coin github org def coin_github_org_ingestion(): sheet_key = '1tpOAiuRo9RNKnyPCVTGjc3H9S1miIJD1AimFLg8sv4E' tab = 'organization' data = get_googlesheet_data(sheet_key, tab) return data # ingest coin github exclude data def coin_github_exclusion_ingestion(): sheet_key = '1tpOAiuRo9RNKnyPCVTGjc3H9S1miIJD1AimFLg8sv4E' tab = 'excluding_repos' data = get_googlesheet_data(sheet_key, tab) return data # In[5]: # ingest coinmarketcap data def coin_marketcap_ingestion(limit=200): data = json_normalize(getjson("https://api.coinmarketcap.com/v1/ticker/?limit=" + str(limit))) return data # In[6]: # ingest github repo data def github_repo_ingestion(github_org_data, trunc_date=datetime.date(2017, 1, 1)): start_time = datetime.datetime.today() data = pd.DataFrame() for symbol in github_org_data.symbol.unique(): for github_org in list(github_org_data[github_org_data.symbol == symbol].github_org): try: data_repo = getjson("https://api.github.com/users/" + str( github_org) + "/repos?sort=updated&direction=desc&per_page=100") repo_dict = json_normalize(data_repo).set_index('name') repo_dict['updated_at'] = pd.to_datetime(repo_dict['updated_at']) repo_dict['symbol'] = symbol repo_list = repo_dict[repo_dict.updated_at >= trunc_date].index data = data.append(repo_dict) print str(github_org) + ' completed!' except: print str(github_org) + ' failed!' pass # pd.DataFrame.to_csv(token_repo_df,'./data/token_repo_dictionary_'+str(today)+'.csv') minutes_passed = (datetime.datetime.today() - start_time).seconds / 60 data.pushed_at = pd.to_datetime(data.pushed_at) print 'finished ingesting coin github repo data! used ' + str(minutes_passed) + ' minutes!' return data # In[7]: # write github org google sheet with coins that needs to be updated with github orgs def update_no_org_coins(coin_github_org_data, coin_marketcap_data): coin_org_list = coin_github_org_data.symbol.unique() coin_total_list = coin_marketcap_data.symbol.unique() coin_gap_list = list(set(coin_total_list) - set(coin_org_list)) coin_gap_list_df = coin_marketcap_data[coin_marketcap_data.symbol.isin(coin_gap_list)][['symbol', 'id']] sheet_key = '1tpOAiuRo9RNKnyPCVTGjc3H9S1miIJD1AimFLg8sv4E' tab = 'undocumented_top_200_coins' cell_col = 'A' cell_row = 1 write_cells(coin_gap_list_df, sheet_key, tab, cell_col, cell_row, transpose=0) return coin_gap_list # In[8]: # full contribution list per repo def get_full_contribution_history(coin_github_repo_data): start_time = datetime.datetime.today() data_contributions_entry = pd.DataFrame() for repo_name in coin_github_repo_data.full_name.unique(): try: data_repo_contributors = json_normalize(getjson( "https://api.github.com/repos/" + repo_name + "/stats/contributors?sort=total&direction=desc&per_page=100")) data_repo_contributors['repo_full_name'] = repo_name data_repo_contributors = \ data_repo_contributors.dropna(subset=['author.login']).set_index(['repo_full_name', 'author.login'])[ ['weeks']] data_repo_contributors = data_repo_contributors.weeks.apply(pd.Series) data_repo_contributors = pd.DataFrame(data_repo_contributors.stack())[0].apply(pd.Series) data_repo_contributors = data_repo_contributors[data_repo_contributors.c > 0] data_contributions_entry = data_contributions_entry.append(data_repo_contributors) memory = (data_contributions_entry.memory_usage()).sum() / (1024 ** 2) minutes_passed = (datetime.datetime.today() - start_time).seconds / 60 print 'repo ' + repo_name + ' flattern completed! used ' + str( minutes_passed) + ' minutes! ' + 'memory used ' + str(memory) + 'MB' del data_repo_contributors except: print 'repo ' + repo_name + ' flattern failed! used ' + str( minutes_passed) + ' minutes! ' + 'memory used ' + str(memory) + 'MB' pass minutes_passed = (datetime.datetime.today() - start_time).seconds / 60 print 'finished ingesting coin contribution data! used ' + str(minutes_passed) + ' minutes!' data_contributions_entry['w'] = pd.to_datetime(data_contributions_entry.w, unit='s') data_contributions_entry = data_contributions_entry.reset_index().drop(['level_2'], axis=1) data_contributions_entry = data_contributions_entry.rename( columns={'w': 'week', 'c': 'commits', 'a': 'additions', 'd': 'deletions', 'author.login': 'login'}) return data_contributions_entry # In[52]: # pulling repo lists that need to be updated def generate_update_repo_list(data_contributions_entry_existing, coin_github_repo_data): # dropping empty rows data_contributions_entry_existing = data_contributions_entry_existing[data_contributions_entry_existing.commits > 0] # formatting dates data_contributions_entry_existing.week = pd.to_datetime(data_contributions_entry_existing.week) coin_github_repo_data.pushed_at = pd.to_datetime(coin_github_repo_data.pushed_at) # contribution update_time contribution_update_time = data_contributions_entry_existing.week.max() # existing records for last commit week repo_last_commit_week = pd.DataFrame( data_contributions_entry_existing.groupby('repo_full_name').week.max()).reset_index() # latest last commit timestamp from github repo repo_latest_record_week = coin_github_repo_data[['full_name', 'pushed_at']].rename( columns={'full_name': 'repo_full_name'}) # merge to generate list of repo lists that have a new push repo_compare = repo_last_commit_week.merge(repo_latest_record_week, how='right') repo_compare.week = pd.to_datetime(repo_compare.week).fillna(datetime.datetime(1900, 1, 1)) repo_update_list = repo_compare[((repo_compare.pushed_at - repo_compare.week).dt.days > 7) & (repo_compare.pushed_at > contribution_update_time - datetime.timedelta( 7))].repo_full_name return repo_update_list # In[ ]: # In[23]: # full contribution list per repo def update_contribution_history(data_contributions_entry_existing, coin_github_repo_data): # generate repo lists that needs to be updated repo_update_list = generate_update_repo_list(data_contributions_entry_existing, coin_github_repo_data) print 'number of repos needed to be updated: ' + str(len(repo_update_list)) start_time = datetime.datetime.today() data_contributions_entry = pd.DataFrame() for repo_name in repo_update_list: try: data_repo_contributors = json_normalize(getjson( "https://api.github.com/repos/" + repo_name + "/stats/contributors?sort=total&direction=desc&per_page=100")) data_repo_contributors['repo_full_name'] = repo_name data_repo_contributors = \ data_repo_contributors.dropna(subset=['author.login']).set_index(['repo_full_name', 'author.login'])[ ['weeks']] data_repo_contributors = data_repo_contributors.weeks.apply(pd.Series) data_repo_contributors = pd.DataFrame(data_repo_contributors.stack())[0].apply(pd.Series) data_repo_contributors = data_repo_contributors[data_repo_contributors.c > 0] data_contributions_entry = data_contributions_entry.append(data_repo_contributors) memory = (data_contributions_entry.memory_usage()).sum() / (1024 ** 2) minutes_passed = (datetime.datetime.today() - start_time).seconds / 60 print 'repo ' + repo_name + ' flattern completed! used ' + str( minutes_passed) + ' minutes! ' + 'memory used ' + str(memory) + 'MB' del data_repo_contributors except: print 'repo ' + repo_name + ' flattern failed! used ' + str( minutes_passed) + ' minutes! ' + 'memory used ' + str(memory) + 'MB' pass minutes_passed = (datetime.datetime.today() - start_time).seconds / 60 print 'finished ingesting coin contribution data! used ' + str(minutes_passed) + ' minutes!' data_contributions_entry['w'] = pd.to_datetime(data_contributions_entry.w, unit='s') data_contributions_entry = data_contributions_entry.reset_index().drop(['level_2'], axis=1) data_contributions_entry = data_contributions_entry.rename( columns={'w': 'week', 'c': 'commits', 'a': 'additions', 'd': 'deletions', 'author.login': 'login'}) data_contributions_entry_updated = data_contributions_entry_existing[ (~data_contributions_entry_existing.repo_full_name.isin(repo_update_list)) & (data_contributions_entry_existing.commits > 0)].append(data_contributions_entry) data_contributions_entry_updated.week = pd.to_datetime(data_contributions_entry_updated.week) data_contributions_entry_updated = data_contributions_entry_updated[ data_contributions_entry_updated.week >= datetime.date(2009, 1, 1)] return data_contributions_entry_updated # In[11]: # main function, update print 'start github_data_pipeline! UTC time: '+str(datetime.datetime.today()) coin_github_org_data = coin_github_org_ingestion() coin_marketcap_data = coin_marketcap_ingestion() coin_github_repo_data = github_repo_ingestion(coin_github_org_data) coin_github_exclude_data = coin_github_exclusion_ingestion() coin_gap_list = update_no_org_coins(coin_github_org_data, coin_marketcap_data) # update contribution data from existing file data_contributions_entry_existing = pd.DataFrame.from_csv('./data/latest_data/top_coin_repo_contributions_entry.csv') data_contributions_entry = update_contribution_history(data_contributions_entry_existing, coin_github_repo_data) data_contributions_entry = data_contributions_entry[~data_contributions_entry.repo_full_name.isin(coin_github_exclude_data.repo_full_name)] # pull from scratch # data_contributions_entry = get_full_contribution_history(coin_github_repo_data) # In[69]: # saving to csv today = datetime.date.today() pd.DataFrame.to_csv(coin_marketcap_data, './data/latest_data/coin_marketcap_data.csv') pd.DataFrame.to_csv(coin_github_repo_data, './data/latest_data//top_coin_repo_list.csv') pd.DataFrame.to_csv(data_contributions_entry, './data/latest_data/top_coin_repo_contributions_entry.csv') # archiving just token contribution data pd.DataFrame.to_csv(data_contributions_entry, './data/archive_data/top_coin_repo_contributions_entry_' + str(today) + '.csv') print 'finished github_data_pipeline! UTC time: '+str(datetime.datetime.today())
[ "jerryshenyizhou@gmail.com" ]
jerryshenyizhou@gmail.com
6747e33efcd4f93c3dbf79fe12368de440154955
b45e649b4580692dd1b8bf63ad29befb3daad95a
/spark/src/main/python/preprocBinning.py
6c21866ee6f9e294698dfe7cff5be5841bf1c7fa
[]
no_license
xu-hao/FHIR-PIT
21ea0e5b8796d86f3a931b99e3e7a3f1e58b04a2
db2fb04e2cc0d9fce2f8043f594f60fdb8f5a8e8
refs/heads/master
2021-05-25T09:49:48.084629
2021-05-19T20:17:11
2021-05-19T20:17:11
127,015,534
2
0
null
null
null
null
UTF-8
Python
false
false
660
py
import os import sys import json from preprocPatient import * from preprocVisit import * year_start, year_end, config_file, input_dir, output_dir = sys.argv[1:] for year in range(int(year_start), int(year_end) + 1): print(year) input_file_p = f"{input_dir}/{year}/all_patient" output_file_p = f"{output_dir}/{year}patient" preproc_patient(config_file, input_file_p, output_file_p) input_file_v = f"{input_dir}/{year}/all_visit" output_file_v = f"{output_dir}/{year}visit" preproc_visit(config_file, input_file_v, output_file_v)
[ "xuh@cs.unc.edu" ]
xuh@cs.unc.edu
413fe0cf74f78a5479abcffb6ba6f1b944f65717
59b87e4892a583e1eafaeca8582320b3db6e4435
/.c9/metadata/environment/products/views.py
756c77246def161c889dabccb347e037f5dd2284
[]
no_license
cgaynor91/E-Commerce
65e112b4a2c66725d27a65847686c497574d1f58
f7e3e81358f494cd16768e4aba73b19bc16a29ab
refs/heads/master
2021-07-11T23:26:22.895787
2020-03-11T21:47:28
2020-03-11T21:47:28
246,412,701
0
0
null
2021-06-10T22:39:00
2020-03-10T21:32:01
Python
UTF-8
Python
false
false
15,846
py
{"filter":false,"title":"views.py","tooltip":"/products/views.py","ace":{"folds":[],"scrolltop":0,"scrollleft":0,"selection":{"start":{"row":6,"column":65},"end":{"row":6,"column":65},"isBackwards":false},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":0},"hash":"43957824f031b60e8831b61c96c6e4a720a0ef77","undoManager":{"mark":39,"position":39,"stack":[[{"start":{"row":1,"column":0},"end":{"row":1,"column":1},"action":"insert","lines":["d"],"id":2}],[{"start":{"row":1,"column":0},"end":{"row":1,"column":1},"action":"remove","lines":["d"],"id":3}],[{"start":{"row":1,"column":0},"end":{"row":1,"column":1},"action":"insert","lines":["f"],"id":4},{"start":{"row":1,"column":1},"end":{"row":1,"column":2},"action":"insert","lines":["r"]},{"start":{"row":1,"column":2},"end":{"row":1,"column":3},"action":"insert","lines":["o"]},{"start":{"row":1,"column":3},"end":{"row":1,"column":4},"action":"insert","lines":["m"]}],[{"start":{"row":1,"column":4},"end":{"row":1,"column":5},"action":"insert","lines":[" "],"id":5},{"start":{"row":1,"column":5},"end":{"row":1,"column":6},"action":"insert","lines":["."]},{"start":{"row":1,"column":6},"end":{"row":1,"column":7},"action":"insert","lines":["m"]},{"start":{"row":1,"column":7},"end":{"row":1,"column":8},"action":"insert","lines":["o"]},{"start":{"row":1,"column":8},"end":{"row":1,"column":9},"action":"insert","lines":["d"]},{"start":{"row":1,"column":9},"end":{"row":1,"column":10},"action":"insert","lines":["e"]},{"start":{"row":1,"column":10},"end":{"row":1,"column":11},"action":"insert","lines":["l"]},{"start":{"row":1,"column":11},"end":{"row":1,"column":12},"action":"insert","lines":["s"]}],[{"start":{"row":1,"column":12},"end":{"row":1,"column":13},"action":"insert","lines":[" "],"id":6},{"start":{"row":1,"column":13},"end":{"row":1,"column":14},"action":"insert","lines":["i"]},{"start":{"row":1,"column":14},"end":{"row":1,"column":15},"action":"insert","lines":["m"]},{"start":{"row":1,"column":15},"end":{"row":1,"column":16},"action":"insert","lines":["p"]},{"start":{"row":1,"column":16},"end":{"row":1,"column":17},"action":"insert","lines":["o"]},{"start":{"row":1,"column":17},"end":{"row":1,"column":18},"action":"insert","lines":["r"]},{"start":{"row":1,"column":18},"end":{"row":1,"column":19},"action":"insert","lines":["t"]}],[{"start":{"row":1,"column":19},"end":{"row":1,"column":20},"action":"insert","lines":[" "],"id":7},{"start":{"row":1,"column":20},"end":{"row":1,"column":21},"action":"insert","lines":["P"]},{"start":{"row":1,"column":21},"end":{"row":1,"column":22},"action":"insert","lines":["r"]},{"start":{"row":1,"column":22},"end":{"row":1,"column":23},"action":"insert","lines":["o"]},{"start":{"row":1,"column":23},"end":{"row":1,"column":24},"action":"insert","lines":["d"]},{"start":{"row":1,"column":24},"end":{"row":1,"column":25},"action":"insert","lines":["u"]},{"start":{"row":1,"column":25},"end":{"row":1,"column":26},"action":"insert","lines":["c"]},{"start":{"row":1,"column":26},"end":{"row":1,"column":27},"action":"insert","lines":["t"]}],[{"start":{"row":3,"column":0},"end":{"row":4,"column":0},"action":"insert","lines":["",""],"id":8},{"start":{"row":4,"column":0},"end":{"row":4,"column":1},"action":"insert","lines":["d"]},{"start":{"row":4,"column":1},"end":{"row":4,"column":2},"action":"insert","lines":["e"]},{"start":{"row":4,"column":2},"end":{"row":4,"column":3},"action":"insert","lines":["f"]}],[{"start":{"row":4,"column":3},"end":{"row":4,"column":4},"action":"insert","lines":[" "],"id":9},{"start":{"row":4,"column":4},"end":{"row":4,"column":5},"action":"insert","lines":["a"]},{"start":{"row":4,"column":5},"end":{"row":4,"column":6},"action":"insert","lines":["l"]},{"start":{"row":4,"column":6},"end":{"row":4,"column":7},"action":"insert","lines":["l"]},{"start":{"row":4,"column":7},"end":{"row":4,"column":8},"action":"insert","lines":["_"]},{"start":{"row":4,"column":8},"end":{"row":4,"column":9},"action":"insert","lines":["p"]},{"start":{"row":4,"column":9},"end":{"row":4,"column":10},"action":"insert","lines":["r"]},{"start":{"row":4,"column":10},"end":{"row":4,"column":11},"action":"insert","lines":["o"]},{"start":{"row":4,"column":11},"end":{"row":4,"column":12},"action":"insert","lines":["d"]},{"start":{"row":4,"column":12},"end":{"row":4,"column":13},"action":"insert","lines":["u"]},{"start":{"row":4,"column":13},"end":{"row":4,"column":14},"action":"insert","lines":["c"]},{"start":{"row":4,"column":14},"end":{"row":4,"column":15},"action":"insert","lines":["t"]}],[{"start":{"row":4,"column":15},"end":{"row":4,"column":16},"action":"insert","lines":["s"],"id":10}],[{"start":{"row":4,"column":16},"end":{"row":4,"column":18},"action":"insert","lines":["()"],"id":11}],[{"start":{"row":4,"column":17},"end":{"row":4,"column":18},"action":"insert","lines":["r"],"id":12},{"start":{"row":4,"column":18},"end":{"row":4,"column":19},"action":"insert","lines":["e"]},{"start":{"row":4,"column":19},"end":{"row":4,"column":20},"action":"insert","lines":["q"]},{"start":{"row":4,"column":20},"end":{"row":4,"column":21},"action":"insert","lines":["u"]},{"start":{"row":4,"column":21},"end":{"row":4,"column":22},"action":"insert","lines":["e"]},{"start":{"row":4,"column":22},"end":{"row":4,"column":23},"action":"insert","lines":["s"]},{"start":{"row":4,"column":23},"end":{"row":4,"column":24},"action":"insert","lines":["t"]}],[{"start":{"row":4,"column":25},"end":{"row":4,"column":26},"action":"insert","lines":[":"],"id":13}],[{"start":{"row":4,"column":26},"end":{"row":5,"column":0},"action":"insert","lines":["",""],"id":14},{"start":{"row":5,"column":0},"end":{"row":5,"column":4},"action":"insert","lines":[" "]},{"start":{"row":5,"column":4},"end":{"row":5,"column":5},"action":"insert","lines":["p"]},{"start":{"row":5,"column":5},"end":{"row":5,"column":6},"action":"insert","lines":["r"]},{"start":{"row":5,"column":6},"end":{"row":5,"column":7},"action":"insert","lines":["o"]},{"start":{"row":5,"column":7},"end":{"row":5,"column":8},"action":"insert","lines":["d"]},{"start":{"row":5,"column":8},"end":{"row":5,"column":9},"action":"insert","lines":["u"]},{"start":{"row":5,"column":9},"end":{"row":5,"column":10},"action":"insert","lines":["c"]},{"start":{"row":5,"column":10},"end":{"row":5,"column":11},"action":"insert","lines":["t"]},{"start":{"row":5,"column":11},"end":{"row":5,"column":12},"action":"insert","lines":["s"]}],[{"start":{"row":5,"column":12},"end":{"row":5,"column":13},"action":"insert","lines":[" "],"id":15},{"start":{"row":5,"column":13},"end":{"row":5,"column":14},"action":"insert","lines":["="]}],[{"start":{"row":5,"column":14},"end":{"row":5,"column":15},"action":"insert","lines":[" "],"id":16},{"start":{"row":5,"column":15},"end":{"row":5,"column":16},"action":"insert","lines":["P"]},{"start":{"row":5,"column":16},"end":{"row":5,"column":17},"action":"insert","lines":["r"]},{"start":{"row":5,"column":17},"end":{"row":5,"column":18},"action":"insert","lines":["o"]},{"start":{"row":5,"column":18},"end":{"row":5,"column":19},"action":"insert","lines":["d"]},{"start":{"row":5,"column":19},"end":{"row":5,"column":20},"action":"insert","lines":["u"]},{"start":{"row":5,"column":20},"end":{"row":5,"column":21},"action":"insert","lines":["c"]},{"start":{"row":5,"column":21},"end":{"row":5,"column":22},"action":"insert","lines":["t"]}],[{"start":{"row":5,"column":22},"end":{"row":5,"column":23},"action":"insert","lines":["."],"id":17},{"start":{"row":5,"column":23},"end":{"row":5,"column":24},"action":"insert","lines":["o"]},{"start":{"row":5,"column":24},"end":{"row":5,"column":25},"action":"insert","lines":["b"]},{"start":{"row":5,"column":25},"end":{"row":5,"column":26},"action":"insert","lines":["j"]},{"start":{"row":5,"column":26},"end":{"row":5,"column":27},"action":"insert","lines":["e"]},{"start":{"row":5,"column":27},"end":{"row":5,"column":28},"action":"insert","lines":["c"]},{"start":{"row":5,"column":28},"end":{"row":5,"column":29},"action":"insert","lines":["t"]},{"start":{"row":5,"column":29},"end":{"row":5,"column":30},"action":"insert","lines":["s"]}],[{"start":{"row":5,"column":30},"end":{"row":5,"column":31},"action":"insert","lines":["."],"id":18},{"start":{"row":5,"column":31},"end":{"row":5,"column":32},"action":"insert","lines":["a"]},{"start":{"row":5,"column":32},"end":{"row":5,"column":33},"action":"insert","lines":["l"]},{"start":{"row":5,"column":33},"end":{"row":5,"column":34},"action":"insert","lines":["l"]}],[{"start":{"row":5,"column":34},"end":{"row":5,"column":36},"action":"insert","lines":["()"],"id":19}],[{"start":{"row":5,"column":35},"end":{"row":6,"column":0},"action":"insert","lines":["",""],"id":20},{"start":{"row":6,"column":0},"end":{"row":6,"column":8},"action":"insert","lines":[" "]}],[{"start":{"row":6,"column":4},"end":{"row":6,"column":8},"action":"remove","lines":[" "],"id":21},{"start":{"row":6,"column":0},"end":{"row":6,"column":4},"action":"remove","lines":[" "]},{"start":{"row":5,"column":35},"end":{"row":6,"column":0},"action":"remove","lines":["",""]}],[{"start":{"row":5,"column":36},"end":{"row":6,"column":0},"action":"insert","lines":["",""],"id":22},{"start":{"row":6,"column":0},"end":{"row":6,"column":4},"action":"insert","lines":[" "]},{"start":{"row":6,"column":4},"end":{"row":6,"column":5},"action":"insert","lines":["r"]},{"start":{"row":6,"column":5},"end":{"row":6,"column":6},"action":"insert","lines":["e"]},{"start":{"row":6,"column":6},"end":{"row":6,"column":7},"action":"insert","lines":["u"]}],[{"start":{"row":6,"column":6},"end":{"row":6,"column":7},"action":"remove","lines":["u"],"id":23}],[{"start":{"row":6,"column":6},"end":{"row":6,"column":7},"action":"insert","lines":["t"],"id":24},{"start":{"row":6,"column":7},"end":{"row":6,"column":8},"action":"insert","lines":["i"]},{"start":{"row":6,"column":8},"end":{"row":6,"column":9},"action":"insert","lines":["r"]},{"start":{"row":6,"column":9},"end":{"row":6,"column":10},"action":"insert","lines":["n"]}],[{"start":{"row":6,"column":9},"end":{"row":6,"column":10},"action":"remove","lines":["n"],"id":25},{"start":{"row":6,"column":8},"end":{"row":6,"column":9},"action":"remove","lines":["r"]},{"start":{"row":6,"column":7},"end":{"row":6,"column":8},"action":"remove","lines":["i"]}],[{"start":{"row":6,"column":7},"end":{"row":6,"column":8},"action":"insert","lines":["u"],"id":26},{"start":{"row":6,"column":8},"end":{"row":6,"column":9},"action":"insert","lines":["r"]},{"start":{"row":6,"column":9},"end":{"row":6,"column":10},"action":"insert","lines":["n"]}],[{"start":{"row":6,"column":10},"end":{"row":6,"column":11},"action":"insert","lines":[" "],"id":27},{"start":{"row":6,"column":11},"end":{"row":6,"column":12},"action":"insert","lines":["r"]},{"start":{"row":6,"column":12},"end":{"row":6,"column":13},"action":"insert","lines":["e"]},{"start":{"row":6,"column":13},"end":{"row":6,"column":14},"action":"insert","lines":["d"]}],[{"start":{"row":6,"column":13},"end":{"row":6,"column":14},"action":"remove","lines":["d"],"id":28}],[{"start":{"row":6,"column":13},"end":{"row":6,"column":14},"action":"insert","lines":["n"],"id":29},{"start":{"row":6,"column":14},"end":{"row":6,"column":15},"action":"insert","lines":["d"]},{"start":{"row":6,"column":15},"end":{"row":6,"column":16},"action":"insert","lines":["e"]},{"start":{"row":6,"column":16},"end":{"row":6,"column":17},"action":"insert","lines":["r"]}],[{"start":{"row":6,"column":17},"end":{"row":6,"column":19},"action":"insert","lines":["()"],"id":30}],[{"start":{"row":6,"column":18},"end":{"row":6,"column":19},"action":"insert","lines":["r"],"id":31},{"start":{"row":6,"column":19},"end":{"row":6,"column":20},"action":"insert","lines":["e"]},{"start":{"row":6,"column":20},"end":{"row":6,"column":21},"action":"insert","lines":["q"]},{"start":{"row":6,"column":21},"end":{"row":6,"column":22},"action":"insert","lines":["u"]},{"start":{"row":6,"column":22},"end":{"row":6,"column":23},"action":"insert","lines":["e"]},{"start":{"row":6,"column":23},"end":{"row":6,"column":24},"action":"insert","lines":["s"]},{"start":{"row":6,"column":24},"end":{"row":6,"column":25},"action":"insert","lines":["t"]},{"start":{"row":6,"column":25},"end":{"row":6,"column":26},"action":"insert","lines":[","]}],[{"start":{"row":6,"column":26},"end":{"row":6,"column":27},"action":"insert","lines":[" "],"id":32}],[{"start":{"row":6,"column":27},"end":{"row":6,"column":29},"action":"insert","lines":["\"\""],"id":33}],[{"start":{"row":6,"column":28},"end":{"row":6,"column":29},"action":"insert","lines":["p"],"id":34},{"start":{"row":6,"column":29},"end":{"row":6,"column":30},"action":"insert","lines":["r"]},{"start":{"row":6,"column":30},"end":{"row":6,"column":31},"action":"insert","lines":["o"]},{"start":{"row":6,"column":31},"end":{"row":6,"column":32},"action":"insert","lines":["d"]},{"start":{"row":6,"column":32},"end":{"row":6,"column":33},"action":"insert","lines":["u"]},{"start":{"row":6,"column":33},"end":{"row":6,"column":34},"action":"insert","lines":["c"]},{"start":{"row":6,"column":34},"end":{"row":6,"column":35},"action":"insert","lines":["t"]},{"start":{"row":6,"column":35},"end":{"row":6,"column":36},"action":"insert","lines":["s"]},{"start":{"row":6,"column":36},"end":{"row":6,"column":37},"action":"insert","lines":["."]},{"start":{"row":6,"column":37},"end":{"row":6,"column":38},"action":"insert","lines":["h"]},{"start":{"row":6,"column":38},"end":{"row":6,"column":39},"action":"insert","lines":["t"]},{"start":{"row":6,"column":39},"end":{"row":6,"column":40},"action":"insert","lines":["m"]},{"start":{"row":6,"column":40},"end":{"row":6,"column":41},"action":"insert","lines":["l"]}],[{"start":{"row":6,"column":42},"end":{"row":6,"column":43},"action":"insert","lines":[","],"id":35}],[{"start":{"row":6,"column":43},"end":{"row":6,"column":44},"action":"insert","lines":[" "],"id":36}],[{"start":{"row":6,"column":44},"end":{"row":6,"column":46},"action":"insert","lines":["{}"],"id":37}],[{"start":{"row":6,"column":45},"end":{"row":6,"column":47},"action":"insert","lines":["\"\""],"id":38}],[{"start":{"row":6,"column":46},"end":{"row":6,"column":47},"action":"insert","lines":["p"],"id":39},{"start":{"row":6,"column":47},"end":{"row":6,"column":48},"action":"insert","lines":["r"]},{"start":{"row":6,"column":48},"end":{"row":6,"column":49},"action":"insert","lines":["o"]},{"start":{"row":6,"column":49},"end":{"row":6,"column":50},"action":"insert","lines":["d"]},{"start":{"row":6,"column":50},"end":{"row":6,"column":51},"action":"insert","lines":["u"]},{"start":{"row":6,"column":51},"end":{"row":6,"column":52},"action":"insert","lines":["c"]},{"start":{"row":6,"column":52},"end":{"row":6,"column":53},"action":"insert","lines":["t"]},{"start":{"row":6,"column":53},"end":{"row":6,"column":54},"action":"insert","lines":["s"]}],[{"start":{"row":6,"column":55},"end":{"row":6,"column":56},"action":"insert","lines":[":"],"id":40}],[{"start":{"row":6,"column":56},"end":{"row":6,"column":57},"action":"insert","lines":[" "],"id":41},{"start":{"row":6,"column":57},"end":{"row":6,"column":58},"action":"insert","lines":["p"]},{"start":{"row":6,"column":58},"end":{"row":6,"column":59},"action":"insert","lines":["r"]},{"start":{"row":6,"column":59},"end":{"row":6,"column":60},"action":"insert","lines":["o"]},{"start":{"row":6,"column":60},"end":{"row":6,"column":61},"action":"insert","lines":["d"]},{"start":{"row":6,"column":61},"end":{"row":6,"column":62},"action":"insert","lines":["u"]},{"start":{"row":6,"column":62},"end":{"row":6,"column":63},"action":"insert","lines":["c"]},{"start":{"row":6,"column":63},"end":{"row":6,"column":64},"action":"insert","lines":["t"]},{"start":{"row":6,"column":64},"end":{"row":6,"column":65},"action":"insert","lines":["s"]}]]},"timestamp":1583336017716}
[ "ubuntu@ip-172-31-36-97.ec2.internal" ]
ubuntu@ip-172-31-36-97.ec2.internal
69b0fa5230cadb504175821f7cb8097e99df18c4
901658f002f0d996fe17b9f1a241ccf95bdb82e3
/home/migrations/0002_auto_20200801_1224.py
76aa831a18ba7eb063bd34d75b1394c39ac08103
[]
no_license
OnurBoynuegri/RentHome
2d0fb308664d1095eaddafd5838982751a497c37
c20c934f9edbc8d9c7215d0d3f462769b5d048c7
refs/heads/master
2022-11-28T04:42:45.158688
2020-08-11T15:09:38
2020-08-11T15:09:38
280,904,461
0
0
null
null
null
null
UTF-8
Python
false
false
1,729
py
# Generated by Django 3.0.8 on 2020-08-01 09:24 import ckeditor_uploader.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ] operations = [ migrations.CreateModel( name='ContactFormMessage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=20)), ('email', models.CharField(blank=True, max_length=50)), ('subject', models.CharField(blank=True, max_length=50)), ('message', models.CharField(blank=True, max_length=255)), ('status', models.CharField(choices=[('New', 'New'), ('Read', 'Read')], default='New', max_length=10)), ('ip', models.CharField(blank=True, max_length=20)), ('note', models.CharField(blank=True, max_length=100)), ('create_at', models.DateTimeField(auto_now_add=True)), ('update_at', models.DateTimeField(auto_now=True)), ], ), migrations.AlterField( model_name='setting', name='aboutus', field=ckeditor_uploader.fields.RichTextUploadingField(blank=True), ), migrations.AlterField( model_name='setting', name='contact', field=ckeditor_uploader.fields.RichTextUploadingField(blank=True), ), migrations.AlterField( model_name='setting', name='references', field=ckeditor_uploader.fields.RichTextUploadingField(blank=True), ), ]
[ "onurboynueğri@gmail.com" ]
onurboynueğri@gmail.com
61bb250a081ee773aa1aa16082aa203ec3a1eefd
0378c82c8bcd5501732acc27d1d33b3230f9a393
/KYLIN_USB/sources/spark/load/sources/020-mds_elt_niveau.py
1d935431623fd660c2a5018af23ee80f7d2fefbf
[]
no_license
bmwalid/Controlla
85718a94e47acdc2a90ee06b951282954dc1ed11
c63febd9aeb1ae268b79ade1880d867a888554d0
refs/heads/master
2020-04-29T16:15:27.646599
2019-03-19T16:40:36
2019-03-19T16:40:36
176,252,951
0
0
null
null
null
null
UTF-8
Python
false
false
1,726
py
# import Libraries from pyspark.conf import SparkConf from pyspark.sql import SparkSession from pyspark.sql.types import * # init sparkConf conf = SparkConf() conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer") \ .set("spark.executor.cores", "1") \ .set("spark.executor.memory", "1G") # Initialize Spark Session spark = SparkSession.builder.appName("020-mds_elt_niveau").config(conf=SparkConf()).enableHiveSupport().getOrCreate() # Data path path = "s3://decathlon-ods/ods/mds_elt_niveau/*.gz" # From gz files on S3 to Spark Dataframe df = spark.read.option("header", "false").option("delimiter", "|").csv(path) # write to hdfs df.select("_c0", "_c1", "_c2", "_c6", "_c7", "_c3", "_c4", "_c5") \ .withColumn("org_num_organisation_niv", df["_c0"].cast(IntegerType())) \ .withColumn("niv_num_niveau_niv", df["_c1"].cast(StringType())) \ .withColumn("eln_num_elt_niveau", df["_c2"].cast(IntegerType())) \ .withColumn("tlb_typ_libelle_lib", df["_c6"].cast(StringType())) \ .withColumn("lib_num_libelle_lib", df["_c7"].cast(IntegerType())) \ .withColumn("org_num_organisation_sup", df["_c3"].cast(IntegerType())) \ .withColumn("niv_num_niveau_sup", df["_c4"].cast(IntegerType())) \ .withColumn("eln_num_elt_niveau_sup", df["_c5"].cast(IntegerType())) \ .select("org_num_organisation_niv", "niv_num_niveau_niv", "eln_num_elt_niveau", "tlb_typ_libelle_lib", "lib_num_libelle_lib", "org_num_organisation_sup", "niv_num_niveau_sup", "eln_num_elt_niveau_sup") \ .repartition(80).write.option("compression", "snappy").mode("overwrite").format("parquet").saveAsTable( "kylin_usb_mqb.mds_elt_niveau") # stopping session spark.sparkContext.stop()
[ "bmwalide@gmail.com" ]
bmwalide@gmail.com
3b6282d79f208c7ee3adea1226ff383f5e2e6fd3
4edbd8a42011e7f6db0cecf55a3f87a647c2ac1e
/expected_move.py
9cfae8fc004e6c88df9dab63e846d2516a4b0d8a
[]
no_license
k6116/zebra
fe220ff0c1278f6ea20a06d030080345b540902d
0aa0ba9a294d557d41377b112a624a294adbebf5
refs/heads/master
2022-11-08T07:54:20.415663
2020-06-27T19:03:43
2020-06-27T19:03:43
275,326,505
0
0
null
null
null
null
UTF-8
Python
false
false
4,378
py
import models from database import SessionLocal, engine from models import Stock, Option from sqlalchemy.orm import Session from sqlalchemy import and_, or_, desc, asc import math import tools import numpy as np def get_expected_move(symbol, underlying_price, dte): two_atm_call_iv = None strikes = tools.strike_increments(symbol, dte) # print('strikes') # print(strikes) # print('underlying_price') # print(underlying_price) if strikes[0] < underlying_price and underlying_price < strikes[len(strikes) - 1]: two_atm_strikes = two_ntm_strikes(strikes, underlying_price) two_atm_call_iv = tools.get_option_prop(symbol, two_atm_strikes, 'CALL', 'impliedVolatility', dte) two_atm_put_iv = tools.get_option_prop(symbol, two_atm_strikes, 'PUT', 'impliedVolatility', dte) print('dte: ' + str(dte)) print('two_atm_strikes') print(two_atm_strikes) # print('two_atm_call_iv') # print(two_atm_call_iv) expected_move_iv = calc_expected_move_iv(underlying_price, two_atm_call_iv, two_atm_put_iv, dte) return expected_move_iv else: return None def calc_expected_move_iv(underlying_price, call_iv, put_iv, dte): iv_sum = 0 for val in call_iv: iv_sum = iv_sum + val # print('iv_sum: ' + str(iv_sum)) for val in put_iv: iv_sum = iv_sum + val # print('iv_sum: ' + str(iv_sum)) avg_iv = iv_sum / 4 expected_move = float(underlying_price) * (float(avg_iv) / 100) * (math.sqrt(int(dte)) / math.sqrt(365)) # print('iv: ' + str(avg_iv)) return expected_move def two_ntm_strikes(strikes, underlying_price): # find 2 near-the-money strikes # First find the atm_strike strike_1 = tools.find_atm_strike_index(strikes, underlying_price) # If the underlying_price is less than the initial strike price if (underlying_price < strikes[strike_1]): strike_2 = strike_1 - 1 else: strike_2 = strike_1 + 1 return sorted([strikes[strike_1], strikes[strike_2]], key=float) def get_expected_move_premium(symbol, underlying_price, dte): strikes = tools.strike_increments(symbol, dte) if strikes[0] < underlying_price and underlying_price < strikes[len(strikes) - 1]: if len(strikes) > 1: two_atm_strikes = two_ntm_strikes(strikes, underlying_price) two_premium_calls_bids = tools.get_option_prop(symbol, two_atm_strikes, 'CALL', 'bid', dte) two_premium_calls_asks = tools.get_option_prop(symbol, two_atm_strikes, 'CALL', 'ask', dte) two_premium_puts_bids = tools.get_option_prop(symbol, two_atm_strikes, 'PUT', 'bid', dte) two_premium_puts_asks = tools.get_option_prop(symbol, two_atm_strikes, 'PUT', 'ask', dte) # Since the underlying price won't be exactly on a strike, calculate the weighted difference between the nearest strikes strike_diff = abs(two_atm_strikes[1] - two_atm_strikes[0]) price_distance = abs(underlying_price - two_atm_strikes[1]) price_distance_percent = price_distance / strike_diff two_premium_calls_mid = (np.array(two_premium_calls_bids) + np.array(two_premium_calls_asks)) / 2.0 two_premium_puts_mid = (np.array(two_premium_puts_bids) + np.array(two_premium_puts_asks)) / 2.0 two_premium_calls_mid_diff = abs(two_premium_calls_mid[1] - two_premium_calls_mid[0]) two_premium_puts_mid_diff = abs(two_premium_puts_mid[1] - two_premium_puts_mid[0]) premium_call = two_premium_calls_mid[1] + (two_premium_calls_mid_diff * price_distance_percent) premium_put = two_premium_puts_mid[1] - (two_premium_puts_mid_diff * price_distance_percent) # print('premium_put') # print(premium_put) expected_move_premium = calc_expected_move_premium(underlying_price, premium_call, premium_put, dte) return expected_move_premium else: return None def calc_expected_move_premium(underlying_price, prem_call, prem_put, dte): # average the two calls and puts premiums total_prem = prem_call + prem_put expected_move_premium_percent = total_prem * 85 / underlying_price expected_move_calc = expected_move_premium_percent / 100 * underlying_price return expected_move_calc
[ "2784285+k6116@users.noreply.github.com" ]
2784285+k6116@users.noreply.github.com