INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
expr : expr LBRACE expr_list RBRACE | expr LBRACE RBRACE
def p_cellarrayref(p): """expr : expr LBRACE expr_list RBRACE | expr LBRACE RBRACE """ args = node.expr_list() if len(p) == 4 else p[3] assert isinstance(args, node.expr_list) p[0] = node.cellarrayref(func_expr=p[1], args=args)
concat_list : expr_list SEMI expr_list | concat_list SEMI expr_list
def p_concat_list(p): """ concat_list : expr_list SEMI expr_list | concat_list SEMI expr_list """ if p[1].__class__ == node.expr_list: p[0] = node.concat_list([p[1], p[3]]) else: p[0] = p[1] p[0].append(p[3])
elseif_stmt : | ELSE stmt_list_opt | ELSEIF expr sep stmt_list_opt elseif_stmt | ELSEIF LPAREN expr RPAREN stmt_list_opt elseif_stmt
def p_elseif_stmt(p): """ elseif_stmt : | ELSE stmt_list_opt | ELSEIF expr sep stmt_list_opt elseif_stmt | ELSEIF LPAREN expr RPAREN stmt_list_opt elseif_stmt """ if len(p) == 1: p[0] = node.stmt_list() elif len(p) == 3: p[0] = p[2] ...
expr1 : MINUS expr %prec UMINUS | PLUS expr %prec UMINUS | NEG expr | HANDLE ident | PLUSPLUS ident | MINUSMINUS ident
def p_expr1(p): """expr1 : MINUS expr %prec UMINUS | PLUS expr %prec UMINUS | NEG expr | HANDLE ident | PLUSPLUS ident | MINUSMINUS ident """ p[0] = node.expr(op=p[1], args=node.expr_list([p[2]]))
expr2 : expr AND expr | expr ANDAND expr | expr BACKSLASH expr | expr COLON expr | expr DIV expr | expr DOT expr | expr DOTDIV expr | expr DOTDIVEQ expr | expr DOTEXP expr | expr DOTMUL expr ...
def p_expr2(p): """expr2 : expr AND expr | expr ANDAND expr | expr BACKSLASH expr | expr COLON expr | expr DIV expr | expr DOT expr | expr DOTDIV expr | expr DOTDIVEQ expr | expr DOTEXP expr | expr D...
end : END_EXPR
def p_expr_end(p): "end : END_EXPR" p[0] = node.expr( op="end", args=node.expr_list([node.number(0), node.number(0)]))
ident : IDENT
def p_expr_ident(p): "ident : IDENT" global use_nargin, use_varargin if p[1] == "varargin": use_varargin = 1 if p[1] == "nargin": use_nargin = 1 # import pdb; pdb.set_trace() p[0] = node.ident( name=p[1], lineno=p.lineno(1), column=p.lexpos(1) - p.lexer.le...
ident_init_opt : NEG | ident | ident EQ expr
def p_ident_init_opt(p): """ ident_init_opt : NEG | ident | ident EQ expr """ if p[1] == '~': p[0] = node.ident("__") else: p[0] = p[1] if len(p) == 2: p[0].init = node.ident(name="None") else: p[0].init = p[3]
number : NUMBER
def p_expr_number(p): "number : NUMBER" p[0] = node.number(p[1], lineno=p.lineno(1), lexpos=p.lexpos(1))
expr_stmt : expr_list SEMI
def p_expr_stmt(p): """ expr_stmt : expr_list SEMI """ assert isinstance(p[1], node.expr_list) p[0] = node.expr_stmt(expr=p[1])
string : STRING
def p_expr_string(p): "string : STRING" p[0] = node.string(p[1], lineno=p.lineno(1), lexpos=p.lexpos(1))
exprs : expr | exprs COMMA expr
def p_exprs(p): """ exprs : expr | exprs COMMA expr """ if len(p) == 2: p[0] = node.expr_list([p[1]]) elif len(p) == 4: p[0] = p[1] p[0].append(p[3]) else: assert (0) assert isinstance(p[0], node.expr_list)
expr : expr FIELD
def p_field_expr(p): """ expr : expr FIELD """ p[0] = node.expr( op=".", args=node.expr_list([ p[1], node.ident( name=p[2], lineno=p.lineno(2), lexpos=p.lexpos(2)) ]))
foo_stmt : expr OROR expr SEMI
def p_foo_stmt(p): "foo_stmt : expr OROR expr SEMI" expr1 = p[1][1][0] expr2 = p[3][1][0] ident = expr1.ret args1 = expr1.args args2 = expr2.args p[0] = node.let(ret=ident, args=node.expr("or", node.expr_list([args1, args2])))
for_stmt : FOR ident EQ expr SEMI stmt_list END_STMT | FOR LPAREN ident EQ expr RPAREN SEMI stmt_list END_STMT | FOR matrix EQ expr SEMI stmt_list END_STMT
def p_for_stmt(p): """ for_stmt : FOR ident EQ expr SEMI stmt_list END_STMT | FOR LPAREN ident EQ expr RPAREN SEMI stmt_list END_STMT | FOR matrix EQ expr SEMI stmt_list END_STMT """ if len(p) == 8: if not isinstance(p[2], node.ident): raise_exception(Syntax...
func_stmt : FUNCTION ident lambda_args SEMI | FUNCTION ret EQ ident lambda_args SEMI
def p_func_stmt(p): """func_stmt : FUNCTION ident lambda_args SEMI | FUNCTION ret EQ ident lambda_args SEMI """ # stmt_list of func_stmt is set below # marked with XYZZY global ret_expr, use_nargin, use_varargin ret_expr = node.expr_list() use_varargin = use_nargin = 0 ...
expr : expr LPAREN expr_list RPAREN | expr LPAREN RPAREN
def p_funcall_expr(p): """expr : expr LPAREN expr_list RPAREN | expr LPAREN RPAREN """ if (len(p) == 5 and len(p[3]) == 1 and p[3][0].__class__ is node.expr and p[3][0].op == ":" and not p[3][0].args): # foo(:) => ravel(foo) p[0] = node.funcall( func_expr=...
global_list : ident | global_list ident
def p_global_list(p): """global_list : ident | global_list ident """ if len(p) == 2: p[0] = node.global_list([p[1]]) elif len(p) == 3: p[0] = p[1] p[0].append(p[2])
global_stmt : GLOBAL global_list SEMI | GLOBAL ident EQ expr SEMI
def p_global_stmt(p): """ global_stmt : GLOBAL global_list SEMI | GLOBAL ident EQ expr SEMI """ p[0] = node.global_stmt(p[2]) for ident in p[0]: ident.props = "G"
if_stmt : IF expr sep stmt_list_opt elseif_stmt END_STMT | IF LPAREN expr RPAREN stmt_list_opt elseif_stmt END_STMT
def p_if_stmt(p): """ if_stmt : IF expr sep stmt_list_opt elseif_stmt END_STMT | IF LPAREN expr RPAREN stmt_list_opt elseif_stmt END_STMT """ if len(p) == 7: p[0] = node.if_stmt(cond_expr=p[2], then_stmt=p[4], else_stmt=p[5]) elif len(p) == 8: p[0] = node.if_stmt(cond_exp...
matrix : LBRACKET RBRACKET | LBRACKET concat_list RBRACKET | LBRACKET concat_list SEMI RBRACKET | LBRACKET expr_list RBRACKET | LBRACKET expr_list SEMI RBRACKET
def p_matrix(p): """matrix : LBRACKET RBRACKET | LBRACKET concat_list RBRACKET | LBRACKET concat_list SEMI RBRACKET | LBRACKET expr_list RBRACKET | LBRACKET expr_list SEMI RBRACKET """ if len(p) == 3: p[0] = node.matrix() else: p[0]...
expr : LPAREN expr RPAREN
def p_parens_expr(p): """ expr : LPAREN expr RPAREN """ p[0] = node.expr(op="parens", args=node.expr_list([p[2]]))
ret : ident | LBRACKET RBRACKET | LBRACKET expr_list RBRACKET
def p_ret(p): """ ret : ident | LBRACKET RBRACKET | LBRACKET expr_list RBRACKET """ if len(p) == 2: p[0] = node.expr_list([p[1]]) elif len(p) == 3: p[0] = node.expr_list([]) elif len(p) == 4: assert isinstance(p[2], node.expr_list) p[0] = p[2] ...
stmt_list : stmt | stmt_list stmt
def p_stmt_list(p): """ stmt_list : stmt | stmt_list stmt """ if len(p) == 2: p[0] = node.stmt_list([p[1]] if p[1] else []) elif len(p) == 3: p[0] = p[1] if p[2]: p[0].append(p[2]) else: assert 0
switch_stmt : SWITCH expr semi_opt case_list END_STMT
def p_switch_stmt(p): """ switch_stmt : SWITCH expr semi_opt case_list END_STMT """ def backpatch(expr, stmt): if isinstance(stmt, node.if_stmt): stmt.cond_expr.args[1] = expr backpatch(expr, stmt.else_stmt) backpatch(p[2], p[4]) p[0] = p[4]
try_catch : TRY stmt_list CATCH stmt_list END_STMT
def p_try_catch(p): """ try_catch : TRY stmt_list CATCH stmt_list END_STMT """ ## | TRY stmt_list END_STMT assert isinstance(p[2], node.stmt_list) # assert isinstance(p[4],node.stmt_list) p[0] = node.try_catch( try_stmt=p[2], catch_stmt=p[4], finally_stmt=node.stmt_li...
unwind : UNWIND_PROTECT stmt_list UNWIND_PROTECT_CLEANUP stmt_list END_UNWIND_PROTECT
def p_unwind(p): """ unwind : UNWIND_PROTECT stmt_list UNWIND_PROTECT_CLEANUP stmt_list END_UNWIND_PROTECT """ p[0] = node.try_catch( try_stmt=p[2], catch_stmt=node.expr_list(), finally_stmt=p[4])
while_stmt : WHILE expr SEMI stmt_list END_STMT
def p_while_stmt(p): """ while_stmt : WHILE expr SEMI stmt_list END_STMT """ assert isinstance(p[4], node.stmt_list) p[0] = node.while_stmt(cond_expr=p[2], stmt_list=p[4])
To the parser, funcall is indistinguishable from rhs array reference. But LHS references can be converted to arrayref nodes.
def to_arrayref(u): """ To the parser, funcall is indistinguishable from rhs array reference. But LHS references can be converted to arrayref nodes. """ if u.__class__ is node.funcall: try: if u.func_expr.props in "UR": # upd,ref u.__class__ = node.arrayref ...
Array colon subscripts foo(1:10) and colon expressions 1:10 look too similar to each other. Now is the time to find out who is who.
def colon_subscripts(u): """ Array colon subscripts foo(1:10) and colon expressions 1:10 look too similar to each other. Now is the time to find out who is who. """ if u.__class__ in (node.arrayref,node.cellarrayref): for w in u.args: if w.__class__ is node.expr and w.op == ":":...
If LHS is a plain variable, and RHS is a matrix enclosed in square brackets, replace the matrix expr with a funcall.
def let_statement(u): """ If LHS is a plain variable, and RHS is a matrix enclosed in square brackets, replace the matrix expr with a funcall. """ if u.__class__ is node.let: if (u.ret.__class__ is node.ident and u.args.__class__ is node.matrix): u.args = node.fun...
Convert "+++"/"---" formatted win/loss streak column into a +/- integer column
def process_win_streak(data): """ Convert "+++"/"---" formatted win/loss streak column into a +/- integer column """ #only do this if there are non-NANs in the column if data['Streak'].count()>0: data['Streak2'] = data['Streak'].str.len() data.loc[data['Streak'].str[0]=='-','Streak2'...
Splits Statcast queries to avoid request timeouts
def split_request(start_dt, end_dt, player_id, url): """ Splits Statcast queries to avoid request timeouts """ current_dt = datetime.datetime.strptime(start_dt, '%Y-%m-%d') end_dt = datetime.datetime.strptime(end_dt, '%Y-%m-%d') results = [] # list to hold data as it is returned player_id =...
Get zip file from provided URL
def get_zip_file(url): """ Get zip file from provided URL """ with requests.get(url, stream=True) as f: z = zipfile.ZipFile(io.BytesIO(f.content)) return z
Pulls statcast pitch-level data from Baseball Savant for a given pitcher. ARGUMENTS start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data end_dt : YYYY-MM-DD : the final date for which you want data player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.pl...
def statcast_pitcher(start_dt=None, end_dt=None, player_id=None): """ Pulls statcast pitch-level data from Baseball Savant for a given pitcher. ARGUMENTS start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data end_dt : YYYY-MM-DD : the final date for which you want data ...
Get all batting stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format.
def batting_stats_range(start_dt=None, end_dt=None): """ Get all batting stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format. """ # make sure date inputs are valid start_dt, end_dt = sanitize_input(star...
Get all batting stats for a set season. If no argument is supplied, gives stats for current season to date.
def batting_stats_bref(season=None): """ Get all batting stats for a set season. If no argument is supplied, gives stats for current season to date. """ if season is None: season = datetime.datetime.today().strftime("%Y") season = str(season) start_dt = season + '-03-01' #opening day...
Pull Retrosheet game logs for a given season
def season_game_logs(season): """ Pull Retrosheet game logs for a given season """ # validate input max_year = int(datetime.now().year) - 1 if season > max_year or season < 1871: raise ValueError('Season must be between 1871 and {}'.format(max_year)) file_name = 'GL{}.TXT'.format(sea...
Pull Retrosheet World Series Game Logs
def world_series_logs(): """ Pull Retrosheet World Series Game Logs """ file_name = 'GLWS.TXT' z = get_zip_file(world_series_url) data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"') data.columns = gamelog_columns return data
Pull Retrosheet All Star Game Logs
def all_star_game_logs(): """ Pull Retrosheet All Star Game Logs """ file_name = 'GLAS.TXT' z = get_zip_file(all_star_url) data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"') data.columns = gamelog_columns return data
Pull Retrosheet Wild Card Game Logs
def wild_card_logs(): """ Pull Retrosheet Wild Card Game Logs """ file_name = 'GLWC.TXT' z = get_zip_file(wild_card_url) data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"') data.columns = gamelog_columns return data
Pull Retrosheet Division Series Game Logs
def division_series_logs(): """ Pull Retrosheet Division Series Game Logs """ file_name = 'GLDV.TXT' z = get_zip_file(division_series_url) data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"') data.columns = gamelog_columns return data
Pull Retrosheet LCS Game Logs
def lcs_logs(): """ Pull Retrosheet LCS Game Logs """ file_name = 'GLLC.TXT' z = get_zip_file(lcs_url) data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"') data.columns = gamelog_columns return data
Get season-level pitching data aggregated by team. ARGUMENTS: start_season : int : first season you want data for (or the only season if you do not specify an end_season) end_season : int : final season you want data for league : "all", "nl", or "al" ind : int : =1 if you want individual season l...
def team_pitching(start_season, end_season=None, league='all', ind=1): """ Get season-level pitching data aggregated by team. ARGUMENTS: start_season : int : first season you want data for (or the only season if you do not specify an end_season) end_season : int : final season you want data for ...
Get season-level Pitching Statistics for Specific Team (from Baseball-Reference) ARGUMENTS: team : str : The Team Abbreviation (i.e. 'NYY' for Yankees) of the Team you want data for start_season : int : first season you want data for (or the only season if you do not specify an end_season) end_season :...
def team_pitching_bref(team, start_season, end_season=None): """ Get season-level Pitching Statistics for Specific Team (from Baseball-Reference) ARGUMENTS: team : str : The Team Abbreviation (i.e. 'NYY' for Yankees) of the Team you want data for start_season : int : first season you want data for ...
Pulls statcast pitch-level data from Baseball Savant for a given batter. ARGUMENTS start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data end_dt : YYYY-MM-DD : the final date for which you want data player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.pla...
def statcast_batter(start_dt=None, end_dt=None, player_id=None): """ Pulls statcast pitch-level data from Baseball Savant for a given batter. ARGUMENTS start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data end_dt : YYYY-MM-DD : the final date for which you want data ...
Retrieve a table of player information given a list of player ids :param player_ids: list of player ids :type player_ids: list :param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs") :type key_type: str :rtype: :class:`pandas.core.frame.DataFrame`
def playerid_reverse_lookup(player_ids, key_type=None): """Retrieve a table of player information given a list of player ids :param player_ids: list of player ids :type player_ids: list :param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs") :type ke...
Get season-level pitching data from FanGraphs. ARGUMENTS: start_season : int : first season you want data for (or the only season if you do not specify an end_season) end_season : int : final season you want data for league : "all", "nl", or "al" qual: minimum number of pitches thrown to be inclu...
def pitching_stats(start_season, end_season=None, league='all', qual=1, ind=1): """ Get season-level pitching data from FanGraphs. ARGUMENTS: start_season : int : first season you want data for (or the only season if you do not specify an end_season) end_season : int : final season you want data f...
break start and end date into smaller increments, collecting all data in small chunks and appending all results to a common dataframe end_dt is the date strings for the final day of the query d1 and d2 are datetime objects for first and last day of query, for doing date math a third datetime object (d) will...
def large_request(start_dt,end_dt,d1,d2,step,verbose): """ break start and end date into smaller increments, collecting all data in small chunks and appending all results to a common dataframe end_dt is the date strings for the final day of the query d1 and d2 are datetime objects for first and last day...
Pulls statcast play-level data from Baseball Savant for a given date range. INPUTS: start_dt: YYYY-MM-DD : the first date for which you want statcast data end_dt: YYYY-MM-DD : the last date for which you want statcast data team: optional (defaults to None) : city abbreviation of the team you want data ...
def statcast(start_dt=None, end_dt=None, team=None, verbose=True): """ Pulls statcast play-level data from Baseball Savant for a given date range. INPUTS: start_dt: YYYY-MM-DD : the first date for which you want statcast data end_dt: YYYY-MM-DD : the last date for which you want statcast data t...
Pulls statcast play-level data from Baseball Savant for a single game, identified by its MLB game ID (game_pk in statcast data) INPUTS: game_pk : 6-digit integer MLB game ID to retrieve
def statcast_single_game(game_pk, team=None): """ Pulls statcast play-level data from Baseball Savant for a single game, identified by its MLB game ID (game_pk in statcast data) INPUTS: game_pk : 6-digit integer MLB game ID to retrieve """ data = single_game_request(game_pk) data = post...
Get all pitching stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format.
def pitching_stats_range(start_dt=None, end_dt=None): """ Get all pitching stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format. """ # ensure valid date strings, perform necessary processing for query ...
Get all pitching stats for a set season. If no argument is supplied, gives stats for current season to date.
def pitching_stats_bref(season=None): """ Get all pitching stats for a set season. If no argument is supplied, gives stats for current season to date. """ if season is None: season = datetime.datetime.today().strftime("%Y") season = str(season) start_dt = season + '-03-01' #opening...
Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats. To get all fields from this table, supply argument return_all=True.
def bwar_pitch(return_all=False): """ Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats. To get all fields from this table, supply argument return_all=True. """ url = "http://www.baseball-reference.com/data/war_daily_pitch.txt" s = requests.get(url...
Decorator to mark a specified function as deprecated :param version: version in which it is deprecated :param replacement: replacement functions to use
def deprecated(version, *replacement): """ Decorator to mark a specified function as deprecated :param version: version in which it is deprecated :param replacement: replacement functions to use """ def deprecated_wrapper(func): replacement_message = 'Use {} instead'.format(', '.join( ...
Returns a dictionary in cloud format :param restrict_keys: a set of keys to restrict the returned data to.
def to_api_data(self, restrict_keys=None): """ Returns a dictionary in cloud format :param restrict_keys: a set of keys to restrict the returned data to. """ cc = self._cc # alias data = { cc('displayName'): self.__display_name, cc('givenName'): self.__...
Deletes this contact :return: Success or Failure :rtype: bool :raises RuntimeError: if contact is not yet saved to cloud
def delete(self): """ Deletes this contact :return: Success or Failure :rtype: bool :raises RuntimeError: if contact is not yet saved to cloud """ if not self.object_id: raise RuntimeError('Attempting to delete an unsaved Contact') url = self.build_u...
Saves this contact to the cloud (create or update existing one based on what values have changed) :return: Saved or Not :rtype: bool
def save(self): """ Saves this contact to the cloud (create or update existing one based on what values have changed) :return: Saved or Not :rtype: bool """ if self.object_id: # Update Contact if not self._track_changes: return Tru...
This method returns a new draft Message instance with contacts first email as a recipient :param Recipient recipient: a Recipient instance where to send this message. If None first email of this contact will be used :param RecipientType recipient_type: section to add recipient into ...
def new_message(self, recipient=None, *, recipient_type=RecipientType.TO): """ This method returns a new draft Message instance with contacts first email as a recipient :param Recipient recipient: a Recipient instance where to send this message. If None first email of this contact will...
Gets a list of contacts from this address book When querying the Global Address List the Users endpoint will be used. Only a limited set of information will be available unless you have access to scope 'User.Read.All' which requires App Administration Consent. Also using endpoi...
def get_contacts(self, limit=100, *, query=None, order_by=None, batch=None): """ Gets a list of contacts from this address book When querying the Global Address List the Users endpoint will be used. Only a limited set of information will be available unless you have access to scope 'Use...
Returns a Contact by it's email :param email: email to get contact for :return: Contact for specified email :rtype: Contact
def get_contact_by_email(self, email): """ Returns a Contact by it's email :param email: email to get contact for :return: Contact for specified email :rtype: Contact """ if not email: return None email = email.strip() query = self.q().any(co...
Returns a list of child folders :param int limit: max no. of folders to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :re...
def get_folders(self, limit=None, *, query=None, order_by=None): """ Returns a list of child folders :param int limit: max no. of folders to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result...
Creates a new child folder :param str folder_name: name of the new folder to create :return: newly created folder :rtype: ContactFolder or None
def create_child_folder(self, folder_name): """ Creates a new child folder :param str folder_name: name of the new folder to create :return: newly created folder :rtype: ContactFolder or None """ if not folder_name: return None if self.root: ...
Change this folder name :param str name: new name to change to :return: Updated or Not :rtype: bool
def update_folder_name(self, name): """ Change this folder name :param str name: new name to change to :return: Updated or Not :rtype: bool """ if self.root: return False if not name: return False url = self.build_url( ...
Change this folder name :param to_folder: folder_id/ContactFolder to move into :type to_folder: str or ContactFolder :return: Moved or Not :rtype: bool
def move_folder(self, to_folder): """ Change this folder name :param to_folder: folder_id/ContactFolder to move into :type to_folder: str or ContactFolder :return: Moved or Not :rtype: bool """ if self.root: return False if not to_folder: ...
Creates a new contact to be saved into it's parent folder :return: newly created contact :rtype: Contact
def new_contact(self): """ Creates a new contact to be saved into it's parent folder :return: newly created contact :rtype: Contact """ contact = self.contact_constructor(parent=self) if not self.root: contact.__folder_id = self.folder_id return conta...
This method returns a new draft Message instance with all the contacts first email as a recipient :param RecipientType recipient_type: section to add recipient into :param query: applies a OData filter to the request :type query: Query or str :return: newly created message ...
def new_message(self, recipient_type=RecipientType.TO, *, query=None): """ This method returns a new draft Message instance with all the contacts first email as a recipient :param RecipientType recipient_type: section to add recipient into :param query: applies a OData filter to the req...
Returns a Contact by it's email :param email: email to get contact for :return: Contact for specified email :rtype: Contact
def get_contact_by_email(self, email): """ Returns a Contact by it's email :param email: email to get contact for :return: Contact for specified email :rtype: Contact """ if not email: return None email = email.strip() url = self.build_url('...
Sets this message as flagged :param start_date: the start datetime of the followUp :param due_date: the due datetime of the followUp
def set_flagged(self, *, start_date=None, due_date=None): """ Sets this message as flagged :param start_date: the start datetime of the followUp :param due_date: the due datetime of the followUp """ self.__status = Flag.Flagged start_date = start_date or dt.datetime.now()...
Sets this message flag as completed :param completition_date: the datetime this followUp was completed
def set_completed(self, *, completition_date=None): """ Sets this message flag as completed :param completition_date: the datetime this followUp was completed """ self.__status = Flag.Complete completition_date = completition_date or dt.datetime.now() if completition_date...
Sets this message as un flagged
def delete_flag(self): """ Sets this message as un flagged """ self.__status = Flag.NotFlagged self.__start = None self.__due_date = None self.__completed = None self._track_changes()
Returns this data as a dict to be sent to the server
def to_api_data(self): """ Returns this data as a dict to be sent to the server """ data = { self._cc('flagStatus'): self._cc(self.__status.value) } if self.__status is Flag.Flagged: data[self._cc('startDateTime')] = self._build_date_time_time_zone(self.__start) ...
sender is a property to force to be always a Recipient class
def sender(self, value): """ sender is a property to force to be always a Recipient class """ if isinstance(value, Recipient): if value._parent is None: value._parent = self value._field = 'from' self.__sender = value elif isinstance(value,...
Returns a dict representation of this message prepared to be send to the cloud :param restrict_keys: a set of keys to restrict the returned data to :type restrict_keys: dict or set :return: converted to cloud based keys :rtype: dict
def to_api_data(self, restrict_keys=None): """ Returns a dict representation of this message prepared to be send to the cloud :param restrict_keys: a set of keys to restrict the returned data to :type restrict_keys: dict or set :return: converted to cloud based keys ...
Sends this message :param bool save_to_sent_folder: whether or not to save it to sent folder :return: Success / Failure :rtype: bool
def send(self, save_to_sent_folder=True): """ Sends this message :param bool save_to_sent_folder: whether or not to save it to sent folder :return: Success / Failure :rtype: bool """ if self.object_id and not self.__is_draft: return RuntimeError('No...
Creates a new message that is a reply to this message :param bool to_all: whether or not to replies to all the recipients instead to just the sender :return: new message :rtype: Message
def reply(self, to_all=True): """ Creates a new message that is a reply to this message :param bool to_all: whether or not to replies to all the recipients instead to just the sender :return: new message :rtype: Message """ if not self.object_id or self.__is_dr...
Creates a new message that is a forward this message :return: new message :rtype: Message
def forward(self): """ Creates a new message that is a forward this message :return: new message :rtype: Message """ if not self.object_id or self.__is_draft: raise RuntimeError("Can't forward this message") url = self.build_url( self._endpoints...
Marks this message as read in the cloud :return: Success / Failure :rtype: bool
def mark_as_read(self): """ Marks this message as read in the cloud :return: Success / Failure :rtype: bool """ if self.object_id is None or self.__is_draft: raise RuntimeError('Attempting to mark as read an unsaved Message') data = {self._cc('isRead'): True...
Move the message to a given folder :param folder: Folder object or Folder id or Well-known name to move this message to :type folder: str or mailbox.Folder :return: Success / Failure :rtype: bool
def move(self, folder): """ Move the message to a given folder :param folder: Folder object or Folder id or Well-known name to move this message to :type folder: str or mailbox.Folder :return: Success / Failure :rtype: bool """ if self.object_id is None:...
Copy the message to a given folder :param folder: Folder object or Folder id or Well-known name to copy this message to :type folder: str or mailbox.Folder :returns: the copied message :rtype: Message
def copy(self, folder): """ Copy the message to a given folder :param folder: Folder object or Folder id or Well-known name to copy this message to :type folder: str or mailbox.Folder :returns: the copied message :rtype: Message """ if self.object_id is ...
Saves changes to a message. If the message is a new or saved draft it will call 'save_draft' otherwise this will save only properties of a message that are draft-independent such as: - is_read - category - flag :return: Success / Failure :rtype: bool
def save_message(self): """ Saves changes to a message. If the message is a new or saved draft it will call 'save_draft' otherwise this will save only properties of a message that are draft-independent such as: - is_read - category - flag :return: Succ...
Save this message as a draft on the cloud :param target_folder: name of the drafts folder :return: Success / Failure :rtype: bool
def save_draft(self, target_folder=OutlookWellKnowFolderNames.DRAFTS): """ Save this message as a draft on the cloud :param target_folder: name of the drafts folder :return: Success / Failure :rtype: bool """ if self.object_id: # update message. Attachments ...
If this is a EventMessage it should return the related Event
def get_event(self): """ If this is a EventMessage it should return the related Event""" if not self.is_event_message: return None # select a dummy field (eg. subject) to avoid pull unneccesary data query = self.q().select('subject').expand('event') url = self.buil...
Builds the distribution files: wheels and source.
def build(force): """ Builds the distribution files: wheels and source. """ dist_path = Path(DIST_PATH) if dist_path.exists() and list(dist_path.glob('*')): if force or click.confirm('{} is not empty - delete contents?'.format(dist_path)): dist_path.rename(DIST_PATH_DELETE) s...
Uploads distribuition files to pypi or pypitest.
def upload(ctx, release, rebuild): """ Uploads distribuition files to pypi or pypitest. """ dist_path = Path(DIST_PATH) if rebuild is False: if not dist_path.exists() or not list(dist_path.glob('*')): print("No distribution files found. Please run 'build' command first") retu...
Checks the long description.
def check(): """ Checks the long description. """ dist_path = Path(DIST_PATH) if not dist_path.exists() or not list(dist_path.glob('*')): print("No distribution files found. Please run 'build' command first") return subprocess.check_call(['twine', 'check', 'dist/*'])
Lists all releases published on pypi.
def list_releases(): """ Lists all releases published on pypi. """ response = requests.get(PYPI_URL.format(package=PYPI_PACKAGE_NAME)) if response: data = response.json() releases_dict = data.get('releases', {}) if releases_dict: for version, release in releases_dict.it...
Displays a table of the contributors and to what extent we have them to thank.
def contribution_breakdown(): """ Displays a table of the contributors and to what extent we have them to thank.""" args = ['git', 'blame'] counts = {} line_format = '{0:30}\t{1:>10}\t{2:>10}%' files = subprocess.check_output(['git', 'ls-files']).decode("utf-8").split('\n') for f in files[:-1]:...
A helper method to perform the OAuth2 authentication flow. Authenticate and get the oauth token :param str client_id: the client_id :param str client_secret: the client_secret :param list[str] scopes: a list of protocol user scopes to be converted by the protocol or raw scopes :param Protocol ...
def oauth_authentication_flow(client_id, client_secret, scopes=None, protocol=None, **kwargs): """ A helper method to perform the OAuth2 authentication flow. Authenticate and get the oauth token :param str client_id: the client_id :param str client_secret: the client_secre...
Returns a list of scopes needed for each of the scope_helpers provided, by adding the prefix to them if required :param user_provided_scopes: a list of scopes or scope helpers :type user_provided_scopes: list or tuple or str :return: scopes with url prefix added :rtype: list ...
def get_scopes_for(self, user_provided_scopes): """ Returns a list of scopes needed for each of the scope_helpers provided, by adding the prefix to them if required :param user_provided_scopes: a list of scopes or scope helpers :type user_provided_scopes: list or tuple or str :r...
Inserts the protocol scope prefix if required
def _prefix_scope(self, scope): """ Inserts the protocol scope prefix if required""" if self.protocol_scope_prefix: if isinstance(scope, tuple): return scope[0] elif scope.startswith(self.protocol_scope_prefix): return scope else: ...
Sets a proxy on the Session :param str proxy_server: the proxy server :param int proxy_port: the proxy port, defaults to 8080 :param str proxy_username: the proxy username :param str proxy_password: the proxy password
def set_proxy(self, proxy_server, proxy_port, proxy_username, proxy_password): """ Sets a proxy on the Session :param str proxy_server: the proxy server :param int proxy_port: the proxy port, defaults to 8080 :param str proxy_username: the proxy username :param...
Checks if the token file exists at the given position :return: if file exists or not :rtype: bool
def check_token_file(self): """ Checks if the token file exists at the given position :return: if file exists or not :rtype: bool """ # TODO: remove this method in a future release warnings.warn('This method will be removed in future versions', Depr...
Initializes the oauth authorization flow, getting the authorization url that the user must approve. :param list[str] requested_scopes: list of scopes to request access for :param str redirect_uri: redirect url configured in registered app :param kwargs: allow to pass unused params in co...
def get_authorization_url(self, requested_scopes=None, redirect_uri=OAUTH_REDIRECT_URL, **kwargs): """ Initializes the oauth authorization flow, getting the authorization url that the user must approve. :param list[str] requested_scopes: list of scopes to request a...
Authenticates for the specified url and gets the token, save the token for future based if requested :param str authorization_url: url given by the authorization flow :param bool store_token: whether or not to store the token, so u don't have to keep opening the auth link and ...
def request_token(self, authorization_url, store_token=True, token_path=None, **kwargs): """ Authenticates for the specified url and gets the token, save the token for future based if requested :param str authorization_url: url given by the authorization flow :para...
Create a requests Session object :param Path token_path: (Only oauth) full path to where the token should be load from :return: A ready to use requests session :rtype: OAuth2Session
def get_session(self, token_path=None): """ Create a requests Session object :param Path token_path: (Only oauth) full path to where the token should be load from :return: A ready to use requests session :rtype: OAuth2Session """ # TODO: remove token_path in fut...
Refresh the OAuth authorization token. This will be called automatically when the access token expires, however, you can manually call this method to request a new refresh token. :return bool: Success / Failure
def refresh_token(self): """ Refresh the OAuth authorization token. This will be called automatically when the access token expires, however, you can manually call this method to request a new refresh token. :return bool: Success / Failure """ if self.se...
Checks if a delay is needed between requests and sleeps if True
def _check_delay(self): """ Checks if a delay is needed between requests and sleeps if True """ if self._previous_request_at: dif = round(time.time() - self._previous_request_at, 2) * 1000 # difference in miliseconds if dif < self.requests_delay: ...
Internal handling of requests. Handles Exceptions. :param request_obj: a requests session. :param str url: url to send request to :param str method: type of request (get/put/post/patch/delete) :param kwargs: extra params to send to the request api :return: Response of the reques...
def _internal_request(self, request_obj, url, method, **kwargs): """ Internal handling of requests. Handles Exceptions. :param request_obj: a requests session. :param str url: url to send request to :param str method: type of request (get/put/post/patch/delete) :param kwargs: ex...
Makes a request to url using an without oauth authorization session, but through a normal session :param str url: url to send request to :param str method: type of request (get/put/post/patch/delete) :param kwargs: extra params to send to the request api :return: Response of the...
def naive_request(self, url, method, **kwargs): """ Makes a request to url using an without oauth authorization session, but through a normal session :param str url: url to send request to :param str method: type of request (get/put/post/patch/delete) :param kwargs: extra params...