repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
gwastro/pycbc-glue
pycbc_glue/text_progress_bar.py
demo
def demo(): """Demonstrate progress bar.""" from time import sleep maxProgress = 1000 with ProgressBar(max=maxProgress) as progressbar: for i in range(-100, maxProgress): sleep(0.01) progressbar.update(i) progressbar2 = ProgressBar(max=maxProgress) for s in progressbar2.iterate(range(maxProgress)): sleep(0.01) for s in progressbar2.iterate(range(maxProgress), format='iteration %d'): sleep(0.01)
python
def demo(): """Demonstrate progress bar.""" from time import sleep maxProgress = 1000 with ProgressBar(max=maxProgress) as progressbar: for i in range(-100, maxProgress): sleep(0.01) progressbar.update(i) progressbar2 = ProgressBar(max=maxProgress) for s in progressbar2.iterate(range(maxProgress)): sleep(0.01) for s in progressbar2.iterate(range(maxProgress), format='iteration %d'): sleep(0.01)
[ "def", "demo", "(", ")", ":", "from", "time", "import", "sleep", "maxProgress", "=", "1000", "with", "ProgressBar", "(", "max", "=", "maxProgress", ")", "as", "progressbar", ":", "for", "i", "in", "range", "(", "-", "100", ",", "maxProgress", ")", ":",...
Demonstrate progress bar.
[ "Demonstrate", "progress", "bar", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/text_progress_bar.py#L212-L224
gwastro/pycbc-glue
pycbc_glue/text_progress_bar.py
ProgressBar.iterate
def iterate(self, iterable, format="%s"): """Use as a target of a for-loop to issue a progress update for every iteration. For example: progress = ProgressBar() for text in progress.iterate(["foo", "bar", "bat"]): ... """ # If iterable has a definite length, then set the maximum value of the # progress bar. Else, set the maximum value to -1 so that the progress # bar displays indeterminate progress (scrolling dots). try: length = len(iterable) except TypeError: self.max = -1 else: self.max = length # Iterate over the input, updating the progress bar for each element. for i, item in enumerate(iterable): self.update(i, format % item) yield item
python
def iterate(self, iterable, format="%s"): """Use as a target of a for-loop to issue a progress update for every iteration. For example: progress = ProgressBar() for text in progress.iterate(["foo", "bar", "bat"]): ... """ # If iterable has a definite length, then set the maximum value of the # progress bar. Else, set the maximum value to -1 so that the progress # bar displays indeterminate progress (scrolling dots). try: length = len(iterable) except TypeError: self.max = -1 else: self.max = length # Iterate over the input, updating the progress bar for each element. for i, item in enumerate(iterable): self.update(i, format % item) yield item
[ "def", "iterate", "(", "self", ",", "iterable", ",", "format", "=", "\"%s\"", ")", ":", "# If iterable has a definite length, then set the maximum value of the", "# progress bar. Else, set the maximum value to -1 so that the progress", "# bar displays indeterminate progress (scrolling do...
Use as a target of a for-loop to issue a progress update for every iteration. For example: progress = ProgressBar() for text in progress.iterate(["foo", "bar", "bat"]): ...
[ "Use", "as", "a", "target", "of", "a", "for", "-", "loop", "to", "issue", "a", "progress", "update", "for", "every", "iteration", ".", "For", "example", ":" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/text_progress_bar.py#L98-L120
gwastro/pycbc-glue
pycbc_glue/text_progress_bar.py
ProgressBar.show
def show(self): """Redraw the text progress bar.""" if len(self.text) > self.textwidth: label = self.text[0:self.textwidth] else: label = self.text.rjust(self.textwidth) terminalSize = getTerminalSize() if terminalSize is None: terminalSize = 80 else: terminalSize = terminalSize[1] barWidth = terminalSize - self.textwidth - 10 if self.value is None or self.value < 0: pattern = self.twiddle_sequence[ self.twiddle % len(self.twiddle_sequence)] self.twiddle += 1 barSymbols = (pattern * int(math.ceil(barWidth/3.0)))[0:barWidth] progressFractionText = ' . %' else: progressFraction = float(self.value) / self.max nBlocksFrac, nBlocksInt = math.modf( max(0.0, min(1.0, progressFraction)) * barWidth) nBlocksInt = int(nBlocksInt) partialBlock = self.sequence[ int(math.floor(nBlocksFrac * len(self.sequence)))] nBlanks = barWidth - nBlocksInt - 1 barSymbols = (self.sequence[-1] * nBlocksInt) + partialBlock + \ (self.sequence[0] * nBlanks) barSymbols = barSymbols[:barWidth] progressFractionText = ('%.1f%%' % (100*progressFraction)).rjust(6) print >>self.fid, '\r\x1B[1m' + label + '\x1B[0m [' + barSymbols + \ ']' + progressFractionText, self.fid.flush() self.linefed = False
python
def show(self): """Redraw the text progress bar.""" if len(self.text) > self.textwidth: label = self.text[0:self.textwidth] else: label = self.text.rjust(self.textwidth) terminalSize = getTerminalSize() if terminalSize is None: terminalSize = 80 else: terminalSize = terminalSize[1] barWidth = terminalSize - self.textwidth - 10 if self.value is None or self.value < 0: pattern = self.twiddle_sequence[ self.twiddle % len(self.twiddle_sequence)] self.twiddle += 1 barSymbols = (pattern * int(math.ceil(barWidth/3.0)))[0:barWidth] progressFractionText = ' . %' else: progressFraction = float(self.value) / self.max nBlocksFrac, nBlocksInt = math.modf( max(0.0, min(1.0, progressFraction)) * barWidth) nBlocksInt = int(nBlocksInt) partialBlock = self.sequence[ int(math.floor(nBlocksFrac * len(self.sequence)))] nBlanks = barWidth - nBlocksInt - 1 barSymbols = (self.sequence[-1] * nBlocksInt) + partialBlock + \ (self.sequence[0] * nBlanks) barSymbols = barSymbols[:barWidth] progressFractionText = ('%.1f%%' % (100*progressFraction)).rjust(6) print >>self.fid, '\r\x1B[1m' + label + '\x1B[0m [' + barSymbols + \ ']' + progressFractionText, self.fid.flush() self.linefed = False
[ "def", "show", "(", "self", ")", ":", "if", "len", "(", "self", ".", "text", ")", ">", "self", ".", "textwidth", ":", "label", "=", "self", ".", "text", "[", "0", ":", "self", ".", "textwidth", "]", "else", ":", "label", "=", "self", ".", "text...
Redraw the text progress bar.
[ "Redraw", "the", "text", "progress", "bar", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/text_progress_bar.py#L122-L163
gwastro/pycbc-glue
pycbc_glue/text_progress_bar.py
ProgressBar.update
def update(self, value=None, text=None): """Redraw the progress bar, optionally changing the value and text and return the (possibly new) value. For I/O performance, the progress bar might not be written to the terminal if the text does not change and the value changes by too little. Use .show() to force a redraw.""" redraw = False if text is not None: redraw = text != self.text self.text = text if value is not None: redraw |= self.max == 0 or round(value/(0.0003*self.max)) != \ round(self.value/(0.0003*self.max)) self.value = value if redraw: if self.isatty: self.show() else: print >>self.fid, self.text return self.value
python
def update(self, value=None, text=None): """Redraw the progress bar, optionally changing the value and text and return the (possibly new) value. For I/O performance, the progress bar might not be written to the terminal if the text does not change and the value changes by too little. Use .show() to force a redraw.""" redraw = False if text is not None: redraw = text != self.text self.text = text if value is not None: redraw |= self.max == 0 or round(value/(0.0003*self.max)) != \ round(self.value/(0.0003*self.max)) self.value = value if redraw: if self.isatty: self.show() else: print >>self.fid, self.text return self.value
[ "def", "update", "(", "self", ",", "value", "=", "None", ",", "text", "=", "None", ")", ":", "redraw", "=", "False", "if", "text", "is", "not", "None", ":", "redraw", "=", "text", "!=", "self", ".", "text", "self", ".", "text", "=", "text", "if",...
Redraw the progress bar, optionally changing the value and text and return the (possibly new) value. For I/O performance, the progress bar might not be written to the terminal if the text does not change and the value changes by too little. Use .show() to force a redraw.
[ "Redraw", "the", "progress", "bar", "optionally", "changing", "the", "value", "and", "text", "and", "return", "the", "(", "possibly", "new", ")", "value", ".", "For", "I", "/", "O", "performance", "the", "progress", "bar", "might", "not", "be", "written", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/text_progress_bar.py#L165-L184
gwastro/pycbc-glue
pycbc_glue/text_progress_bar.py
ProgressBar.increment
def increment(self, delta=1, text=None): """Redraw the progress bar, incrementing the value by delta (default=1) and optionally changing the text. Returns the ProgressBar's new value. See also .update().""" return self.update(value=min(self.max, self.value + delta), text=text)
python
def increment(self, delta=1, text=None): """Redraw the progress bar, incrementing the value by delta (default=1) and optionally changing the text. Returns the ProgressBar's new value. See also .update().""" return self.update(value=min(self.max, self.value + delta), text=text)
[ "def", "increment", "(", "self", ",", "delta", "=", "1", ",", "text", "=", "None", ")", ":", "return", "self", ".", "update", "(", "value", "=", "min", "(", "self", ".", "max", ",", "self", ".", "value", "+", "delta", ")", ",", "text", "=", "te...
Redraw the progress bar, incrementing the value by delta (default=1) and optionally changing the text. Returns the ProgressBar's new value. See also .update().
[ "Redraw", "the", "progress", "bar", "incrementing", "the", "value", "by", "delta", "(", "default", "=", "1", ")", "and", "optionally", "changing", "the", "text", ".", "Returns", "the", "ProgressBar", "s", "new", "value", ".", "See", "also", ".", "update", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/text_progress_bar.py#L186-L190
mattharrison/rst2odp
odplib/imagescale.py
adjust_fit
def adjust_fit(dst_w, dst_h, img_w, img_h): """ given a x and y of dest, determine the ratio and return an (x,y,w,h) for a fitted image (note x or y could be neg). >>> adjust_fit(4,3,5,5) (0.5, 0, 3.0, 3.0) >>> adjust_fit(8,6,5,5) (1.0, 0, 6.0, 6.0) >>> adjust_fit(4,3,5,2) (0, 0.69999999999999996, 4.0, 1.6000000000000001) >>> adjust_fit(8,6,5,2) (0, 1.3999999999999999, 8.0, 3.2000000000000002) """ dst_w = float(dst_w) dst_h = float(dst_h) img_w = float(img_w) img_h = float(img_h) dst_ratio = float(dst_w) / dst_h img_ratio = float(img_w) / img_h if dst_ratio > img_ratio: # image is narrower, use height y = 0 h = dst_h w = h * img_ratio x = dst_w / 2 - w / 2 else: scale = dst_h / img_h x = 0 w = dst_w h = w / img_ratio y = dst_h / 2 - h / 2 return x, y, w, h
python
def adjust_fit(dst_w, dst_h, img_w, img_h): """ given a x and y of dest, determine the ratio and return an (x,y,w,h) for a fitted image (note x or y could be neg). >>> adjust_fit(4,3,5,5) (0.5, 0, 3.0, 3.0) >>> adjust_fit(8,6,5,5) (1.0, 0, 6.0, 6.0) >>> adjust_fit(4,3,5,2) (0, 0.69999999999999996, 4.0, 1.6000000000000001) >>> adjust_fit(8,6,5,2) (0, 1.3999999999999999, 8.0, 3.2000000000000002) """ dst_w = float(dst_w) dst_h = float(dst_h) img_w = float(img_w) img_h = float(img_h) dst_ratio = float(dst_w) / dst_h img_ratio = float(img_w) / img_h if dst_ratio > img_ratio: # image is narrower, use height y = 0 h = dst_h w = h * img_ratio x = dst_w / 2 - w / 2 else: scale = dst_h / img_h x = 0 w = dst_w h = w / img_ratio y = dst_h / 2 - h / 2 return x, y, w, h
[ "def", "adjust_fit", "(", "dst_w", ",", "dst_h", ",", "img_w", ",", "img_h", ")", ":", "dst_w", "=", "float", "(", "dst_w", ")", "dst_h", "=", "float", "(", "dst_h", ")", "img_w", "=", "float", "(", "img_w", ")", "img_h", "=", "float", "(", "img_h"...
given a x and y of dest, determine the ratio and return an (x,y,w,h) for a fitted image (note x or y could be neg). >>> adjust_fit(4,3,5,5) (0.5, 0, 3.0, 3.0) >>> adjust_fit(8,6,5,5) (1.0, 0, 6.0, 6.0) >>> adjust_fit(4,3,5,2) (0, 0.69999999999999996, 4.0, 1.6000000000000001) >>> adjust_fit(8,6,5,2) (0, 1.3999999999999999, 8.0, 3.2000000000000002)
[ "given", "a", "x", "and", "y", "of", "dest", "determine", "the", "ratio", "and", "return", "an", "(", "x", "y", "w", "h", ")", "for", "a", "fitted", "image", "(", "note", "x", "or", "y", "could", "be", "neg", ")", ".", ">>>", "adjust_fit", "(", ...
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/imagescale.py#L74-L108
mattharrison/rst2odp
odplib/imagescale.py
ImageScale.adjust_size
def adjust_size(self, dst_x, dst_y, mode=FIT): """ given a x and y of dest, determine the ratio and return an (x,y,w,h) for a output image. """ # get image size image = Image.open(self.path) width, height = image.size if mode == FIT: return adjust_crop(dst_x, dst_y, width, height)
python
def adjust_size(self, dst_x, dst_y, mode=FIT): """ given a x and y of dest, determine the ratio and return an (x,y,w,h) for a output image. """ # get image size image = Image.open(self.path) width, height = image.size if mode == FIT: return adjust_crop(dst_x, dst_y, width, height)
[ "def", "adjust_size", "(", "self", ",", "dst_x", ",", "dst_y", ",", "mode", "=", "FIT", ")", ":", "# get image size", "image", "=", "Image", ".", "open", "(", "self", ".", "path", ")", "width", ",", "height", "=", "image", ".", "size", "if", "mode", ...
given a x and y of dest, determine the ratio and return an (x,y,w,h) for a output image.
[ "given", "a", "x", "and", "y", "of", "dest", "determine", "the", "ratio", "and", "return", "an", "(", "x", "y", "w", "h", ")", "for", "a", "output", "image", "." ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/imagescale.py#L14-L23
btaba/sinkhorn_knopp
sinkhorn_knopp/sinkhorn_knopp.py
SinkhornKnopp.fit
def fit(self, P): """Fit the diagonal matrices in Sinkhorn Knopp's algorithm Parameters ---------- P : 2d array-like Must be a square non-negative 2d array-like object, that is convertible to a numpy array. The matrix must not be equal to 0 and it must have total support for the algorithm to converge. Returns ------- A double stochastic matrix. """ P = np.asarray(P) assert np.all(P >= 0) assert P.ndim == 2 assert P.shape[0] == P.shape[1] N = P.shape[0] max_thresh = 1 + self._epsilon min_thresh = 1 - self._epsilon # Initialize r and c, the diagonals of D1 and D2 # and warn if the matrix does not have support. r = np.ones((N, 1)) pdotr = P.T.dot(r) total_support_warning_str = ( "Matrix P must have total support. " "See documentation" ) if not np.all(pdotr != 0): warnings.warn(total_support_warning_str, UserWarning) c = 1 / pdotr pdotc = P.dot(c) if not np.all(pdotc != 0): warnings.warn(total_support_warning_str, UserWarning) r = 1 / pdotc del pdotr, pdotc P_eps = np.copy(P) while np.any(np.sum(P_eps, axis=1) < min_thresh) \ or np.any(np.sum(P_eps, axis=1) > max_thresh) \ or np.any(np.sum(P_eps, axis=0) < min_thresh) \ or np.any(np.sum(P_eps, axis=0) > max_thresh): c = 1 / P.T.dot(r) r = 1 / P.dot(c) self._D1 = np.diag(np.squeeze(r)) self._D2 = np.diag(np.squeeze(c)) P_eps = self._D1.dot(P).dot(self._D2) self._iterations += 1 if self._iterations >= self._max_iter: self._stopping_condition = "max_iter" break if not self._stopping_condition: self._stopping_condition = "epsilon" self._D1 = np.diag(np.squeeze(r)) self._D2 = np.diag(np.squeeze(c)) P_eps = self._D1.dot(P).dot(self._D2) return P_eps
python
def fit(self, P): """Fit the diagonal matrices in Sinkhorn Knopp's algorithm Parameters ---------- P : 2d array-like Must be a square non-negative 2d array-like object, that is convertible to a numpy array. The matrix must not be equal to 0 and it must have total support for the algorithm to converge. Returns ------- A double stochastic matrix. """ P = np.asarray(P) assert np.all(P >= 0) assert P.ndim == 2 assert P.shape[0] == P.shape[1] N = P.shape[0] max_thresh = 1 + self._epsilon min_thresh = 1 - self._epsilon # Initialize r and c, the diagonals of D1 and D2 # and warn if the matrix does not have support. r = np.ones((N, 1)) pdotr = P.T.dot(r) total_support_warning_str = ( "Matrix P must have total support. " "See documentation" ) if not np.all(pdotr != 0): warnings.warn(total_support_warning_str, UserWarning) c = 1 / pdotr pdotc = P.dot(c) if not np.all(pdotc != 0): warnings.warn(total_support_warning_str, UserWarning) r = 1 / pdotc del pdotr, pdotc P_eps = np.copy(P) while np.any(np.sum(P_eps, axis=1) < min_thresh) \ or np.any(np.sum(P_eps, axis=1) > max_thresh) \ or np.any(np.sum(P_eps, axis=0) < min_thresh) \ or np.any(np.sum(P_eps, axis=0) > max_thresh): c = 1 / P.T.dot(r) r = 1 / P.dot(c) self._D1 = np.diag(np.squeeze(r)) self._D2 = np.diag(np.squeeze(c)) P_eps = self._D1.dot(P).dot(self._D2) self._iterations += 1 if self._iterations >= self._max_iter: self._stopping_condition = "max_iter" break if not self._stopping_condition: self._stopping_condition = "epsilon" self._D1 = np.diag(np.squeeze(r)) self._D2 = np.diag(np.squeeze(c)) P_eps = self._D1.dot(P).dot(self._D2) return P_eps
[ "def", "fit", "(", "self", ",", "P", ")", ":", "P", "=", "np", ".", "asarray", "(", "P", ")", "assert", "np", ".", "all", "(", "P", ">=", "0", ")", "assert", "P", ".", "ndim", "==", "2", "assert", "P", ".", "shape", "[", "0", "]", "==", "...
Fit the diagonal matrices in Sinkhorn Knopp's algorithm Parameters ---------- P : 2d array-like Must be a square non-negative 2d array-like object, that is convertible to a numpy array. The matrix must not be equal to 0 and it must have total support for the algorithm to converge. Returns ------- A double stochastic matrix.
[ "Fit", "the", "diagonal", "matrices", "in", "Sinkhorn", "Knopp", "s", "algorithm" ]
train
https://github.com/btaba/sinkhorn_knopp/blob/73e9d74e7f050d0d08e00957ab3f3f2fbc2d25f2/sinkhorn_knopp/sinkhorn_knopp.py#L90-L160
gwastro/pycbc-glue
pycbc_glue/auth/__init__.py
request_ligodotorg
def request_ligodotorg(url, debug=False): """Request the given URL using LIGO.ORG SAML authentication. This requires an active Kerberos ticket for the user, to get one: $ kinit albert.einstein@LIGO.ORG Parameters ---------- url : `str` URL path for request debug : `bool`, optional Query in verbose debuggin mode, default `False` Returns ------- urllib.addinfourl file object containing output data, use .read() to extract text content """ # set debug to 1 to see all HTTP(s) traffic debug = int(debug) # need an instance of HTTPS handler to do HTTPS httpsHandler = urllib2.HTTPSHandler(debuglevel = debug) # use a cookie jar to store session cookies jar = cookielib.LWPCookieJar() # if a cookier jar exists open it and read the cookies # and make sure it has the right permissions if os.path.exists(COOKIE_JAR): os.chmod(COOKIE_JAR, stat.S_IRUSR | stat.S_IWUSR) # set ignore_discard so that session cookies are preserved jar.load(COOKIE_JAR, ignore_discard = True) # create a cookie handler from the cookier jar cookie_handler = urllib2.HTTPCookieProcessor(jar) # need a redirect handler to follow redirects redirectHandler = urllib2.HTTPRedirectHandler() # need an auth handler that can do negotiation. # input parameter is the Kerberos service principal. auth_handler = HTTPNegotiateAuthHandler(service_principal='HTTP@%s' % (LIGO_LOGIN_URL)) # create the opener. opener = urllib2.build_opener(auth_handler, cookie_handler, httpsHandler, redirectHandler) # prepare the request object request = urllib2.Request(url) # use the opener and the request object to make the request. response = opener.open(request) # save the session cookies to a file so that they can # be used again without having to authenticate jar.save(COOKIE_JAR, ignore_discard=True) return response
python
def request_ligodotorg(url, debug=False): """Request the given URL using LIGO.ORG SAML authentication. This requires an active Kerberos ticket for the user, to get one: $ kinit albert.einstein@LIGO.ORG Parameters ---------- url : `str` URL path for request debug : `bool`, optional Query in verbose debuggin mode, default `False` Returns ------- urllib.addinfourl file object containing output data, use .read() to extract text content """ # set debug to 1 to see all HTTP(s) traffic debug = int(debug) # need an instance of HTTPS handler to do HTTPS httpsHandler = urllib2.HTTPSHandler(debuglevel = debug) # use a cookie jar to store session cookies jar = cookielib.LWPCookieJar() # if a cookier jar exists open it and read the cookies # and make sure it has the right permissions if os.path.exists(COOKIE_JAR): os.chmod(COOKIE_JAR, stat.S_IRUSR | stat.S_IWUSR) # set ignore_discard so that session cookies are preserved jar.load(COOKIE_JAR, ignore_discard = True) # create a cookie handler from the cookier jar cookie_handler = urllib2.HTTPCookieProcessor(jar) # need a redirect handler to follow redirects redirectHandler = urllib2.HTTPRedirectHandler() # need an auth handler that can do negotiation. # input parameter is the Kerberos service principal. auth_handler = HTTPNegotiateAuthHandler(service_principal='HTTP@%s' % (LIGO_LOGIN_URL)) # create the opener. opener = urllib2.build_opener(auth_handler, cookie_handler, httpsHandler, redirectHandler) # prepare the request object request = urllib2.Request(url) # use the opener and the request object to make the request. response = opener.open(request) # save the session cookies to a file so that they can # be used again without having to authenticate jar.save(COOKIE_JAR, ignore_discard=True) return response
[ "def", "request_ligodotorg", "(", "url", ",", "debug", "=", "False", ")", ":", "# set debug to 1 to see all HTTP(s) traffic", "debug", "=", "int", "(", "debug", ")", "# need an instance of HTTPS handler to do HTTPS", "httpsHandler", "=", "urllib2", ".", "HTTPSHandler", ...
Request the given URL using LIGO.ORG SAML authentication. This requires an active Kerberos ticket for the user, to get one: $ kinit albert.einstein@LIGO.ORG Parameters ---------- url : `str` URL path for request debug : `bool`, optional Query in verbose debuggin mode, default `False` Returns ------- urllib.addinfourl file object containing output data, use .read() to extract text content
[ "Request", "the", "given", "URL", "using", "LIGO", ".", "ORG", "SAML", "authentication", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/auth/__init__.py#L38-L99
blaklites/fb
fb/request.py
publish_cat1
def publish_cat1(method, con, token, cat, kwargs): """ Constructs a "POST" and "DELETE" URL. The function is used by the publish and delete method First category of "POST" and "DELETE" url construction. Caling it first category because for publishing photos or more complex stuffs, newer fucntions might be added to deal with "POST". """ req_str = "/"+str( kwargs['id'] )+"/"+cat+'?' #/id/category? del kwargs['id'] kwargs['access_token'] = token #add access token to kwwargs res = wiring.send_request(method, con, req_str, kwargs) return res
python
def publish_cat1(method, con, token, cat, kwargs): """ Constructs a "POST" and "DELETE" URL. The function is used by the publish and delete method First category of "POST" and "DELETE" url construction. Caling it first category because for publishing photos or more complex stuffs, newer fucntions might be added to deal with "POST". """ req_str = "/"+str( kwargs['id'] )+"/"+cat+'?' #/id/category? del kwargs['id'] kwargs['access_token'] = token #add access token to kwwargs res = wiring.send_request(method, con, req_str, kwargs) return res
[ "def", "publish_cat1", "(", "method", ",", "con", ",", "token", ",", "cat", ",", "kwargs", ")", ":", "req_str", "=", "\"/\"", "+", "str", "(", "kwargs", "[", "'id'", "]", ")", "+", "\"/\"", "+", "cat", "+", "'?'", "#/id/category?", "del", "kwargs", ...
Constructs a "POST" and "DELETE" URL. The function is used by the publish and delete method First category of "POST" and "DELETE" url construction. Caling it first category because for publishing photos or more complex stuffs, newer fucntions might be added to deal with "POST".
[ "Constructs", "a", "POST", "and", "DELETE", "URL", ".", "The", "function", "is", "used", "by", "the", "publish", "and", "delete", "method", "First", "category", "of", "POST", "and", "DELETE", "url", "construction", ".", "Caling", "it", "first", "category", ...
train
https://github.com/blaklites/fb/blob/4ddba4dae204463ed24f473872215c5a26370a81/fb/request.py#L6-L16
blaklites/fb
fb/request.py
get_object_cat1
def get_object_cat1(con, token, cat, kwargs): """ Constructs the "GET" URL. The functions is used by the get_object method First Category of "GET" URL construction. Again calling it first category because more complex functions maybe added later. """ req_str = "/"+kwargs['id']+"?" #/id? req_str += "access_token="+token #/id?@acces_token=...... del kwargs['id'] key = settings.get_object_cat1_param[cat] #get the param name for the category(single, multiple) req_str += "&"+key+"=" #/id?@acces_token=......key= if key in kwargs.keys(): length = len( kwargs[key] ) for i in range(length): if i == 0: req_str += kwargs[key][i] else: req_str += ","+kwargs[key][i] else: return "Parameter Error" res = wiring.send_request("GET", con, req_str, '') return res
python
def get_object_cat1(con, token, cat, kwargs): """ Constructs the "GET" URL. The functions is used by the get_object method First Category of "GET" URL construction. Again calling it first category because more complex functions maybe added later. """ req_str = "/"+kwargs['id']+"?" #/id? req_str += "access_token="+token #/id?@acces_token=...... del kwargs['id'] key = settings.get_object_cat1_param[cat] #get the param name for the category(single, multiple) req_str += "&"+key+"=" #/id?@acces_token=......key= if key in kwargs.keys(): length = len( kwargs[key] ) for i in range(length): if i == 0: req_str += kwargs[key][i] else: req_str += ","+kwargs[key][i] else: return "Parameter Error" res = wiring.send_request("GET", con, req_str, '') return res
[ "def", "get_object_cat1", "(", "con", ",", "token", ",", "cat", ",", "kwargs", ")", ":", "req_str", "=", "\"/\"", "+", "kwargs", "[", "'id'", "]", "+", "\"?\"", "#/id?", "req_str", "+=", "\"access_token=\"", "+", "token", "#/id?@acces_token=......", "del", ...
Constructs the "GET" URL. The functions is used by the get_object method First Category of "GET" URL construction. Again calling it first category because more complex functions maybe added later.
[ "Constructs", "the", "GET", "URL", ".", "The", "functions", "is", "used", "by", "the", "get_object", "method", "First", "Category", "of", "GET", "URL", "construction", ".", "Again", "calling", "it", "first", "category", "because", "more", "complex", "functions...
train
https://github.com/blaklites/fb/blob/4ddba4dae204463ed24f473872215c5a26370a81/fb/request.py#L20-L43
fractalego/parvusdb
parvusdb/utils/match.py
Match.get_variables_substitution_dictionaries
def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph): """ Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names """ if not rhs_graph: return {}, {}, {} self.matching_code_container.add_graph_to_namespace(lhs_graph) self.matching_code_container.add_graph_to_namespace(rhs_graph) return self.__collect_variables_that_match_graph(lhs_graph, rhs_graph)
python
def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph): """ Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names """ if not rhs_graph: return {}, {}, {} self.matching_code_container.add_graph_to_namespace(lhs_graph) self.matching_code_container.add_graph_to_namespace(rhs_graph) return self.__collect_variables_that_match_graph(lhs_graph, rhs_graph)
[ "def", "get_variables_substitution_dictionaries", "(", "self", ",", "lhs_graph", ",", "rhs_graph", ")", ":", "if", "not", "rhs_graph", ":", "return", "{", "}", ",", "{", "}", ",", "{", "}", "self", ".", "matching_code_container", ".", "add_graph_to_namespace", ...
Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names
[ "Looks", "for", "sub", "-", "isomorphisms", "of", "rhs", "into", "lhs" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/match.py#L11-L23
avara1986/ardy
ardy/core/build/build.py
Build.run
def run(self, src_folder, requirements="requirements.txt", local_package=None): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ self.set_src_path(src_folder) if not os.path.isdir(self.get_src_path()): raise ArdyNoFileError("File {} not exist".format(self.get_src_path())) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = 'dist' path_to_dist = os.path.join(self.get_src_path(), dist_directory) self.mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. output_filename = "{0}.zip".format(self.timestamp()) path_to_temp = mkdtemp(prefix='aws-lambda') self.pip_install_to_target(path_to_temp, requirements=requirements, local_package=local_package) if os.path.isabs(src_folder): src_folder = src_folder.split(os.sep)[-1] self.copytree(self.get_src_path(), os.path.join(path_to_temp, src_folder)) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = self.create_artefact(path_to_temp, path_to_dist, output_filename) return path_to_zip_file
python
def run(self, src_folder, requirements="requirements.txt", local_package=None): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ self.set_src_path(src_folder) if not os.path.isdir(self.get_src_path()): raise ArdyNoFileError("File {} not exist".format(self.get_src_path())) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = 'dist' path_to_dist = os.path.join(self.get_src_path(), dist_directory) self.mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. output_filename = "{0}.zip".format(self.timestamp()) path_to_temp = mkdtemp(prefix='aws-lambda') self.pip_install_to_target(path_to_temp, requirements=requirements, local_package=local_package) if os.path.isabs(src_folder): src_folder = src_folder.split(os.sep)[-1] self.copytree(self.get_src_path(), os.path.join(path_to_temp, src_folder)) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = self.create_artefact(path_to_temp, path_to_dist, output_filename) return path_to_zip_file
[ "def", "run", "(", "self", ",", "src_folder", ",", "requirements", "=", "\"requirements.txt\"", ",", "local_package", "=", "None", ")", ":", "self", ".", "set_src_path", "(", "src_folder", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", "...
Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi)
[ "Builds", "the", "file", "bundle", ".", ":", "param", "str", "src", ":", "The", "path", "to", "your", "Lambda", "ready", "project", "(", "folder", "must", "contain", "a", "valid", "config", ".", "yaml", "and", "handler", "module", "(", "e", ".", "g", ...
train
https://github.com/avara1986/ardy/blob/1942413f12e117b991278cada69f478474b9b94b/ardy/core/build/build.py#L109-L145
avara1986/ardy
ardy/core/build/build.py
Build._install_packages
def _install_packages(self, path, packages): """Install all packages listed to the target directory. Ignores any package that includes Python itself and python-lambda as well since its only needed for deploying and not running the code :param str path: Path to copy installed pip packages to. :param list packages: A list of packages to be installed via pip. """ def _filter_blacklist(package): blacklist = ["-i", "#", "Python==", "ardy=="] return all(package.startswith(entry.encode()) is False for entry in blacklist) filtered_packages = filter(_filter_blacklist, packages) # print([package for package in filtered_packages]) for package in filtered_packages: package = str(package, "utf-8") if package.startswith('-e '): package = package.replace('-e ', '') logger.info('Installing {package}'.format(package=package)) pip.main(['install', package, '-t', path, '--ignore-installed', '-q'])
python
def _install_packages(self, path, packages): """Install all packages listed to the target directory. Ignores any package that includes Python itself and python-lambda as well since its only needed for deploying and not running the code :param str path: Path to copy installed pip packages to. :param list packages: A list of packages to be installed via pip. """ def _filter_blacklist(package): blacklist = ["-i", "#", "Python==", "ardy=="] return all(package.startswith(entry.encode()) is False for entry in blacklist) filtered_packages = filter(_filter_blacklist, packages) # print([package for package in filtered_packages]) for package in filtered_packages: package = str(package, "utf-8") if package.startswith('-e '): package = package.replace('-e ', '') logger.info('Installing {package}'.format(package=package)) pip.main(['install', package, '-t', path, '--ignore-installed', '-q'])
[ "def", "_install_packages", "(", "self", ",", "path", ",", "packages", ")", ":", "def", "_filter_blacklist", "(", "package", ")", ":", "blacklist", "=", "[", "\"-i\"", ",", "\"#\"", ",", "\"Python==\"", ",", "\"ardy==\"", "]", "return", "all", "(", "packag...
Install all packages listed to the target directory. Ignores any package that includes Python itself and python-lambda as well since its only needed for deploying and not running the code :param str path: Path to copy installed pip packages to. :param list packages: A list of packages to be installed via pip.
[ "Install", "all", "packages", "listed", "to", "the", "target", "directory", ".", "Ignores", "any", "package", "that", "includes", "Python", "itself", "and", "python", "-", "lambda", "as", "well", "since", "its", "only", "needed", "for", "deploying", "and", "...
train
https://github.com/avara1986/ardy/blob/1942413f12e117b991278cada69f478474b9b94b/ardy/core/build/build.py#L147-L169
avara1986/ardy
ardy/core/build/build.py
Build.pip_install_to_target
def pip_install_to_target(self, path, requirements="", local_package=None): """For a given active virtualenv, gather all installed pip packages then copy (re-install) them to the path provided. :param str path: Path to copy installed pip packages to. :param str requirements: If set, only the packages in the requirements.txt file are installed. The requirements.txt file needs to be in the same directory as the project which shall be deployed. Defaults to false and installs all pacakges found via pip freeze if not set. :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ packages = [] if not requirements: logger.debug('Gathering pip packages') # packages.extend(pip.operations.freeze.freeze()) pass else: requirements_path = os.path.join(self.get_src_path(), requirements) logger.debug('Gathering packages from requirements: {}'.format(requirements_path)) if os.path.isfile(requirements_path): data = self.read(requirements_path) packages.extend(data.splitlines()) else: logger.debug('No requirements file in {}'.format(requirements_path)) if local_package is not None: if not isinstance(local_package, (list, tuple)): local_package = [local_package] for l_package in local_package: packages.append(l_package) self._install_packages(path, packages)
python
def pip_install_to_target(self, path, requirements="", local_package=None): """For a given active virtualenv, gather all installed pip packages then copy (re-install) them to the path provided. :param str path: Path to copy installed pip packages to. :param str requirements: If set, only the packages in the requirements.txt file are installed. The requirements.txt file needs to be in the same directory as the project which shall be deployed. Defaults to false and installs all pacakges found via pip freeze if not set. :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ packages = [] if not requirements: logger.debug('Gathering pip packages') # packages.extend(pip.operations.freeze.freeze()) pass else: requirements_path = os.path.join(self.get_src_path(), requirements) logger.debug('Gathering packages from requirements: {}'.format(requirements_path)) if os.path.isfile(requirements_path): data = self.read(requirements_path) packages.extend(data.splitlines()) else: logger.debug('No requirements file in {}'.format(requirements_path)) if local_package is not None: if not isinstance(local_package, (list, tuple)): local_package = [local_package] for l_package in local_package: packages.append(l_package) self._install_packages(path, packages)
[ "def", "pip_install_to_target", "(", "self", ",", "path", ",", "requirements", "=", "\"\"", ",", "local_package", "=", "None", ")", ":", "packages", "=", "[", "]", "if", "not", "requirements", ":", "logger", ".", "debug", "(", "'Gathering pip packages'", ")"...
For a given active virtualenv, gather all installed pip packages then copy (re-install) them to the path provided. :param str path: Path to copy installed pip packages to. :param str requirements: If set, only the packages in the requirements.txt file are installed. The requirements.txt file needs to be in the same directory as the project which shall be deployed. Defaults to false and installs all pacakges found via pip freeze if not set. :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi)
[ "For", "a", "given", "active", "virtualenv", "gather", "all", "installed", "pip", "packages", "then", "copy", "(", "re", "-", "install", ")", "them", "to", "the", "path", "provided", ".", ":", "param", "str", "path", ":", "Path", "to", "copy", "installed...
train
https://github.com/avara1986/ardy/blob/1942413f12e117b991278cada69f478474b9b94b/ardy/core/build/build.py#L171-L205
eseraygun/python-table
table.py
readTableFromDelimited
def readTableFromDelimited(f, separator="\t"): """ Reads a table object from given plain delimited file. """ rowNames = [] columnNames = [] matrix = [] first = True for line in f.readlines(): line = line.rstrip() if len(line) == 0: continue row = line.split(separator) if first: columnNames = row[1:] first = False else: rowNames.append(row[0]) matrix.append([float(c) for c in row[1:]]) return Table(rowNames, columnNames, matrix)
python
def readTableFromDelimited(f, separator="\t"): """ Reads a table object from given plain delimited file. """ rowNames = [] columnNames = [] matrix = [] first = True for line in f.readlines(): line = line.rstrip() if len(line) == 0: continue row = line.split(separator) if first: columnNames = row[1:] first = False else: rowNames.append(row[0]) matrix.append([float(c) for c in row[1:]]) return Table(rowNames, columnNames, matrix)
[ "def", "readTableFromDelimited", "(", "f", ",", "separator", "=", "\"\\t\"", ")", ":", "rowNames", "=", "[", "]", "columnNames", "=", "[", "]", "matrix", "=", "[", "]", "first", "=", "True", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", ...
Reads a table object from given plain delimited file.
[ "Reads", "a", "table", "object", "from", "given", "plain", "delimited", "file", "." ]
train
https://github.com/eseraygun/python-table/blob/4b2d5799a9f3af93b8327758c06f5c6890bc5a1a/table.py#L133-L155
eseraygun/python-table
table.py
readTableFromCSV
def readTableFromCSV(f, dialect="excel"): """ Reads a table object from given CSV file. """ rowNames = [] columnNames = [] matrix = [] first = True for row in csv.reader(f, dialect): if first: columnNames = row[1:] first = False else: rowNames.append(row[0]) matrix.append([float(c) for c in row[1:]]) return Table(rowNames, columnNames, matrix)
python
def readTableFromCSV(f, dialect="excel"): """ Reads a table object from given CSV file. """ rowNames = [] columnNames = [] matrix = [] first = True for row in csv.reader(f, dialect): if first: columnNames = row[1:] first = False else: rowNames.append(row[0]) matrix.append([float(c) for c in row[1:]]) return Table(rowNames, columnNames, matrix)
[ "def", "readTableFromCSV", "(", "f", ",", "dialect", "=", "\"excel\"", ")", ":", "rowNames", "=", "[", "]", "columnNames", "=", "[", "]", "matrix", "=", "[", "]", "first", "=", "True", "for", "row", "in", "csv", ".", "reader", "(", "f", ",", "diale...
Reads a table object from given CSV file.
[ "Reads", "a", "table", "object", "from", "given", "CSV", "file", "." ]
train
https://github.com/eseraygun/python-table/blob/4b2d5799a9f3af93b8327758c06f5c6890bc5a1a/table.py#L157-L174
eseraygun/python-table
table.py
Table.cell
def cell(self, rowName, columnName): """ Returns the value of the cell on the given row and column. """ return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]]
python
def cell(self, rowName, columnName): """ Returns the value of the cell on the given row and column. """ return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]]
[ "def", "cell", "(", "self", ",", "rowName", ",", "columnName", ")", ":", "return", "self", ".", "matrix", "[", "self", ".", "rowIndices", "[", "rowName", "]", ",", "self", ".", "columnIndices", "[", "columnName", "]", "]" ]
Returns the value of the cell on the given row and column.
[ "Returns", "the", "value", "of", "the", "cell", "on", "the", "given", "row", "and", "column", "." ]
train
https://github.com/eseraygun/python-table/blob/4b2d5799a9f3af93b8327758c06f5c6890bc5a1a/table.py#L47-L51
eseraygun/python-table
table.py
Table.rows
def rows(self): """ Returns a list of dicts. """ rows = [] for rowName in self.rowNames: row = {columnName: self[rowName, columnName] for columnName in self.columnNames} row["_"] = rowName rows.append(row) return rows
python
def rows(self): """ Returns a list of dicts. """ rows = [] for rowName in self.rowNames: row = {columnName: self[rowName, columnName] for columnName in self.columnNames} row["_"] = rowName rows.append(row) return rows
[ "def", "rows", "(", "self", ")", ":", "rows", "=", "[", "]", "for", "rowName", "in", "self", ".", "rowNames", ":", "row", "=", "{", "columnName", ":", "self", "[", "rowName", ",", "columnName", "]", "for", "columnName", "in", "self", ".", "columnName...
Returns a list of dicts.
[ "Returns", "a", "list", "of", "dicts", "." ]
train
https://github.com/eseraygun/python-table/blob/4b2d5799a9f3af93b8327758c06f5c6890bc5a1a/table.py#L65-L74
honmaple/flask-maple
example/manager.py
init_db
def init_db(): """ Drops and re-creates the SQL schema """ db.drop_all() db.configure_mappers() db.create_all() db.session.commit()
python
def init_db(): """ Drops and re-creates the SQL schema """ db.drop_all() db.configure_mappers() db.create_all() db.session.commit()
[ "def", "init_db", "(", ")", ":", "db", ".", "drop_all", "(", ")", "db", ".", "configure_mappers", "(", ")", "db", ".", "create_all", "(", ")", "db", ".", "session", ".", "commit", "(", ")" ]
Drops and re-creates the SQL schema
[ "Drops", "and", "re", "-", "creates", "the", "SQL", "schema" ]
train
https://github.com/honmaple/flask-maple/blob/8124de55e5e531a5cb43477944168f98608dc08f/example/manager.py#L24-L31
honmaple/flask-maple
example/manager.py
gunicorn
def gunicorn(host, port, workers): """use gunicorn""" from gunicorn.app.base import Application class FlaskApplication(Application): def init(self, parser, opts, args): return {'bind': '{0}:{1}'.format(host, port), 'workers': workers} def load(self): return app application = FlaskApplication() return application.run()
python
def gunicorn(host, port, workers): """use gunicorn""" from gunicorn.app.base import Application class FlaskApplication(Application): def init(self, parser, opts, args): return {'bind': '{0}:{1}'.format(host, port), 'workers': workers} def load(self): return app application = FlaskApplication() return application.run()
[ "def", "gunicorn", "(", "host", ",", "port", ",", "workers", ")", ":", "from", "gunicorn", ".", "app", ".", "base", "import", "Application", "class", "FlaskApplication", "(", "Application", ")", ":", "def", "init", "(", "self", ",", "parser", ",", "opts"...
use gunicorn
[ "use", "gunicorn" ]
train
https://github.com/honmaple/flask-maple/blob/8124de55e5e531a5cb43477944168f98608dc08f/example/manager.py#L61-L73
mattharrison/rst2odp
odplib/zipwrap.py
ZipWrap.load_zipfile
def load_zipfile(self, path): """ import contents of a zipfile """ # try to add as zipfile zin = zipfile.ZipFile(path) for zinfo in zin.infolist(): name = zinfo.filename if name.endswith("/"): self.mkdir(name) else: content = zin.read(name) self.touch(name, content)
python
def load_zipfile(self, path): """ import contents of a zipfile """ # try to add as zipfile zin = zipfile.ZipFile(path) for zinfo in zin.infolist(): name = zinfo.filename if name.endswith("/"): self.mkdir(name) else: content = zin.read(name) self.touch(name, content)
[ "def", "load_zipfile", "(", "self", ",", "path", ")", ":", "# try to add as zipfile", "zin", "=", "zipfile", ".", "ZipFile", "(", "path", ")", "for", "zinfo", "in", "zin", ".", "infolist", "(", ")", ":", "name", "=", "zinfo", ".", "filename", "if", "na...
import contents of a zipfile
[ "import", "contents", "of", "a", "zipfile" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/zipwrap.py#L128-L140
mattharrison/rst2odp
odplib/zipwrap.py
ZipWrap.load_dir
def load_dir(self, path): """ import contents of a directory """ def visit_path(arg, dirname, names): for name in names: fpath = os.path.join(dirname, name) new_path = fpath[len(path):] if os.path.isfile(fpath): content = open(fpath, "rb").read() self.touch(new_path, content) else: self.mkdir(new_path) os.path.walk(path, visit_path, None)
python
def load_dir(self, path): """ import contents of a directory """ def visit_path(arg, dirname, names): for name in names: fpath = os.path.join(dirname, name) new_path = fpath[len(path):] if os.path.isfile(fpath): content = open(fpath, "rb").read() self.touch(new_path, content) else: self.mkdir(new_path) os.path.walk(path, visit_path, None)
[ "def", "load_dir", "(", "self", ",", "path", ")", ":", "def", "visit_path", "(", "arg", ",", "dirname", ",", "names", ")", ":", "for", "name", "in", "names", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "name", ")", "ne...
import contents of a directory
[ "import", "contents", "of", "a", "directory" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/zipwrap.py#L142-L157
mattharrison/rst2odp
odplib/zipwrap.py
ZipWrap._rel_path
def _rel_path(self, path, basepath=None): """ trim off basepath """ basepath = basepath or self.src_dir return path[len(basepath) + 1:]
python
def _rel_path(self, path, basepath=None): """ trim off basepath """ basepath = basepath or self.src_dir return path[len(basepath) + 1:]
[ "def", "_rel_path", "(", "self", ",", "path", ",", "basepath", "=", "None", ")", ":", "basepath", "=", "basepath", "or", "self", ".", "src_dir", "return", "path", "[", "len", "(", "basepath", ")", "+", "1", ":", "]" ]
trim off basepath
[ "trim", "off", "basepath" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/zipwrap.py#L216-L221
mattharrison/rst2odp
odplib/zipwrap.py
ZipWrap.unzip
def unzip(self, directory): """ Write contents of zipfile to directory """ if not os.path.exists(directory): os.makedirs(directory) shutil.copytree(self.src_dir, directory)
python
def unzip(self, directory): """ Write contents of zipfile to directory """ if not os.path.exists(directory): os.makedirs(directory) shutil.copytree(self.src_dir, directory)
[ "def", "unzip", "(", "self", ",", "directory", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "shutil", ".", "copytree", "(", "self", ".", "src_dir", ",", "directory"...
Write contents of zipfile to directory
[ "Write", "contents", "of", "zipfile", "to", "directory" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/zipwrap.py#L223-L229
fractalego/parvusdb
parvusdb/utils/graph_database.py
GraphDatabase.query
def query(self, string, repeat_n_times=None): """ This method performs the operations onto self.g :param string: The list of operations to perform. The sequences of commands should be separated by a semicolon An example might be CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2), {'tag': 'PLACE', 'text': 'London'}(v2) MATCH {}(_a), {'relation': 'LIVES_AT'}(_a,_b), {}(_b) WHERE (= (get _a "text") "joseph") RETURN _a,_b; :param repeat_n_times: The maximum number of times the graph is queried. It sets the maximum length of the return list. If None then the value is set by the function self.__determine_how_many_times_to_repeat_query(string) :return: If the RETURN command is called with a list of variables names, a list of JSON with the corresponding properties is returned. If the RETURN command is used alone, a list with the entire graph is returned. Otherwise it returns an empty list """ if not repeat_n_times: repeat_n_times = self.__determine_how_many_times_to_repeat_query(string) lines = self.__get_command_lines(string) return_list = [] for line in lines: lst = self.__query_n_times(line, repeat_n_times) if lst and lst[0]: return_list = lst return return_list
python
def query(self, string, repeat_n_times=None): """ This method performs the operations onto self.g :param string: The list of operations to perform. The sequences of commands should be separated by a semicolon An example might be CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2), {'tag': 'PLACE', 'text': 'London'}(v2) MATCH {}(_a), {'relation': 'LIVES_AT'}(_a,_b), {}(_b) WHERE (= (get _a "text") "joseph") RETURN _a,_b; :param repeat_n_times: The maximum number of times the graph is queried. It sets the maximum length of the return list. If None then the value is set by the function self.__determine_how_many_times_to_repeat_query(string) :return: If the RETURN command is called with a list of variables names, a list of JSON with the corresponding properties is returned. If the RETURN command is used alone, a list with the entire graph is returned. Otherwise it returns an empty list """ if not repeat_n_times: repeat_n_times = self.__determine_how_many_times_to_repeat_query(string) lines = self.__get_command_lines(string) return_list = [] for line in lines: lst = self.__query_n_times(line, repeat_n_times) if lst and lst[0]: return_list = lst return return_list
[ "def", "query", "(", "self", ",", "string", ",", "repeat_n_times", "=", "None", ")", ":", "if", "not", "repeat_n_times", ":", "repeat_n_times", "=", "self", ".", "__determine_how_many_times_to_repeat_query", "(", "string", ")", "lines", "=", "self", ".", "__ge...
This method performs the operations onto self.g :param string: The list of operations to perform. The sequences of commands should be separated by a semicolon An example might be CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2), {'tag': 'PLACE', 'text': 'London'}(v2) MATCH {}(_a), {'relation': 'LIVES_AT'}(_a,_b), {}(_b) WHERE (= (get _a "text") "joseph") RETURN _a,_b; :param repeat_n_times: The maximum number of times the graph is queried. It sets the maximum length of the return list. If None then the value is set by the function self.__determine_how_many_times_to_repeat_query(string) :return: If the RETURN command is called with a list of variables names, a list of JSON with the corresponding properties is returned. If the RETURN command is used alone, a list with the entire graph is returned. Otherwise it returns an empty list
[ "This", "method", "performs", "the", "operations", "onto", "self", ".", "g" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/graph_database.py#L35-L62
fractalego/parvusdb
parvusdb/utils/graph_database.py
GraphDatabase.__query_with_builder
def __query_with_builder(self, string, builder): """ Uses the builder in the argument to modify the graph, according to the commands in the string :param string: The single query to the database :return: The result of the RETURN operation """ action_graph_pairs = self.__get_action_graph_pairs_from_query(string) for action, graph_str in action_graph_pairs: if action == 'RETURN' or action == '': return self.__return(graph_str, builder) try: self.action_dict[action](graph_str, builder) except MatchException: break return {}
python
def __query_with_builder(self, string, builder): """ Uses the builder in the argument to modify the graph, according to the commands in the string :param string: The single query to the database :return: The result of the RETURN operation """ action_graph_pairs = self.__get_action_graph_pairs_from_query(string) for action, graph_str in action_graph_pairs: if action == 'RETURN' or action == '': return self.__return(graph_str, builder) try: self.action_dict[action](graph_str, builder) except MatchException: break return {}
[ "def", "__query_with_builder", "(", "self", ",", "string", ",", "builder", ")", ":", "action_graph_pairs", "=", "self", ".", "__get_action_graph_pairs_from_query", "(", "string", ")", "for", "action", ",", "graph_str", "in", "action_graph_pairs", ":", "if", "actio...
Uses the builder in the argument to modify the graph, according to the commands in the string :param string: The single query to the database :return: The result of the RETURN operation
[ "Uses", "the", "builder", "in", "the", "argument", "to", "modify", "the", "graph", "according", "to", "the", "commands", "in", "the", "string" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/graph_database.py#L88-L103
fractalego/parvusdb
parvusdb/utils/graph_database.py
GraphDatabase.__get_action_graph_pairs_from_query
def __get_action_graph_pairs_from_query(self, query): """ Splits the query into command/argument pairs, for example [("MATCH","{}(_a))", ("RETURN","_a")] :param query: The string with the list of commands :return: the command/argument pairs """ import re query = convert_special_characters_to_spaces(query) graph_list = re.split('|'.join(self.action_list), query) query_list_positions = [query.find(graph) for graph in graph_list] query_list_positions = query_list_positions query_list_positions = query_list_positions action_list = [query[query_list_positions[i] + len(graph_list[i]):query_list_positions[i + 1]].strip() for i in range(len(graph_list) - 1)] graph_list = graph_list[1:] return zip(action_list, graph_list)
python
def __get_action_graph_pairs_from_query(self, query): """ Splits the query into command/argument pairs, for example [("MATCH","{}(_a))", ("RETURN","_a")] :param query: The string with the list of commands :return: the command/argument pairs """ import re query = convert_special_characters_to_spaces(query) graph_list = re.split('|'.join(self.action_list), query) query_list_positions = [query.find(graph) for graph in graph_list] query_list_positions = query_list_positions query_list_positions = query_list_positions action_list = [query[query_list_positions[i] + len(graph_list[i]):query_list_positions[i + 1]].strip() for i in range(len(graph_list) - 1)] graph_list = graph_list[1:] return zip(action_list, graph_list)
[ "def", "__get_action_graph_pairs_from_query", "(", "self", ",", "query", ")", ":", "import", "re", "query", "=", "convert_special_characters_to_spaces", "(", "query", ")", "graph_list", "=", "re", ".", "split", "(", "'|'", ".", "join", "(", "self", ".", "actio...
Splits the query into command/argument pairs, for example [("MATCH","{}(_a))", ("RETURN","_a")] :param query: The string with the list of commands :return: the command/argument pairs
[ "Splits", "the", "query", "into", "command", "/", "argument", "pairs", "for", "example", "[", "(", "MATCH", "{}", "(", "_a", "))", "(", "RETURN", "_a", ")", "]" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/graph_database.py#L105-L122
ebu/PlugIt
plugit_proxy/utils.py
create_secret
def create_secret(*args, **kwargs): """Return a secure key generated from the user and the object. As we load elements fron any class from user imput, this prevent the user to specify arbitrary class""" to_sign = '-!'.join(args) + '$$'.join(kwargs.values()) key = settings.SECRET_FOR_SIGNS hashed = hmac.new(key, to_sign, sha1) return re.sub(r'[\W_]+', '', binascii.b2a_base64(hashed.digest()))
python
def create_secret(*args, **kwargs): """Return a secure key generated from the user and the object. As we load elements fron any class from user imput, this prevent the user to specify arbitrary class""" to_sign = '-!'.join(args) + '$$'.join(kwargs.values()) key = settings.SECRET_FOR_SIGNS hashed = hmac.new(key, to_sign, sha1) return re.sub(r'[\W_]+', '', binascii.b2a_base64(hashed.digest()))
[ "def", "create_secret", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "to_sign", "=", "'-!'", ".", "join", "(", "args", ")", "+", "'$$'", ".", "join", "(", "kwargs", ".", "values", "(", ")", ")", "key", "=", "settings", ".", "SECRET_FOR_SIGN...
Return a secure key generated from the user and the object. As we load elements fron any class from user imput, this prevent the user to specify arbitrary class
[ "Return", "a", "secure", "key", "generated", "from", "the", "user", "and", "the", "object", ".", "As", "we", "load", "elements", "fron", "any", "class", "from", "user", "imput", "this", "prevent", "the", "user", "to", "specify", "arbitrary", "class" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/utils.py#L10-L18
RadhikaG/markdown-magic
magic/imageGen.py
processString
def processString(inptStr): ''' inptStr may be a string of the following forms: * 'meme: text0 | text1' * 'gif: search_keywords' If not, it returns an appropriate error message, stating an improperly formatted <magic> tag. Fails gracefully when it can't find or generate a meme or a gif, by returning an appropriate image url with the failure message on it. TODO: Find a way to efficiently search for xkcd comics ''' inptStr.strip(' ') imgParamList = inptStr.split(':') if len(imgParamList) < 2: print("Not enough information for searching for image.") return not_enough_info else: imgType = imgParamList[0] imgParams = imgParamList[1] if imgType == 'meme': imgURL = processMeme(imgParams) # print(imgURL) return imgURL elif imgType == 'gif': gifURL = processGif(imgParams) # print(gifURL) return gifURL else: print("Improperly formatted <magic> tag.") return improperly_formatted_tag
python
def processString(inptStr): ''' inptStr may be a string of the following forms: * 'meme: text0 | text1' * 'gif: search_keywords' If not, it returns an appropriate error message, stating an improperly formatted <magic> tag. Fails gracefully when it can't find or generate a meme or a gif, by returning an appropriate image url with the failure message on it. TODO: Find a way to efficiently search for xkcd comics ''' inptStr.strip(' ') imgParamList = inptStr.split(':') if len(imgParamList) < 2: print("Not enough information for searching for image.") return not_enough_info else: imgType = imgParamList[0] imgParams = imgParamList[1] if imgType == 'meme': imgURL = processMeme(imgParams) # print(imgURL) return imgURL elif imgType == 'gif': gifURL = processGif(imgParams) # print(gifURL) return gifURL else: print("Improperly formatted <magic> tag.") return improperly_formatted_tag
[ "def", "processString", "(", "inptStr", ")", ":", "inptStr", ".", "strip", "(", "' '", ")", "imgParamList", "=", "inptStr", ".", "split", "(", "':'", ")", "if", "len", "(", "imgParamList", ")", "<", "2", ":", "print", "(", "\"Not enough information for sea...
inptStr may be a string of the following forms: * 'meme: text0 | text1' * 'gif: search_keywords' If not, it returns an appropriate error message, stating an improperly formatted <magic> tag. Fails gracefully when it can't find or generate a meme or a gif, by returning an appropriate image url with the failure message on it. TODO: Find a way to efficiently search for xkcd comics
[ "inptStr", "may", "be", "a", "string", "of", "the", "following", "forms", ":", "*", "meme", ":", "text0", "|", "text1", "*", "gif", ":", "search_keywords" ]
train
https://github.com/RadhikaG/markdown-magic/blob/af99549b033269d861ea13f0541cb4f894057c47/magic/imageGen.py#L5-L45
h4ck3rk3y/wolfe
wolfe/wolfe.py
main
def main(): '''i am winston wolfe, i solve problems''' arguments = docopt(__doc__, version=__version__) if arguments['on']: print 'Mr. Wolfe is at your service' print 'If any of your programs run into an error' print 'use wolfe $l' print 'To undo the changes made by mr wolfe in your bashrc, do wolfe off' on() elif arguments['off']: off() print 'Mr. Wolfe says goodbye!' elif arguments['QUERY']: last(arguments['QUERY'], arguments['-g'] or arguments['--google']) else: print __doc__
python
def main(): '''i am winston wolfe, i solve problems''' arguments = docopt(__doc__, version=__version__) if arguments['on']: print 'Mr. Wolfe is at your service' print 'If any of your programs run into an error' print 'use wolfe $l' print 'To undo the changes made by mr wolfe in your bashrc, do wolfe off' on() elif arguments['off']: off() print 'Mr. Wolfe says goodbye!' elif arguments['QUERY']: last(arguments['QUERY'], arguments['-g'] or arguments['--google']) else: print __doc__
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", "(", "__doc__", ",", "version", "=", "__version__", ")", "if", "arguments", "[", "'on'", "]", ":", "print", "'Mr. Wolfe is at your service'", "print", "'If any of your programs run into an error'", "print", ...
i am winston wolfe, i solve problems
[ "i", "am", "winston", "wolfe", "i", "solve", "problems" ]
train
https://github.com/h4ck3rk3y/wolfe/blob/81e0e446be924353dad1ee4a2036509979712166/wolfe/wolfe.py#L81-L96
pesaply/sarafu
pesaply.py
pesaplyMM.get_account_details
def get_account_details(self, account): """ This method can be used in a number of scenarios: 1. When it is necessary to very account information 2. When there's a need to filter transactions by an account id 3. When account details (e.g. name of account) are needed """ _form = mechanize.HTMLForm(self.SEARCH_MEMBERS_URL, method="POST") _form.new_control('text', 'username', {'value': account}) _form.new_control('text', '_', {'value': ''}) try: r = self.post_url(self.SEARCH_MEMBERS_URL, form=_form) except AuthRequiredException: self._auth() r = self.post_url(self.SEARCH_MEMBERS_URL, form=_form) if r: # single quoted json parameters are not valid so convert # them into double quoted parameters _decoded = json.loads(r.replace("'", '"')) # we have a double array result so retrieve only what's # essential if _decoded[0]: return _decoded[0][0] raise InvalidAccountException
python
def get_account_details(self, account): """ This method can be used in a number of scenarios: 1. When it is necessary to very account information 2. When there's a need to filter transactions by an account id 3. When account details (e.g. name of account) are needed """ _form = mechanize.HTMLForm(self.SEARCH_MEMBERS_URL, method="POST") _form.new_control('text', 'username', {'value': account}) _form.new_control('text', '_', {'value': ''}) try: r = self.post_url(self.SEARCH_MEMBERS_URL, form=_form) except AuthRequiredException: self._auth() r = self.post_url(self.SEARCH_MEMBERS_URL, form=_form) if r: # single quoted json parameters are not valid so convert # them into double quoted parameters _decoded = json.loads(r.replace("'", '"')) # we have a double array result so retrieve only what's # essential if _decoded[0]: return _decoded[0][0] raise InvalidAccountException
[ "def", "get_account_details", "(", "self", ",", "account", ")", ":", "_form", "=", "mechanize", ".", "HTMLForm", "(", "self", ".", "SEARCH_MEMBERS_URL", ",", "method", "=", "\"POST\"", ")", "_form", ".", "new_control", "(", "'text'", ",", "'username'", ",", ...
This method can be used in a number of scenarios: 1. When it is necessary to very account information 2. When there's a need to filter transactions by an account id 3. When account details (e.g. name of account) are needed
[ "This", "method", "can", "be", "used", "in", "a", "number", "of", "scenarios", ":", "1", ".", "When", "it", "is", "necessary", "to", "very", "account", "information", "2", ".", "When", "there", "s", "a", "need", "to", "filter", "transactions", "by", "a...
train
https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/pesaply.py#L52-L78
pesaply/sarafu
pesaply.py
pesaplyMM.get_transactions
def get_transactions(self, **kwargs): """ This method optionally takes the following extra keyword arguments: to_date: a datetime object representing the date the filter should end with from_date: a datetime object representing the date the filter should start from txn_ref: the transaction reference of a particular transaction from_account_id: the account id for the account to filter transactions by (you will need to get this information from `get_account_details` method) If you specify txn_ref, then it's not necessary to specify to_date and from_date. """ kw_map = { 'to_date': 'query(period).end', 'from_account_id': 'query(member)', 'from_date': 'query(period).begin', 'txn_ref': 'query(transactionNumber)'} if not self.TRANSACTIONS_FORM: try: self.get_url(self.TRANSACTIONS_URL) except AuthRequiredException: self._auth() self.get_url(self.TRANSACTIONS_URL) self.br.select_form("accountHistoryForm") self.br.form.method = 'POST' self.br.form.action = self.TRANSACTIONS_EXPORT_URL self.TRANSACTIONS_FORM = self.br.form _form = deepcopy(self.TRANSACTIONS_FORM) else: _form = deepcopy(self.TRANSACTIONS_FORM) # make all hidden and readonly fields writable _form.set_all_readonly(False) for key, field_name in kw_map.items(): if key in kwargs: # if the field is a date, format accordingly if key.endswith('_date'): _form[field_name] = kwargs.get(key).strftime('%d/%m/%Y') else: _form[field_name] = kwargs.get(key) try: r = self.post_url(self.TRANSACTIONS_EXPORT_URL, form=_form) return self._parse_transactions(r) except AuthRequiredException: self._auth() r = self.post_url(self.TRANSACTIONS_EXPORT_URL, form=_form) return self._parse_transactions(r)
python
def get_transactions(self, **kwargs): """ This method optionally takes the following extra keyword arguments: to_date: a datetime object representing the date the filter should end with from_date: a datetime object representing the date the filter should start from txn_ref: the transaction reference of a particular transaction from_account_id: the account id for the account to filter transactions by (you will need to get this information from `get_account_details` method) If you specify txn_ref, then it's not necessary to specify to_date and from_date. """ kw_map = { 'to_date': 'query(period).end', 'from_account_id': 'query(member)', 'from_date': 'query(period).begin', 'txn_ref': 'query(transactionNumber)'} if not self.TRANSACTIONS_FORM: try: self.get_url(self.TRANSACTIONS_URL) except AuthRequiredException: self._auth() self.get_url(self.TRANSACTIONS_URL) self.br.select_form("accountHistoryForm") self.br.form.method = 'POST' self.br.form.action = self.TRANSACTIONS_EXPORT_URL self.TRANSACTIONS_FORM = self.br.form _form = deepcopy(self.TRANSACTIONS_FORM) else: _form = deepcopy(self.TRANSACTIONS_FORM) # make all hidden and readonly fields writable _form.set_all_readonly(False) for key, field_name in kw_map.items(): if key in kwargs: # if the field is a date, format accordingly if key.endswith('_date'): _form[field_name] = kwargs.get(key).strftime('%d/%m/%Y') else: _form[field_name] = kwargs.get(key) try: r = self.post_url(self.TRANSACTIONS_EXPORT_URL, form=_form) return self._parse_transactions(r) except AuthRequiredException: self._auth() r = self.post_url(self.TRANSACTIONS_EXPORT_URL, form=_form) return self._parse_transactions(r)
[ "def", "get_transactions", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kw_map", "=", "{", "'to_date'", ":", "'query(period).end'", ",", "'from_account_id'", ":", "'query(member)'", ",", "'from_date'", ":", "'query(period).begin'", ",", "'txn_ref'", ":", "'q...
This method optionally takes the following extra keyword arguments: to_date: a datetime object representing the date the filter should end with from_date: a datetime object representing the date the filter should start from txn_ref: the transaction reference of a particular transaction from_account_id: the account id for the account to filter transactions by (you will need to get this information from `get_account_details` method) If you specify txn_ref, then it's not necessary to specify to_date and from_date.
[ "This", "method", "optionally", "takes", "the", "following", "extra", "keyword", "arguments", ":", "to_date", ":", "a", "datetime", "object", "representing", "the", "date", "the", "filter", "should", "end", "with", "from_date", ":", "a", "datetime", "object", ...
train
https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/pesaply.py#L80-L128
pesaply/sarafu
pesaply.py
pesaplyMM.make_payment
def make_payment(self, recipient, amount, description=None): """ make_payment allows for automated payments. A use case includes the ability to trigger a payment to a customer who requires a refund for example. You only need to provide the recipient and the amount to be transfered. It supports transfers in Kobo as well, just add the necessary decimals. """ self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account}) try: # Search for the existence of the Register link - indicating a new account # Payments cannot be made from an account that isn't registered - obviously. self.br.find_link(text='Register') raise InvalidAccountException except mechanize.LinkNotFoundError: pass # Follow through by clicking links to get to the payment form self.br.follow_link(text='My sarafu') self.br.follow_link(text='Transfer') self.br.follow_link(text='sarafu-to-sarafu') self.br.select_form(nr=0) self.br['recipient'] = recipient self.br.new_control('text', 'pin', attrs={'value': self.pin}) self.br.new_control('text', 'amount', attrs={'value': amount}) self.br.new_control('text', 'channel', attrs={'value': 'WAP'}) r = self.br.submit() # Right away, we can tell if the recipient doesn't exist and raise an exception if re.search(r'Recipient not found', r): raise InvalidAccountException self.br.select_form(nr=0) self.br.new_control('text', 'pin', attrs={'value': self.pin}) r = self.br.submit().read() # We don't get to know if our pin was valid until this step if re.search(r'Invalid PIN', r): raise AuthDeniedException # An error could occur for other reasons if re.search(r'Error occured', r): raise RequestErrorException # If it was successful, we extract the transaction id and return that if re.search(r'Transaction id: (?P<txnid>\d+)', r): match = re.search(r'Transaction id: (?P<txnid>\d+)', r) return match.group('txnid')
python
def make_payment(self, recipient, amount, description=None): """ make_payment allows for automated payments. A use case includes the ability to trigger a payment to a customer who requires a refund for example. You only need to provide the recipient and the amount to be transfered. It supports transfers in Kobo as well, just add the necessary decimals. """ self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account}) try: # Search for the existence of the Register link - indicating a new account # Payments cannot be made from an account that isn't registered - obviously. self.br.find_link(text='Register') raise InvalidAccountException except mechanize.LinkNotFoundError: pass # Follow through by clicking links to get to the payment form self.br.follow_link(text='My sarafu') self.br.follow_link(text='Transfer') self.br.follow_link(text='sarafu-to-sarafu') self.br.select_form(nr=0) self.br['recipient'] = recipient self.br.new_control('text', 'pin', attrs={'value': self.pin}) self.br.new_control('text', 'amount', attrs={'value': amount}) self.br.new_control('text', 'channel', attrs={'value': 'WAP'}) r = self.br.submit() # Right away, we can tell if the recipient doesn't exist and raise an exception if re.search(r'Recipient not found', r): raise InvalidAccountException self.br.select_form(nr=0) self.br.new_control('text', 'pin', attrs={'value': self.pin}) r = self.br.submit().read() # We don't get to know if our pin was valid until this step if re.search(r'Invalid PIN', r): raise AuthDeniedException # An error could occur for other reasons if re.search(r'Error occured', r): raise RequestErrorException # If it was successful, we extract the transaction id and return that if re.search(r'Transaction id: (?P<txnid>\d+)', r): match = re.search(r'Transaction id: (?P<txnid>\d+)', r) return match.group('txnid')
[ "def", "make_payment", "(", "self", ",", "recipient", ",", "amount", ",", "description", "=", "None", ")", ":", "self", ".", "br", ".", "open", "(", "self", ".", "MOBILE_WEB_URL", "%", "{", "'accountno'", ":", "self", ".", "account", "}", ")", "try", ...
make_payment allows for automated payments. A use case includes the ability to trigger a payment to a customer who requires a refund for example. You only need to provide the recipient and the amount to be transfered. It supports transfers in Kobo as well, just add the necessary decimals.
[ "make_payment", "allows", "for", "automated", "payments", ".", "A", "use", "case", "includes", "the", "ability", "to", "trigger", "a", "payment", "to", "a", "customer", "who", "requires", "a", "refund", "for", "example", ".", "You", "only", "need", "to", "...
train
https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/pesaply.py#L130-L177
pesaply/sarafu
pesaply.py
pesaplyMM.get_balance
def get_balance(self): """ Retrieves the balance for the configured account """ self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account}) try: # Search for the existence of the Register link - indicating a new account self.br.find_link(text='Register') raise InvalidAccountException except mechanize.LinkNotFoundError: pass self.br.follow_link(text='My sarafu') self.br.follow_link(text='Balance Inquiry') self.br.select_form(nr=0) self.br['pin'] = self.pin r = self.br.submit().read() # Pin valid? if re.search(r'Invalid PIN', r): raise AuthDeniedException # An error could occur for other reasons if re.search(r'Error occured', r): raise RequestErrorException # If it was successful, we extract the balance if re.search(r'Your balance is TSH (?P<balance>[\d\.]+)', r): match = re.search(r'Your balance is TSH (?P<balance>[\d\.]+)', r) return match.group('balance')
python
def get_balance(self): """ Retrieves the balance for the configured account """ self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account}) try: # Search for the existence of the Register link - indicating a new account self.br.find_link(text='Register') raise InvalidAccountException except mechanize.LinkNotFoundError: pass self.br.follow_link(text='My sarafu') self.br.follow_link(text='Balance Inquiry') self.br.select_form(nr=0) self.br['pin'] = self.pin r = self.br.submit().read() # Pin valid? if re.search(r'Invalid PIN', r): raise AuthDeniedException # An error could occur for other reasons if re.search(r'Error occured', r): raise RequestErrorException # If it was successful, we extract the balance if re.search(r'Your balance is TSH (?P<balance>[\d\.]+)', r): match = re.search(r'Your balance is TSH (?P<balance>[\d\.]+)', r) return match.group('balance')
[ "def", "get_balance", "(", "self", ")", ":", "self", ".", "br", ".", "open", "(", "self", ".", "MOBILE_WEB_URL", "%", "{", "'accountno'", ":", "self", ".", "account", "}", ")", "try", ":", "# Search for the existence of the Register link - indicating a new account...
Retrieves the balance for the configured account
[ "Retrieves", "the", "balance", "for", "the", "configured", "account" ]
train
https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/pesaply.py#L179-L208
pesaply/sarafu
pesaply.py
pesaplyMM.get_url
def get_url(self, url): """ Internally used to retrieve the contents of a URL """ _r = self.br.open(url) # check that we've not been redirected to the login page if self.br.geturl().startswith(self.AUTH_URL): raise AuthRequiredException elif self.br.geturl().startswith(self.ERROR_URL): raise RequestErrorException else: return _r.read()
python
def get_url(self, url): """ Internally used to retrieve the contents of a URL """ _r = self.br.open(url) # check that we've not been redirected to the login page if self.br.geturl().startswith(self.AUTH_URL): raise AuthRequiredException elif self.br.geturl().startswith(self.ERROR_URL): raise RequestErrorException else: return _r.read()
[ "def", "get_url", "(", "self", ",", "url", ")", ":", "_r", "=", "self", ".", "br", ".", "open", "(", "url", ")", "# check that we've not been redirected to the login page", "if", "self", ".", "br", ".", "geturl", "(", ")", ".", "startswith", "(", "self", ...
Internally used to retrieve the contents of a URL
[ "Internally", "used", "to", "retrieve", "the", "contents", "of", "a", "URL" ]
train
https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/pesaply.py#L221-L233
pesaply/sarafu
pesaply.py
pesaplyMM.post_url
def post_url(self, url, form): """ Internally used to retrieve the contents of a URL using the POST request method. The `form` parameter is a mechanize.HTMLForm object This method will use a POST request type regardless of the method used in the `form`. """ _r = self.br.open(url, form.click_request_data()[1]) # check that we've not been redirected to the login page or an error occured if self.br.geturl().startswith(self.AUTH_URL): raise AuthRequiredException elif self.br.geturl().startswith(self.ERROR_URL): raise RequestErrorException else: return _r.read()
python
def post_url(self, url, form): """ Internally used to retrieve the contents of a URL using the POST request method. The `form` parameter is a mechanize.HTMLForm object This method will use a POST request type regardless of the method used in the `form`. """ _r = self.br.open(url, form.click_request_data()[1]) # check that we've not been redirected to the login page or an error occured if self.br.geturl().startswith(self.AUTH_URL): raise AuthRequiredException elif self.br.geturl().startswith(self.ERROR_URL): raise RequestErrorException else: return _r.read()
[ "def", "post_url", "(", "self", ",", "url", ",", "form", ")", ":", "_r", "=", "self", ".", "br", ".", "open", "(", "url", ",", "form", ".", "click_request_data", "(", ")", "[", "1", "]", ")", "# check that we've not been redirected to the login page or an er...
Internally used to retrieve the contents of a URL using the POST request method. The `form` parameter is a mechanize.HTMLForm object This method will use a POST request type regardless of the method used in the `form`.
[ "Internally", "used", "to", "retrieve", "the", "contents", "of", "a", "URL", "using", "the", "POST", "request", "method", ".", "The", "form", "parameter", "is", "a", "mechanize", ".", "HTMLForm", "object", "This", "method", "will", "use", "a", "POST", "req...
train
https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/pesaply.py#L235-L251
pesaply/sarafu
pesaply.py
pesaplyMM._parse_transactions
def _parse_transactions(self, response): """ This method parses the CSV output in `get_transactions` to generate a usable list of transactions that use native python data types """ transactions = list() if response: f = StringIO(response) reader = csv.DictReader(f) for line in reader: txn = {} txn['date'] = datetime.strptime(line['Date'], '%d/%m/%Y %H:%M:%S') txn['description'] = line['Description'] txn['amount'] = float(line['Amount'].replace(',', '')) txn['reference'] = line['Transaction number'] txn['sender'] = line['???transfer.fromOwner???'] txn['recipient'] = line['???transfer.toOwner???'] txn['currency'] = 'TSH' txn['comment'] = line['Transaction type'] transactions.append(txn) return transactions
python
def _parse_transactions(self, response): """ This method parses the CSV output in `get_transactions` to generate a usable list of transactions that use native python data types """ transactions = list() if response: f = StringIO(response) reader = csv.DictReader(f) for line in reader: txn = {} txn['date'] = datetime.strptime(line['Date'], '%d/%m/%Y %H:%M:%S') txn['description'] = line['Description'] txn['amount'] = float(line['Amount'].replace(',', '')) txn['reference'] = line['Transaction number'] txn['sender'] = line['???transfer.fromOwner???'] txn['recipient'] = line['???transfer.toOwner???'] txn['currency'] = 'TSH' txn['comment'] = line['Transaction type'] transactions.append(txn) return transactions
[ "def", "_parse_transactions", "(", "self", ",", "response", ")", ":", "transactions", "=", "list", "(", ")", "if", "response", ":", "f", "=", "StringIO", "(", "response", ")", "reader", "=", "csv", ".", "DictReader", "(", "f", ")", "for", "line", "in",...
This method parses the CSV output in `get_transactions` to generate a usable list of transactions that use native python data types
[ "This", "method", "parses", "the", "CSV", "output", "in", "get_transactions", "to", "generate", "a", "usable", "list", "of", "transactions", "that", "use", "native", "python", "data", "types" ]
train
https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/pesaply.py#L253-L278
ebu/PlugIt
plugit_proxy/views.py
getPlugItObject
def getPlugItObject(hproPk): """Return the plugit object and the baseURI to use if not in standalone mode""" from hprojects.models import HostedProject try: hproject = HostedProject.objects.get(pk=hproPk) except (HostedProject.DoesNotExist, ValueError): try: hproject = HostedProject.objects.get(plugItCustomUrlKey=hproPk) except HostedProject.DoesNotExist: raise Http404 if hproject.plugItURI == '' and not hproject.runURI: raise Http404 plugIt = PlugIt(hproject.plugItURI) # Test if we should use custom key if hasattr(hproject, 'plugItCustomUrlKey') and hproject.plugItCustomUrlKey: baseURI = reverse('plugIt.views.main', args=(hproject.plugItCustomUrlKey, '')) else: baseURI = reverse('plugIt.views.main', args=(hproject.pk, '')) return (plugIt, baseURI, hproject)
python
def getPlugItObject(hproPk): """Return the plugit object and the baseURI to use if not in standalone mode""" from hprojects.models import HostedProject try: hproject = HostedProject.objects.get(pk=hproPk) except (HostedProject.DoesNotExist, ValueError): try: hproject = HostedProject.objects.get(plugItCustomUrlKey=hproPk) except HostedProject.DoesNotExist: raise Http404 if hproject.plugItURI == '' and not hproject.runURI: raise Http404 plugIt = PlugIt(hproject.plugItURI) # Test if we should use custom key if hasattr(hproject, 'plugItCustomUrlKey') and hproject.plugItCustomUrlKey: baseURI = reverse('plugIt.views.main', args=(hproject.plugItCustomUrlKey, '')) else: baseURI = reverse('plugIt.views.main', args=(hproject.pk, '')) return (plugIt, baseURI, hproject)
[ "def", "getPlugItObject", "(", "hproPk", ")", ":", "from", "hprojects", ".", "models", "import", "HostedProject", "try", ":", "hproject", "=", "HostedProject", ".", "objects", ".", "get", "(", "pk", "=", "hproPk", ")", "except", "(", "HostedProject", ".", ...
Return the plugit object and the baseURI to use if not in standalone mode
[ "Return", "the", "plugit", "object", "and", "the", "baseURI", "to", "use", "if", "not", "in", "standalone", "mode" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L36-L59
ebu/PlugIt
plugit_proxy/views.py
generate_user
def generate_user(mode=None, pk=None): """Return a false user for standalone mode""" user = None if mode == 'log' or pk == "-1": user = DUser(pk=-1, username='Logged', first_name='Logged', last_name='Hector', email='logeedin@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/ebuio1?d=retro' user.ebuio_member = False user.ebuio_admin = False user.subscription_labels = [] elif mode == 'mem' or pk == "-2": user = DUser(pk=-2, username='Member', first_name='Member', last_name='Luc', email='memeber@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/ebuio2?d=retro' user.ebuio_member = True user.ebuio_admin = False user.subscription_labels = [] elif mode == 'adm' or pk == "-3": user = DUser(pk=-3, username='Admin', first_name='Admin', last_name='Charles', email='admin@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/ebuio3?d=retro' user.ebuio_member = True user.ebuio_admin = True user.subscription_labels = [] elif mode == 'ano': user = AnonymousUser() user.email = 'nobody@plugit-standalone.ebuio' user.first_name = 'Ano' user.last_name = 'Nymous' user.ebuio_member = False user.ebuio_admin = False user.subscription_labels = [] elif settings.PIAPI_STANDALONE and pk >= 0: # Generate an unknown user for compatibility reason in standalone mode user = DUser(pk=pk, username='Logged', first_name='Unknown', last_name='Other User', email='unknown@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/unknown?d=retro' user.ebuio_member = False user.ebuio_admin = False user.subscription_labels = [] if user: user.ebuio_orga_member = user.ebuio_member user.ebuio_orga_admin = user.ebuio_admin return user
python
def generate_user(mode=None, pk=None): """Return a false user for standalone mode""" user = None if mode == 'log' or pk == "-1": user = DUser(pk=-1, username='Logged', first_name='Logged', last_name='Hector', email='logeedin@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/ebuio1?d=retro' user.ebuio_member = False user.ebuio_admin = False user.subscription_labels = [] elif mode == 'mem' or pk == "-2": user = DUser(pk=-2, username='Member', first_name='Member', last_name='Luc', email='memeber@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/ebuio2?d=retro' user.ebuio_member = True user.ebuio_admin = False user.subscription_labels = [] elif mode == 'adm' or pk == "-3": user = DUser(pk=-3, username='Admin', first_name='Admin', last_name='Charles', email='admin@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/ebuio3?d=retro' user.ebuio_member = True user.ebuio_admin = True user.subscription_labels = [] elif mode == 'ano': user = AnonymousUser() user.email = 'nobody@plugit-standalone.ebuio' user.first_name = 'Ano' user.last_name = 'Nymous' user.ebuio_member = False user.ebuio_admin = False user.subscription_labels = [] elif settings.PIAPI_STANDALONE and pk >= 0: # Generate an unknown user for compatibility reason in standalone mode user = DUser(pk=pk, username='Logged', first_name='Unknown', last_name='Other User', email='unknown@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.com/avatar/unknown?d=retro' user.ebuio_member = False user.ebuio_admin = False user.subscription_labels = [] if user: user.ebuio_orga_member = user.ebuio_member user.ebuio_orga_admin = user.ebuio_admin return user
[ "def", "generate_user", "(", "mode", "=", "None", ",", "pk", "=", "None", ")", ":", "user", "=", "None", "if", "mode", "==", "'log'", "or", "pk", "==", "\"-1\"", ":", "user", "=", "DUser", "(", "pk", "=", "-", "1", ",", "username", "=", "'Logged'...
Return a false user for standalone mode
[ "Return", "a", "false", "user", "for", "standalone", "mode" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L62-L105
ebu/PlugIt
plugit_proxy/views.py
gen404
def gen404(request, baseURI, reason, project=None): """Return a 404 error""" return HttpResponseNotFound( render_to_response('plugIt/404.html', {'context': { 'reason': reason, 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': project }, context_instance=RequestContext(request)))
python
def gen404(request, baseURI, reason, project=None): """Return a 404 error""" return HttpResponseNotFound( render_to_response('plugIt/404.html', {'context': { 'reason': reason, 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': project }, context_instance=RequestContext(request)))
[ "def", "gen404", "(", "request", ",", "baseURI", ",", "reason", ",", "project", "=", "None", ")", ":", "return", "HttpResponseNotFound", "(", "render_to_response", "(", "'plugIt/404.html'", ",", "{", "'context'", ":", "{", "'reason'", ":", "reason", ",", "'e...
Return a 404 error
[ "Return", "a", "404", "error" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L118-L128
ebu/PlugIt
plugit_proxy/views.py
gen500
def gen500(request, baseURI, project=None): """Return a 500 error""" return HttpResponseServerError( render_to_response('plugIt/500.html', { 'context': { 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': project }, context_instance=RequestContext(request)))
python
def gen500(request, baseURI, project=None): """Return a 500 error""" return HttpResponseServerError( render_to_response('plugIt/500.html', { 'context': { 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': project }, context_instance=RequestContext(request)))
[ "def", "gen500", "(", "request", ",", "baseURI", ",", "project", "=", "None", ")", ":", "return", "HttpResponseServerError", "(", "render_to_response", "(", "'plugIt/500.html'", ",", "{", "'context'", ":", "{", "'ebuio_baseUrl'", ":", "baseURI", ",", "'ebuio_use...
Return a 500 error
[ "Return", "a", "500", "error" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L131-L140
ebu/PlugIt
plugit_proxy/views.py
gen403
def gen403(request, baseURI, reason, project=None): """Return a 403 error""" orgas = None public_ask = False if not settings.PIAPI_STANDALONE: from organizations.models import Organization if project and project.plugItLimitOrgaJoinable: orgas = project.plugItOrgaJoinable.order_by('name').all() else: orgas = Organization.objects.order_by('name').all() rorgas = [] # Find and exclude the visitor orga for o in orgas: if str(o.pk) == settings.VISITOR_ORGA_PK: public_ask = True else: rorgas.append(o) orgas = rorgas return HttpResponseForbidden(render_to_response('plugIt/403.html', {'context': { 'reason': reason, 'orgas': orgas, 'public_ask': public_ask, 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': project }, context_instance=RequestContext(request)))
python
def gen403(request, baseURI, reason, project=None): """Return a 403 error""" orgas = None public_ask = False if not settings.PIAPI_STANDALONE: from organizations.models import Organization if project and project.plugItLimitOrgaJoinable: orgas = project.plugItOrgaJoinable.order_by('name').all() else: orgas = Organization.objects.order_by('name').all() rorgas = [] # Find and exclude the visitor orga for o in orgas: if str(o.pk) == settings.VISITOR_ORGA_PK: public_ask = True else: rorgas.append(o) orgas = rorgas return HttpResponseForbidden(render_to_response('plugIt/403.html', {'context': { 'reason': reason, 'orgas': orgas, 'public_ask': public_ask, 'ebuio_baseUrl': baseURI, 'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'), }, 'project': project }, context_instance=RequestContext(request)))
[ "def", "gen403", "(", "request", ",", "baseURI", ",", "reason", ",", "project", "=", "None", ")", ":", "orgas", "=", "None", "public_ask", "=", "False", "if", "not", "settings", ".", "PIAPI_STANDALONE", ":", "from", "organizations", ".", "models", "import"...
Return a 403 error
[ "Return", "a", "403", "error" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L143-L176
ebu/PlugIt
plugit_proxy/views.py
get_cache_key
def get_cache_key(request, meta, orgaMode, currentOrga): """Return the cache key to use""" # Caching cacheKey = None if 'cache_time' in meta: if meta['cache_time'] > 0: # by default, no cache by user useUser = False # If a logged user in needed, cache the result by user if ('only_logged_user' in meta and meta['only_logged_user']) or \ ('only_member_user' in meta and meta['only_member_user']) or \ ('only_admin_user' in meta and meta['only_admin_user']) or \ ('only_orga_member_user' in meta and meta['only_orga_member_user']) or \ ('only_orga_admin_user' in meta and meta['only_orga_admin_user']): useUser = True # If a value if present in meta, use it if 'cache_by_user' in meta: useUser = meta['cache_by_user'] cacheKey = '-' # Add user info if needed if useUser: cacheKey += str(request.user.pk) + 'usr-' # Add orga if orgaMode: cacheKey += str(currentOrga.pk) + 'org-' # Add current query cacheKey += request.get_full_path() # Add current template (if the template changed, cache must be invalided) cacheKey += meta['template_tag'] return cacheKey
python
def get_cache_key(request, meta, orgaMode, currentOrga): """Return the cache key to use""" # Caching cacheKey = None if 'cache_time' in meta: if meta['cache_time'] > 0: # by default, no cache by user useUser = False # If a logged user in needed, cache the result by user if ('only_logged_user' in meta and meta['only_logged_user']) or \ ('only_member_user' in meta and meta['only_member_user']) or \ ('only_admin_user' in meta and meta['only_admin_user']) or \ ('only_orga_member_user' in meta and meta['only_orga_member_user']) or \ ('only_orga_admin_user' in meta and meta['only_orga_admin_user']): useUser = True # If a value if present in meta, use it if 'cache_by_user' in meta: useUser = meta['cache_by_user'] cacheKey = '-' # Add user info if needed if useUser: cacheKey += str(request.user.pk) + 'usr-' # Add orga if orgaMode: cacheKey += str(currentOrga.pk) + 'org-' # Add current query cacheKey += request.get_full_path() # Add current template (if the template changed, cache must be invalided) cacheKey += meta['template_tag'] return cacheKey
[ "def", "get_cache_key", "(", "request", ",", "meta", ",", "orgaMode", ",", "currentOrga", ")", ":", "# Caching", "cacheKey", "=", "None", "if", "'cache_time'", "in", "meta", ":", "if", "meta", "[", "'cache_time'", "]", ">", "0", ":", "# by default, no cache ...
Return the cache key to use
[ "Return", "the", "cache", "key", "to", "use" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L187-L227
ebu/PlugIt
plugit_proxy/views.py
check_rights_and_access
def check_rights_and_access(request, meta, project=None): """Check if the user can access the page""" # User must be logged ? if ('only_logged_user' in meta and meta['only_logged_user']): if not request.user.is_authenticated(): return gen403(request, baseURI, 'only_logged_user', project) # User must be member of the project ? if ('only_member_user' in meta and meta['only_member_user']): if not request.user.ebuio_member: return gen403(request, baseURI, 'only_member_user', project) # User must be administrator of the project ? if ('only_admin_user' in meta and meta['only_admin_user']): if not request.user.ebuio_admin: return gen403(request, baseURI, 'only_admin_user', project) # User must be member of the orga ? if ('only_orga_member_user' in meta and meta['only_orga_member_user']): if not request.user.ebuio_orga_member: return gen403(request, baseURI, 'only_orga_member_user', project) # User must be administrator of the orga ? if ('only_orga_admin_user' in meta and meta['only_orga_admin_user']): if not request.user.ebuio_orga_admin: return gen403(request, baseURI, 'only_orga_admin_user', project) # Remote IP must be in range ? if ('address_in_networks' in meta): if not is_requestaddress_in_networks(request, meta['address_in_networks']): return gen403(request, baseURI, 'address_in_networks', project)
python
def check_rights_and_access(request, meta, project=None): """Check if the user can access the page""" # User must be logged ? if ('only_logged_user' in meta and meta['only_logged_user']): if not request.user.is_authenticated(): return gen403(request, baseURI, 'only_logged_user', project) # User must be member of the project ? if ('only_member_user' in meta and meta['only_member_user']): if not request.user.ebuio_member: return gen403(request, baseURI, 'only_member_user', project) # User must be administrator of the project ? if ('only_admin_user' in meta and meta['only_admin_user']): if not request.user.ebuio_admin: return gen403(request, baseURI, 'only_admin_user', project) # User must be member of the orga ? if ('only_orga_member_user' in meta and meta['only_orga_member_user']): if not request.user.ebuio_orga_member: return gen403(request, baseURI, 'only_orga_member_user', project) # User must be administrator of the orga ? if ('only_orga_admin_user' in meta and meta['only_orga_admin_user']): if not request.user.ebuio_orga_admin: return gen403(request, baseURI, 'only_orga_admin_user', project) # Remote IP must be in range ? if ('address_in_networks' in meta): if not is_requestaddress_in_networks(request, meta['address_in_networks']): return gen403(request, baseURI, 'address_in_networks', project)
[ "def", "check_rights_and_access", "(", "request", ",", "meta", ",", "project", "=", "None", ")", ":", "# User must be logged ?", "if", "(", "'only_logged_user'", "in", "meta", "and", "meta", "[", "'only_logged_user'", "]", ")", ":", "if", "not", "request", "."...
Check if the user can access the page
[ "Check", "if", "the", "user", "can", "access", "the", "page" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L230-L260
ebu/PlugIt
plugit_proxy/views.py
is_requestaddress_in_networks
def is_requestaddress_in_networks(request, networks): """Helper method to check if the remote real ip of a request is in a network""" from ipware.ip import get_real_ip, get_ip # Get the real IP, i.e. no reverse proxy, no nginx ip = get_real_ip(request) if not ip: ip = get_ip(request) if not ip: return False # For all networks for network in networks: if is_address_in_network(ip, network): return True return False
python
def is_requestaddress_in_networks(request, networks): """Helper method to check if the remote real ip of a request is in a network""" from ipware.ip import get_real_ip, get_ip # Get the real IP, i.e. no reverse proxy, no nginx ip = get_real_ip(request) if not ip: ip = get_ip(request) if not ip: return False # For all networks for network in networks: if is_address_in_network(ip, network): return True return False
[ "def", "is_requestaddress_in_networks", "(", "request", ",", "networks", ")", ":", "from", "ipware", ".", "ip", "import", "get_real_ip", ",", "get_ip", "# Get the real IP, i.e. no reverse proxy, no nginx", "ip", "=", "get_real_ip", "(", "request", ")", "if", "not", ...
Helper method to check if the remote real ip of a request is in a network
[ "Helper", "method", "to", "check", "if", "the", "remote", "real", "ip", "of", "a", "request", "is", "in", "a", "network" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L263-L279
ebu/PlugIt
plugit_proxy/views.py
is_address_in_network
def is_address_in_network(ip, net): """Is an address in a network""" # http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python import socket import struct ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') if int(bits) == 0: return True net = struct.unpack('=L', socket.inet_aton(netaddr))[0] mask = ((2L << int(bits) - 1) - 1) return (ipaddr & mask) == (net & mask)
python
def is_address_in_network(ip, net): """Is an address in a network""" # http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python import socket import struct ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') if int(bits) == 0: return True net = struct.unpack('=L', socket.inet_aton(netaddr))[0] mask = ((2L << int(bits) - 1) - 1) return (ipaddr & mask) == (net & mask)
[ "def", "is_address_in_network", "(", "ip", ",", "net", ")", ":", "# http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python", "import", "socket", "import", "struct", "ipaddr", "=", "struct", ".", "unpack", "(", "'=L'", ",", "socket", "...
Is an address in a network
[ "Is", "an", "address", "in", "a", "network" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L282-L295
ebu/PlugIt
plugit_proxy/views.py
find_in_cache
def find_in_cache(cacheKey): """Check if the content exists in cache and return it""" # If we have to use cache, we try to find the result in cache if cacheKey: data = cache.get('plugit-cache-' + cacheKey, None) # We found a result, we can return it if data: return (data['result'], data['menu'], data['context']) return (None, None, None)
python
def find_in_cache(cacheKey): """Check if the content exists in cache and return it""" # If we have to use cache, we try to find the result in cache if cacheKey: data = cache.get('plugit-cache-' + cacheKey, None) # We found a result, we can return it if data: return (data['result'], data['menu'], data['context']) return (None, None, None)
[ "def", "find_in_cache", "(", "cacheKey", ")", ":", "# If we have to use cache, we try to find the result in cache", "if", "cacheKey", ":", "data", "=", "cache", ".", "get", "(", "'plugit-cache-'", "+", "cacheKey", ",", "None", ")", "# We found a result, we can return it",...
Check if the content exists in cache and return it
[ "Check", "if", "the", "content", "exists", "in", "cache", "and", "return", "it" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L298-L308
ebu/PlugIt
plugit_proxy/views.py
build_base_parameters
def build_base_parameters(request): """Build the list of parameters to forward from the post and get parameters""" getParameters = {} postParameters = {} files = {} # Copy GET parameters, excluding ebuio_* for v in request.GET: if v[:6] != 'ebuio_': val = request.GET.getlist(v) if len(val) == 1: getParameters[v] = val[0] else: getParameters[v] = val # If using post, copy post parameters and files. Excluding ebuio_* if request.method == 'POST': for v in request.POST: if v[:6] != 'ebuio_': val = request.POST.getlist(v) if len(val) == 1: postParameters[v] = val[0] else: postParameters[v] = val for v in request.FILES: if v[:6] != 'ebuio_': files[v] = request.FILES[v] # .chunks() return (getParameters, postParameters, files)
python
def build_base_parameters(request): """Build the list of parameters to forward from the post and get parameters""" getParameters = {} postParameters = {} files = {} # Copy GET parameters, excluding ebuio_* for v in request.GET: if v[:6] != 'ebuio_': val = request.GET.getlist(v) if len(val) == 1: getParameters[v] = val[0] else: getParameters[v] = val # If using post, copy post parameters and files. Excluding ebuio_* if request.method == 'POST': for v in request.POST: if v[:6] != 'ebuio_': val = request.POST.getlist(v) if len(val) == 1: postParameters[v] = val[0] else: postParameters[v] = val for v in request.FILES: if v[:6] != 'ebuio_': files[v] = request.FILES[v] # .chunks() return (getParameters, postParameters, files)
[ "def", "build_base_parameters", "(", "request", ")", ":", "getParameters", "=", "{", "}", "postParameters", "=", "{", "}", "files", "=", "{", "}", "# Copy GET parameters, excluding ebuio_*", "for", "v", "in", "request", ".", "GET", ":", "if", "v", "[", ":", ...
Build the list of parameters to forward from the post and get parameters
[ "Build", "the", "list", "of", "parameters", "to", "forward", "from", "the", "post", "and", "get", "parameters" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L311-L343
ebu/PlugIt
plugit_proxy/views.py
build_user_requested_parameters
def build_user_requested_parameters(request, meta): """Build the list of parameters requested by the plugit server""" postParameters = {} getParameters = {} files = {} # Add parameters requested by the server if 'user_info' in meta: for prop in meta['user_info']: # Test if the value exist, otherwise return None value = None if hasattr(request.user, prop) and prop in settings.PIAPI_USERDATA: value = getattr(request.user, prop) else: raise Exception('requested user attribute "%s", ' 'does not exist or requesting is not allowed' % prop) # Add informations to get or post parameters, depending on the current method if request.method == 'POST': postParameters['ebuio_u_' + prop] = value else: getParameters['ebuio_u_' + prop] = value return (getParameters, postParameters, files)
python
def build_user_requested_parameters(request, meta): """Build the list of parameters requested by the plugit server""" postParameters = {} getParameters = {} files = {} # Add parameters requested by the server if 'user_info' in meta: for prop in meta['user_info']: # Test if the value exist, otherwise return None value = None if hasattr(request.user, prop) and prop in settings.PIAPI_USERDATA: value = getattr(request.user, prop) else: raise Exception('requested user attribute "%s", ' 'does not exist or requesting is not allowed' % prop) # Add informations to get or post parameters, depending on the current method if request.method == 'POST': postParameters['ebuio_u_' + prop] = value else: getParameters['ebuio_u_' + prop] = value return (getParameters, postParameters, files)
[ "def", "build_user_requested_parameters", "(", "request", ",", "meta", ")", ":", "postParameters", "=", "{", "}", "getParameters", "=", "{", "}", "files", "=", "{", "}", "# Add parameters requested by the server", "if", "'user_info'", "in", "meta", ":", "for", "...
Build the list of parameters requested by the plugit server
[ "Build", "the", "list", "of", "parameters", "requested", "by", "the", "plugit", "server" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L346-L371
ebu/PlugIt
plugit_proxy/views.py
build_parameters
def build_parameters(request, meta, orgaMode, currentOrga): """Return the list of get, post and file parameters to send""" postParameters = {} getParameters = {} files = {} def update_parameters(data): tmp_getParameters, tmp_postParameters, tmp_files = data getParameters.update(tmp_getParameters) postParameters.update(tmp_postParameters) files.update(tmp_files) update_parameters(build_base_parameters(request)) update_parameters(build_user_requested_parameters(request, meta)) update_parameters(build_orga_parameters(request, orgaMode, currentOrga)) return (getParameters, postParameters, files)
python
def build_parameters(request, meta, orgaMode, currentOrga): """Return the list of get, post and file parameters to send""" postParameters = {} getParameters = {} files = {} def update_parameters(data): tmp_getParameters, tmp_postParameters, tmp_files = data getParameters.update(tmp_getParameters) postParameters.update(tmp_postParameters) files.update(tmp_files) update_parameters(build_base_parameters(request)) update_parameters(build_user_requested_parameters(request, meta)) update_parameters(build_orga_parameters(request, orgaMode, currentOrga)) return (getParameters, postParameters, files)
[ "def", "build_parameters", "(", "request", ",", "meta", ",", "orgaMode", ",", "currentOrga", ")", ":", "postParameters", "=", "{", "}", "getParameters", "=", "{", "}", "files", "=", "{", "}", "def", "update_parameters", "(", "data", ")", ":", "tmp_getParam...
Return the list of get, post and file parameters to send
[ "Return", "the", "list", "of", "get", "post", "and", "file", "parameters", "to", "send" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L389-L407
ebu/PlugIt
plugit_proxy/views.py
build_extra_headers
def build_extra_headers(request, proxyMode, orgaMode, currentOrga): """Build the list of extra headers""" things_to_add = {} # If in proxymode, add needed infos to headers if proxyMode: # User for prop in settings.PIAPI_USERDATA: if hasattr(request.user, prop): things_to_add['user_' + prop] = getattr(request.user, prop) # Orga if orgaMode: things_to_add['orga_pk'] = currentOrga.pk things_to_add['orga_name'] = currentOrga.name things_to_add['orga_codops'] = currentOrga.ebu_codops # General things_to_add['base_url'] = baseURI if request and hasattr(request, 'META'): if 'REMOTE_ADDR' in request.META: things_to_add['remote-addr'] = request.META['REMOTE_ADDR'] if 'HTTP_X_FORWARDED_FOR' in request.META and getattr(settings, 'HONOR_X_FORWARDED_FOR'): things_to_add['remote-addr'] = request.META['HTTP_X_FORWARDED_FOR'] for meta_header, dest_header in [('HTTP_IF_NONE_MATCH', 'If-None-Match'), ('HTTP_ORIGIN', 'Origin'), ('HTTP_ACCESS_CONtROL_REQUEST_METHOD', 'Access-Control-Request-Method'), ('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'Access-Control-Request-Headers')]: if meta_header in request.META: things_to_add[dest_header] = request.META[meta_header] return things_to_add
python
def build_extra_headers(request, proxyMode, orgaMode, currentOrga): """Build the list of extra headers""" things_to_add = {} # If in proxymode, add needed infos to headers if proxyMode: # User for prop in settings.PIAPI_USERDATA: if hasattr(request.user, prop): things_to_add['user_' + prop] = getattr(request.user, prop) # Orga if orgaMode: things_to_add['orga_pk'] = currentOrga.pk things_to_add['orga_name'] = currentOrga.name things_to_add['orga_codops'] = currentOrga.ebu_codops # General things_to_add['base_url'] = baseURI if request and hasattr(request, 'META'): if 'REMOTE_ADDR' in request.META: things_to_add['remote-addr'] = request.META['REMOTE_ADDR'] if 'HTTP_X_FORWARDED_FOR' in request.META and getattr(settings, 'HONOR_X_FORWARDED_FOR'): things_to_add['remote-addr'] = request.META['HTTP_X_FORWARDED_FOR'] for meta_header, dest_header in [('HTTP_IF_NONE_MATCH', 'If-None-Match'), ('HTTP_ORIGIN', 'Origin'), ('HTTP_ACCESS_CONtROL_REQUEST_METHOD', 'Access-Control-Request-Method'), ('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'Access-Control-Request-Headers')]: if meta_header in request.META: things_to_add[dest_header] = request.META[meta_header] return things_to_add
[ "def", "build_extra_headers", "(", "request", ",", "proxyMode", ",", "orgaMode", ",", "currentOrga", ")", ":", "things_to_add", "=", "{", "}", "# If in proxymode, add needed infos to headers", "if", "proxyMode", ":", "# User", "for", "prop", "in", "settings", ".", ...
Build the list of extra headers
[ "Build", "the", "list", "of", "extra", "headers" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L410-L443
ebu/PlugIt
plugit_proxy/views.py
handle_special_cases
def handle_special_cases(request, data, baseURI, meta): """Handle sepcial cases for returned values by the doAction function""" if request.method == 'OPTIONS': r = HttpResponse('') return r if data is None: return gen404(request, baseURI, 'data') if data.__class__.__name__ == 'PlugIt500': return gen500(request, baseURI) if data.__class__.__name__ == 'PlugItSpecialCode': r = HttpResponse('') r.status_code = data.code return r if data.__class__.__name__ == 'PlugItRedirect': url = data.url if not data.no_prefix: url = baseURI + url return HttpResponseRedirect(url) if data.__class__.__name__ == 'PlugItFile': response = HttpResponse(data.content, content_type=data.content_type) response['Content-Disposition'] = data.content_disposition return response if data.__class__.__name__ == 'PlugItNoTemplate': response = HttpResponse(data.content) return response if meta.get('json_only', None): # Just send the json back # Return application/json if requested if 'HTTP_ACCEPT' in request.META and request.META['HTTP_ACCEPT'].find('json') != -1: return JsonResponse(data) # Return json data without html content type, since json was not # requiered result = json.dumps(data) return HttpResponse(result) if meta.get('xml_only', None): # Just send the xml back return HttpResponse(data['xml'], content_type='application/xml')
python
def handle_special_cases(request, data, baseURI, meta): """Handle sepcial cases for returned values by the doAction function""" if request.method == 'OPTIONS': r = HttpResponse('') return r if data is None: return gen404(request, baseURI, 'data') if data.__class__.__name__ == 'PlugIt500': return gen500(request, baseURI) if data.__class__.__name__ == 'PlugItSpecialCode': r = HttpResponse('') r.status_code = data.code return r if data.__class__.__name__ == 'PlugItRedirect': url = data.url if not data.no_prefix: url = baseURI + url return HttpResponseRedirect(url) if data.__class__.__name__ == 'PlugItFile': response = HttpResponse(data.content, content_type=data.content_type) response['Content-Disposition'] = data.content_disposition return response if data.__class__.__name__ == 'PlugItNoTemplate': response = HttpResponse(data.content) return response if meta.get('json_only', None): # Just send the json back # Return application/json if requested if 'HTTP_ACCEPT' in request.META and request.META['HTTP_ACCEPT'].find('json') != -1: return JsonResponse(data) # Return json data without html content type, since json was not # requiered result = json.dumps(data) return HttpResponse(result) if meta.get('xml_only', None): # Just send the xml back return HttpResponse(data['xml'], content_type='application/xml')
[ "def", "handle_special_cases", "(", "request", ",", "data", ",", "baseURI", ",", "meta", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "r", "=", "HttpResponse", "(", "''", ")", "return", "r", "if", "data", "is", "None", ":", "return...
Handle sepcial cases for returned values by the doAction function
[ "Handle", "sepcial", "cases", "for", "returned", "values", "by", "the", "doAction", "function" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L446-L492
ebu/PlugIt
plugit_proxy/views.py
build_final_response
def build_final_response(request, meta, result, menu, hproject, proxyMode, context): """Build the final response to send back to the browser""" if 'no_template' in meta and meta['no_template']: # Just send the json back return HttpResponse(result) # TODO this breaks pages not using new template # Add sidebar toggler if plugit did not add by itself # if not "sidebar-toggler" in result: # result = "<div class=\"menubar\"><div class=\"sidebar-toggler visible-xs\"><i class=\"ion-navicon\"></i></div></div>" + result # render the template into the whole page if not settings.PIAPI_STANDALONE: return render_to_response('plugIt/' + hproject.get_plugItTemplate_display(), {"project": hproject, "plugit_content": result, "plugit_menu": menu, 'context': context}, context_instance=RequestContext(request)) if proxyMode: # Force inclusion inside template return render_to_response('plugIt/base.html', {'plugit_content': result, "plugit_menu": menu, 'context': context}, context_instance=RequestContext(request)) renderPlugItTemplate = 'plugItBase.html' if settings.PIAPI_PLUGITTEMPLATE: renderPlugItTemplate = settings.PIAPI_PLUGITTEMPLATE return render_to_response('plugIt/' + renderPlugItTemplate, {"plugit_content": result, "plugit_menu": menu, 'context': context}, context_instance=RequestContext(request))
python
def build_final_response(request, meta, result, menu, hproject, proxyMode, context): """Build the final response to send back to the browser""" if 'no_template' in meta and meta['no_template']: # Just send the json back return HttpResponse(result) # TODO this breaks pages not using new template # Add sidebar toggler if plugit did not add by itself # if not "sidebar-toggler" in result: # result = "<div class=\"menubar\"><div class=\"sidebar-toggler visible-xs\"><i class=\"ion-navicon\"></i></div></div>" + result # render the template into the whole page if not settings.PIAPI_STANDALONE: return render_to_response('plugIt/' + hproject.get_plugItTemplate_display(), {"project": hproject, "plugit_content": result, "plugit_menu": menu, 'context': context}, context_instance=RequestContext(request)) if proxyMode: # Force inclusion inside template return render_to_response('plugIt/base.html', {'plugit_content': result, "plugit_menu": menu, 'context': context}, context_instance=RequestContext(request)) renderPlugItTemplate = 'plugItBase.html' if settings.PIAPI_PLUGITTEMPLATE: renderPlugItTemplate = settings.PIAPI_PLUGITTEMPLATE return render_to_response('plugIt/' + renderPlugItTemplate, {"plugit_content": result, "plugit_menu": menu, 'context': context}, context_instance=RequestContext(request))
[ "def", "build_final_response", "(", "request", ",", "meta", ",", "result", ",", "menu", ",", "hproject", ",", "proxyMode", ",", "context", ")", ":", "if", "'no_template'", "in", "meta", "and", "meta", "[", "'no_template'", "]", ":", "# Just send the json back"...
Build the final response to send back to the browser
[ "Build", "the", "final", "response", "to", "send", "back", "to", "the", "browser" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L495-L530
ebu/PlugIt
plugit_proxy/views.py
_get_node
def _get_node(template, context, name): ''' taken originally from http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template ''' for node in template: if isinstance(node, BlockNode) and node.name == name: return node.nodelist.render(context) elif isinstance(node, ExtendsNode): return _get_node(node.nodelist, context, name) # raise Exception("Node '%s' could not be found in template." % name) return ""
python
def _get_node(template, context, name): ''' taken originally from http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template ''' for node in template: if isinstance(node, BlockNode) and node.name == name: return node.nodelist.render(context) elif isinstance(node, ExtendsNode): return _get_node(node.nodelist, context, name) # raise Exception("Node '%s' could not be found in template." % name) return ""
[ "def", "_get_node", "(", "template", ",", "context", ",", "name", ")", ":", "for", "node", "in", "template", ":", "if", "isinstance", "(", "node", ",", "BlockNode", ")", "and", "node", ".", "name", "==", "name", ":", "return", "node", ".", "nodelist", ...
taken originally from http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
[ "taken", "originally", "from", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "2687173", "/", "django", "-", "how", "-", "can", "-", "i", "-", "get", "-", "a", "-", "block", "-", "from", "-", "a", "-", "template" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L533-L545
ebu/PlugIt
plugit_proxy/views.py
render_data
def render_data(context, templateContent, proxyMode, rendered_data, menukey='menubar'): """Render the template""" if proxyMode: # Update csrf_tokens csrf = unicode(context['csrf_token']) tag = u'{~__PLUGIT_CSRF_TOKEN__~}' rendered_data = unicode(rendered_data, 'utf-8').replace(tag, csrf) result = rendered_data # Render in proxy mode menu = None # Proxy mode plugit do not have menu else: # Render it template = Template(templateContent) result = template.render(context) menu = _get_node(template, context, menukey) return (result, menu)
python
def render_data(context, templateContent, proxyMode, rendered_data, menukey='menubar'): """Render the template""" if proxyMode: # Update csrf_tokens csrf = unicode(context['csrf_token']) tag = u'{~__PLUGIT_CSRF_TOKEN__~}' rendered_data = unicode(rendered_data, 'utf-8').replace(tag, csrf) result = rendered_data # Render in proxy mode menu = None # Proxy mode plugit do not have menu else: # Render it template = Template(templateContent) result = template.render(context) menu = _get_node(template, context, menukey) return (result, menu)
[ "def", "render_data", "(", "context", ",", "templateContent", ",", "proxyMode", ",", "rendered_data", ",", "menukey", "=", "'menubar'", ")", ":", "if", "proxyMode", ":", "# Update csrf_tokens", "csrf", "=", "unicode", "(", "context", "[", "'csrf_token'", "]", ...
Render the template
[ "Render", "the", "template" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L548-L566
ebu/PlugIt
plugit_proxy/views.py
cache_if_needed
def cache_if_needed(cacheKey, result, menu, context, meta): """Cache the result, if needed""" if cacheKey: # This will be a method in django 1.7 flat_context = {} for d in context.dicts: flat_context.update(d) del flat_context['csrf_token'] data = {'result': result, 'menu': menu, 'context': flat_context} cache.set('plugit-cache-' + cacheKey, data, meta['cache_time'])
python
def cache_if_needed(cacheKey, result, menu, context, meta): """Cache the result, if needed""" if cacheKey: # This will be a method in django 1.7 flat_context = {} for d in context.dicts: flat_context.update(d) del flat_context['csrf_token'] data = {'result': result, 'menu': menu, 'context': flat_context} cache.set('plugit-cache-' + cacheKey, data, meta['cache_time'])
[ "def", "cache_if_needed", "(", "cacheKey", ",", "result", ",", "menu", ",", "context", ",", "meta", ")", ":", "if", "cacheKey", ":", "# This will be a method in django 1.7", "flat_context", "=", "{", "}", "for", "d", "in", "context", ".", "dicts", ":", "flat...
Cache the result, if needed
[ "Cache", "the", "result", "if", "needed" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L569-L583
ebu/PlugIt
plugit_proxy/views.py
get_template
def get_template(request, query, meta, proxyMode): """Return (if needed) the template to use""" templateContent = None if not proxyMode: templateContent = plugIt.getTemplate(query, meta) if not templateContent: return (None, gen404(request, baseURI, 'template')) return (templateContent, None)
python
def get_template(request, query, meta, proxyMode): """Return (if needed) the template to use""" templateContent = None if not proxyMode: templateContent = plugIt.getTemplate(query, meta) if not templateContent: return (None, gen404(request, baseURI, 'template')) return (templateContent, None)
[ "def", "get_template", "(", "request", ",", "query", ",", "meta", ",", "proxyMode", ")", ":", "templateContent", "=", "None", "if", "not", "proxyMode", ":", "templateContent", "=", "plugIt", ".", "getTemplate", "(", "query", ",", "meta", ")", "if", "not", ...
Return (if needed) the template to use
[ "Return", "(", "if", "needed", ")", "the", "template", "to", "use" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L639-L651
ebu/PlugIt
plugit_proxy/views.py
get_current_orga
def get_current_orga(request, hproject, availableOrga): """Return the current orga to use""" # If nothing available return 404 if len(availableOrga) == 0: raise Http404 # Find the current orga currentOrgaId = request.session.get('plugit-orgapk-' + str(hproject.pk), None) # If we don't have a current one select the first available if currentOrgaId is None: (tmpOrga, _) = availableOrga[0] currentOrgaId = tmpOrga.pk else: # If the current Orga is not among the available ones reset to the first one availableOrgaIds = [o.pk for (o, r) in availableOrga] if currentOrgaId not in availableOrgaIds: (tmpOrga, _) = availableOrga[0] currentOrgaId = tmpOrga.pk from organizations.models import Organization realCurrentOrga = get_object_or_404(Organization, pk=currentOrgaId) return realCurrentOrga
python
def get_current_orga(request, hproject, availableOrga): """Return the current orga to use""" # If nothing available return 404 if len(availableOrga) == 0: raise Http404 # Find the current orga currentOrgaId = request.session.get('plugit-orgapk-' + str(hproject.pk), None) # If we don't have a current one select the first available if currentOrgaId is None: (tmpOrga, _) = availableOrga[0] currentOrgaId = tmpOrga.pk else: # If the current Orga is not among the available ones reset to the first one availableOrgaIds = [o.pk for (o, r) in availableOrga] if currentOrgaId not in availableOrgaIds: (tmpOrga, _) = availableOrga[0] currentOrgaId = tmpOrga.pk from organizations.models import Organization realCurrentOrga = get_object_or_404(Organization, pk=currentOrgaId) return realCurrentOrga
[ "def", "get_current_orga", "(", "request", ",", "hproject", ",", "availableOrga", ")", ":", "# If nothing available return 404", "if", "len", "(", "availableOrga", ")", "==", "0", ":", "raise", "Http404", "# Find the current orga", "currentOrgaId", "=", "request", "...
Return the current orga to use
[ "Return", "the", "current", "orga", "to", "use" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L654-L679
ebu/PlugIt
plugit_proxy/views.py
update_session
def update_session(request, session_to_set, hproPk): """Update the session with users-realted values""" for key, value in session_to_set.items(): request.session['plugit_' + str(hproPk) + '_' + key] = value
python
def update_session(request, session_to_set, hproPk): """Update the session with users-realted values""" for key, value in session_to_set.items(): request.session['plugit_' + str(hproPk) + '_' + key] = value
[ "def", "update_session", "(", "request", ",", "session_to_set", ",", "hproPk", ")", ":", "for", "key", ",", "value", "in", "session_to_set", ".", "items", "(", ")", ":", "request", ".", "session", "[", "'plugit_'", "+", "str", "(", "hproPk", ")", "+", ...
Update the session with users-realted values
[ "Update", "the", "session", "with", "users", "-", "realted", "values" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L682-L686
ebu/PlugIt
plugit_proxy/views.py
get_current_session
def get_current_session(request, hproPk): """Get the current session value""" retour = {} base_key = 'plugit_' + str(hproPk) + '_' for key, value in request.session.iteritems(): if key.startswith(base_key): retour[key[len(base_key):]] = value return retour
python
def get_current_session(request, hproPk): """Get the current session value""" retour = {} base_key = 'plugit_' + str(hproPk) + '_' for key, value in request.session.iteritems(): if key.startswith(base_key): retour[key[len(base_key):]] = value return retour
[ "def", "get_current_session", "(", "request", ",", "hproPk", ")", ":", "retour", "=", "{", "}", "base_key", "=", "'plugit_'", "+", "str", "(", "hproPk", ")", "+", "'_'", "for", "key", ",", "value", "in", "request", ".", "session", ".", "iteritems", "("...
Get the current session value
[ "Get", "the", "current", "session", "value" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L689-L700
ebu/PlugIt
plugit_proxy/views.py
main
def main(request, query, hproPk=None, returnMenuOnly=False): """ Main method called for main page""" if settings.PIAPI_STANDALONE: global plugIt, baseURI # Check if settings are ok if settings.PIAPI_ORGAMODE and settings.PIAPI_REALUSERS: return gen404(request, baseURI, "Configuration error. PIAPI_ORGAMODE and PIAPI_REALUSERS both set to True !") hproject = None else: (plugIt, baseURI, hproject) = getPlugItObject(hproPk) hproject.update_last_access(request.user) # Check for SSL Requirements and redirect to ssl if necessary if hproject and hproject.plugItRequiresSsl: if not request.is_secure(): secure_url = 'https://{0}{1}'.format(request.get_host(), request.get_full_path()) return HttpResponsePermanentRedirect(secure_url) orgaMode = None currentOrga = None plugItMenuAction = None availableOrga = [] # If standalone mode, change the current user and orga mode based on parameters if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: currentUserMode = request.session.get('plugit-standalone-usermode', 'ano') request.user = generate_user(mode=currentUserMode) orgaMode = settings.PIAPI_ORGAMODE currentOrga = SimpleOrga() currentOrga.name = request.session.get('plugit-standalone-organame', 'EBU') currentOrga.pk = request.session.get('plugit-standalone-orgapk', '-1') currentOrga.ebu_codops = request.session.get('plugit-standalone-orgacodops', 'zzebu') else: request.user.ebuio_member = request.user.is_staff request.user.ebuio_admin = request.user.is_superuser request.user.subscription_labels = _get_subscription_labels(request.user, hproject) proxyMode = settings.PIAPI_PROXYMODE plugItMenuAction = settings.PIAPI_PLUGITMENUACTION # TODO Add STANDALONE Orgas here # availableOrga.append((orga, isAdmin)) # Get meta, if not in proxy mode if not proxyMode: try: meta = plugIt.getMeta(query) except Exception as e: report_backend_error(request, e, 'meta', hproPk) meta = None if not meta: return gen404(request, baseURI, 'meta') else: meta = {} else: request.user.ebuio_member = hproject.isMemberRead(request.user) request.user.ebuio_admin = hproject.isMemberWrite(request.user) request.user.subscription_labels = _get_subscription_labels(request.user, hproject) orgaMode = hproject.plugItOrgaMode proxyMode = hproject.plugItProxyMode plugItMenuAction = hproject.plugItMenuAction # Get meta, if not in proxy mode if not proxyMode: try: meta = plugIt.getMeta(query) except Exception as e: report_backend_error(request, e, 'meta', hproPk) meta = None if not meta: return gen404(request, baseURI, 'meta') else: meta = {} if orgaMode: # List available orgas if request.user.is_authenticated(): # If orga limited only output the necessary orgas to which the user has access if hproject and hproject.plugItLimitOrgaJoinable: # Get List of Plugit Available Orgas first projectOrgaIds = hproject.plugItOrgaJoinable.order_by('name').values_list('pk', flat=True) for (orga, isAdmin) in request.user.getOrgas(distinct=True): if orga.pk in projectOrgaIds: availableOrga.append((orga, isAdmin)) else: availableOrga = request.user.getOrgas(distinct=True) if not availableOrga: # TODO HERE TO CHANGE PUBLIC if not meta.get('public'): # Page is not public, raise 403 return gen403(request, baseURI, 'no_orga_in_orgamode', hproject) else: # Build the current orga realCurrentOrga = get_current_orga(request, hproject, availableOrga) currentOrga = SimpleOrga() currentOrga.pk = realCurrentOrga.pk currentOrga.name = realCurrentOrga.name currentOrga.ebu_codops = realCurrentOrga.ebu_codops # Get rights request.user.ebuio_orga_member = realCurrentOrga.isMember(request.user) request.user.ebuio_orga_admin = realCurrentOrga.isOwner(request.user) cacheKey = get_cache_key(request, meta, orgaMode, currentOrga) # Check access rights error = check_rights_and_access(request, meta, hproject) if error: return error # Check cache (cache, menucache, context) = find_in_cache(cacheKey) if cache: return build_final_response(request, meta, cache, menucache, hproject, proxyMode, context) # Build parameters getParameters, postParameters, files = build_parameters(request, meta, orgaMode, currentOrga) # Bonus headers things_to_add = build_extra_headers(request, proxyMode, orgaMode, currentOrga) current_session = get_current_session(request, hproPk) # Do the action try: (data, session_to_set, headers_to_set) = plugIt.doAction(query, request.method, getParameters, postParameters, files, things_to_add, proxyMode=proxyMode, session=current_session) except Exception as e: report_backend_error(request, e, 'meta', hproPk) return gen500(request, baseURI) update_session(request, session_to_set, hproPk) # Handle special case (redirect, etc..) spe_cases = handle_special_cases(request, data, baseURI, meta) if spe_cases: for header, value in headers_to_set.items(): spe_cases[header] = value return spe_cases # Save data for proxyMode if proxyMode: rendered_data = data data = {} else: rendered_data = None # Get template (templateContent, templateError) = get_template(request, query, meta, proxyMode) if templateError: return templateError # Build the context context = build_context(request, data, hproject, orgaMode, currentOrga, availableOrga) # Render the result menu = None # Some page may not have a menu (result, menu) = render_data(context, templateContent, proxyMode, rendered_data, plugItMenuAction) # Cache the result for future uses if requested cache_if_needed(cacheKey, result, menu, context, meta) # Return menu only : ) if returnMenuOnly: return menu # Return the final response final = build_final_response(request, meta, result, menu, hproject, proxyMode, context) for header, value in headers_to_set.items(): final[header] = value return final
python
def main(request, query, hproPk=None, returnMenuOnly=False): """ Main method called for main page""" if settings.PIAPI_STANDALONE: global plugIt, baseURI # Check if settings are ok if settings.PIAPI_ORGAMODE and settings.PIAPI_REALUSERS: return gen404(request, baseURI, "Configuration error. PIAPI_ORGAMODE and PIAPI_REALUSERS both set to True !") hproject = None else: (plugIt, baseURI, hproject) = getPlugItObject(hproPk) hproject.update_last_access(request.user) # Check for SSL Requirements and redirect to ssl if necessary if hproject and hproject.plugItRequiresSsl: if not request.is_secure(): secure_url = 'https://{0}{1}'.format(request.get_host(), request.get_full_path()) return HttpResponsePermanentRedirect(secure_url) orgaMode = None currentOrga = None plugItMenuAction = None availableOrga = [] # If standalone mode, change the current user and orga mode based on parameters if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: currentUserMode = request.session.get('plugit-standalone-usermode', 'ano') request.user = generate_user(mode=currentUserMode) orgaMode = settings.PIAPI_ORGAMODE currentOrga = SimpleOrga() currentOrga.name = request.session.get('plugit-standalone-organame', 'EBU') currentOrga.pk = request.session.get('plugit-standalone-orgapk', '-1') currentOrga.ebu_codops = request.session.get('plugit-standalone-orgacodops', 'zzebu') else: request.user.ebuio_member = request.user.is_staff request.user.ebuio_admin = request.user.is_superuser request.user.subscription_labels = _get_subscription_labels(request.user, hproject) proxyMode = settings.PIAPI_PROXYMODE plugItMenuAction = settings.PIAPI_PLUGITMENUACTION # TODO Add STANDALONE Orgas here # availableOrga.append((orga, isAdmin)) # Get meta, if not in proxy mode if not proxyMode: try: meta = plugIt.getMeta(query) except Exception as e: report_backend_error(request, e, 'meta', hproPk) meta = None if not meta: return gen404(request, baseURI, 'meta') else: meta = {} else: request.user.ebuio_member = hproject.isMemberRead(request.user) request.user.ebuio_admin = hproject.isMemberWrite(request.user) request.user.subscription_labels = _get_subscription_labels(request.user, hproject) orgaMode = hproject.plugItOrgaMode proxyMode = hproject.plugItProxyMode plugItMenuAction = hproject.plugItMenuAction # Get meta, if not in proxy mode if not proxyMode: try: meta = plugIt.getMeta(query) except Exception as e: report_backend_error(request, e, 'meta', hproPk) meta = None if not meta: return gen404(request, baseURI, 'meta') else: meta = {} if orgaMode: # List available orgas if request.user.is_authenticated(): # If orga limited only output the necessary orgas to which the user has access if hproject and hproject.plugItLimitOrgaJoinable: # Get List of Plugit Available Orgas first projectOrgaIds = hproject.plugItOrgaJoinable.order_by('name').values_list('pk', flat=True) for (orga, isAdmin) in request.user.getOrgas(distinct=True): if orga.pk in projectOrgaIds: availableOrga.append((orga, isAdmin)) else: availableOrga = request.user.getOrgas(distinct=True) if not availableOrga: # TODO HERE TO CHANGE PUBLIC if not meta.get('public'): # Page is not public, raise 403 return gen403(request, baseURI, 'no_orga_in_orgamode', hproject) else: # Build the current orga realCurrentOrga = get_current_orga(request, hproject, availableOrga) currentOrga = SimpleOrga() currentOrga.pk = realCurrentOrga.pk currentOrga.name = realCurrentOrga.name currentOrga.ebu_codops = realCurrentOrga.ebu_codops # Get rights request.user.ebuio_orga_member = realCurrentOrga.isMember(request.user) request.user.ebuio_orga_admin = realCurrentOrga.isOwner(request.user) cacheKey = get_cache_key(request, meta, orgaMode, currentOrga) # Check access rights error = check_rights_and_access(request, meta, hproject) if error: return error # Check cache (cache, menucache, context) = find_in_cache(cacheKey) if cache: return build_final_response(request, meta, cache, menucache, hproject, proxyMode, context) # Build parameters getParameters, postParameters, files = build_parameters(request, meta, orgaMode, currentOrga) # Bonus headers things_to_add = build_extra_headers(request, proxyMode, orgaMode, currentOrga) current_session = get_current_session(request, hproPk) # Do the action try: (data, session_to_set, headers_to_set) = plugIt.doAction(query, request.method, getParameters, postParameters, files, things_to_add, proxyMode=proxyMode, session=current_session) except Exception as e: report_backend_error(request, e, 'meta', hproPk) return gen500(request, baseURI) update_session(request, session_to_set, hproPk) # Handle special case (redirect, etc..) spe_cases = handle_special_cases(request, data, baseURI, meta) if spe_cases: for header, value in headers_to_set.items(): spe_cases[header] = value return spe_cases # Save data for proxyMode if proxyMode: rendered_data = data data = {} else: rendered_data = None # Get template (templateContent, templateError) = get_template(request, query, meta, proxyMode) if templateError: return templateError # Build the context context = build_context(request, data, hproject, orgaMode, currentOrga, availableOrga) # Render the result menu = None # Some page may not have a menu (result, menu) = render_data(context, templateContent, proxyMode, rendered_data, plugItMenuAction) # Cache the result for future uses if requested cache_if_needed(cacheKey, result, menu, context, meta) # Return menu only : ) if returnMenuOnly: return menu # Return the final response final = build_final_response(request, meta, result, menu, hproject, proxyMode, context) for header, value in headers_to_set.items(): final[header] = value return final
[ "def", "main", "(", "request", ",", "query", ",", "hproPk", "=", "None", ",", "returnMenuOnly", "=", "False", ")", ":", "if", "settings", ".", "PIAPI_STANDALONE", ":", "global", "plugIt", ",", "baseURI", "# Check if settings are ok", "if", "settings", ".", "...
Main method called for main page
[ "Main", "method", "called", "for", "main", "page" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L703-L895
ebu/PlugIt
plugit_proxy/views.py
media
def media(request, path, hproPk=None): """Ask the server for a media and return it to the client browser. Forward cache headers""" if not settings.PIAPI_STANDALONE: (plugIt, baseURI, _) = getPlugItObject(hproPk) else: global plugIt, baseURI try: (media, contentType, cache_control) = plugIt.getMedia(path) except Exception as e: report_backend_error(request, e, 'meta', hproPk) return gen500(request, baseURI) if not media: # No media returned raise Http404 response = HttpResponse(media) response['Content-Type'] = contentType response['Content-Length'] = len(media) if cache_control: response['Cache-Control'] = cache_control return response
python
def media(request, path, hproPk=None): """Ask the server for a media and return it to the client browser. Forward cache headers""" if not settings.PIAPI_STANDALONE: (plugIt, baseURI, _) = getPlugItObject(hproPk) else: global plugIt, baseURI try: (media, contentType, cache_control) = plugIt.getMedia(path) except Exception as e: report_backend_error(request, e, 'meta', hproPk) return gen500(request, baseURI) if not media: # No media returned raise Http404 response = HttpResponse(media) response['Content-Type'] = contentType response['Content-Length'] = len(media) if cache_control: response['Cache-Control'] = cache_control return response
[ "def", "media", "(", "request", ",", "path", ",", "hproPk", "=", "None", ")", ":", "if", "not", "settings", ".", "PIAPI_STANDALONE", ":", "(", "plugIt", ",", "baseURI", ",", "_", ")", "=", "getPlugItObject", "(", "hproPk", ")", "else", ":", "global", ...
Ask the server for a media and return it to the client browser. Forward cache headers
[ "Ask", "the", "server", "for", "a", "media", "and", "return", "it", "to", "the", "client", "browser", ".", "Forward", "cache", "headers" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L909-L933
ebu/PlugIt
plugit_proxy/views.py
setUser
def setUser(request): """In standalone mode, change the current user""" if not settings.PIAPI_STANDALONE or settings.PIAPI_REALUSERS: raise Http404 request.session['plugit-standalone-usermode'] = request.GET.get('mode') return HttpResponse('')
python
def setUser(request): """In standalone mode, change the current user""" if not settings.PIAPI_STANDALONE or settings.PIAPI_REALUSERS: raise Http404 request.session['plugit-standalone-usermode'] = request.GET.get('mode') return HttpResponse('')
[ "def", "setUser", "(", "request", ")", ":", "if", "not", "settings", ".", "PIAPI_STANDALONE", "or", "settings", ".", "PIAPI_REALUSERS", ":", "raise", "Http404", "request", ".", "session", "[", "'plugit-standalone-usermode'", "]", "=", "request", ".", "GET", "....
In standalone mode, change the current user
[ "In", "standalone", "mode", "change", "the", "current", "user" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L936-L944
ebu/PlugIt
plugit_proxy/views.py
setOrga
def setOrga(request, hproPk=None): """Change the current orga""" if settings.PIAPI_STANDALONE: request.session['plugit-standalone-organame'] = request.GET.get('name') request.session['plugit-standalone-orgapk'] = request.GET.get('pk') else: (_, _, hproject) = getPlugItObject(hproPk) from organizations.models import Organization orga = get_object_or_404(Organization, pk=request.GET.get('orga')) if request.user.is_superuser or orga.isMember(request.user) or orga.isOwner(request.user): request.session['plugit-orgapk-' + str(hproject.pk)] = orga.pk return HttpResponse('')
python
def setOrga(request, hproPk=None): """Change the current orga""" if settings.PIAPI_STANDALONE: request.session['plugit-standalone-organame'] = request.GET.get('name') request.session['plugit-standalone-orgapk'] = request.GET.get('pk') else: (_, _, hproject) = getPlugItObject(hproPk) from organizations.models import Organization orga = get_object_or_404(Organization, pk=request.GET.get('orga')) if request.user.is_superuser or orga.isMember(request.user) or orga.isOwner(request.user): request.session['plugit-orgapk-' + str(hproject.pk)] = orga.pk return HttpResponse('')
[ "def", "setOrga", "(", "request", ",", "hproPk", "=", "None", ")", ":", "if", "settings", ".", "PIAPI_STANDALONE", ":", "request", ".", "session", "[", "'plugit-standalone-organame'", "]", "=", "request", ".", "GET", ".", "get", "(", "'name'", ")", "reques...
Change the current orga
[ "Change", "the", "current", "orga" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L947-L964
ebu/PlugIt
plugit_proxy/views.py
check_api_key
def check_api_key(request, key, hproPk): """Check if an API key is valid""" if settings.PIAPI_STANDALONE: return True (_, _, hproject) = getPlugItObject(hproPk) if not hproject: return False if hproject.plugItApiKey is None or hproject.plugItApiKey == '': return False return hproject.plugItApiKey == key
python
def check_api_key(request, key, hproPk): """Check if an API key is valid""" if settings.PIAPI_STANDALONE: return True (_, _, hproject) = getPlugItObject(hproPk) if not hproject: return False if hproject.plugItApiKey is None or hproject.plugItApiKey == '': return False return hproject.plugItApiKey == key
[ "def", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "if", "settings", ".", "PIAPI_STANDALONE", ":", "return", "True", "(", "_", ",", "_", ",", "hproject", ")", "=", "getPlugItObject", "(", "hproPk", ")", "if", "not", "hproject", ...
Check if an API key is valid
[ "Check", "if", "an", "API", "key", "is", "valid" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L967-L981
ebu/PlugIt
plugit_proxy/views.py
home
def home(request, hproPk): """ Route the request to runURI if defined otherwise go to plugIt """ if settings.PIAPI_STANDALONE: return main(request, '', hproPk) (plugIt, baseURI, hproject) = getPlugItObject(hproPk) if hproject.runURI: return HttpResponseRedirect(hproject.runURI) else: # Check if a custom url key is used if hasattr(hproject, 'plugItCustomUrlKey') and hproject.plugItCustomUrlKey: return HttpResponseRedirect(reverse('plugIt.views.main', args=(hproject.plugItCustomUrlKey, ''))) return main(request, '', hproPk)
python
def home(request, hproPk): """ Route the request to runURI if defined otherwise go to plugIt """ if settings.PIAPI_STANDALONE: return main(request, '', hproPk) (plugIt, baseURI, hproject) = getPlugItObject(hproPk) if hproject.runURI: return HttpResponseRedirect(hproject.runURI) else: # Check if a custom url key is used if hasattr(hproject, 'plugItCustomUrlKey') and hproject.plugItCustomUrlKey: return HttpResponseRedirect(reverse('plugIt.views.main', args=(hproject.plugItCustomUrlKey, ''))) return main(request, '', hproPk)
[ "def", "home", "(", "request", ",", "hproPk", ")", ":", "if", "settings", ".", "PIAPI_STANDALONE", ":", "return", "main", "(", "request", ",", "''", ",", "hproPk", ")", "(", "plugIt", ",", "baseURI", ",", "hproject", ")", "=", "getPlugItObject", "(", "...
Route the request to runURI if defined otherwise go to plugIt
[ "Route", "the", "request", "to", "runURI", "if", "defined", "otherwise", "go", "to", "plugIt" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L984-L998
ebu/PlugIt
plugit_proxy/views.py
api_home
def api_home(request, key=None, hproPk=None): """Show the home page for the API with all methods""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden return render_to_response('plugIt/api.html', {}, context_instance=RequestContext(request))
python
def api_home(request, key=None, hproPk=None): """Show the home page for the API with all methods""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden return render_to_response('plugIt/api.html', {}, context_instance=RequestContext(request))
[ "def", "api_home", "(", "request", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "return", "render_to_response", "(", "'p...
Show the home page for the API with all methods
[ "Show", "the", "home", "page", "for", "the", "API", "with", "all", "methods" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1001-L1007
ebu/PlugIt
plugit_proxy/views.py
api_user
def api_user(request, userPk, key=None, hproPk=None): """Return information about an user""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: user = generate_user(pk=userPk) if user is None: return HttpResponseNotFound() else: user = get_object_or_404(DUser, pk=userPk) hproject = None else: from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) (_, _, hproject) = getPlugItObject(hproPk) user.ebuio_member = hproject.isMemberRead(user) user.ebuio_admin = hproject.isMemberWrite(user) user.subscription_labels = _get_subscription_labels(user, hproject) retour = {} # Append properties for the user data for prop in settings.PIAPI_USERDATA: if hasattr(user, prop): retour[prop] = getattr(user, prop) retour['id'] = str(retour['pk']) # Append the users organisation and access levels orgas = {} if user: limitedOrgas = [] if hproject and hproject.plugItLimitOrgaJoinable: # Get List of Plugit Available Orgas first projectOrgaIds = hproject.plugItOrgaJoinable.order_by('name').values_list('pk', flat=True) for (orga, isAdmin) in user.getOrgas(distinct=True): if orga.pk in projectOrgaIds: limitedOrgas.append((orga, isAdmin)) elif hasattr(user, 'getOrgas'): limitedOrgas = user.getOrgas(distinct=True) # Create List orgas = [{'id': orga.pk, 'name': orga.name, 'codops': orga.ebu_codops, 'is_admin': isAdmin} for (orga, isAdmin) in limitedOrgas] retour['orgas'] = orgas return HttpResponse(json.dumps(retour), content_type="application/json")
python
def api_user(request, userPk, key=None, hproPk=None): """Return information about an user""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: user = generate_user(pk=userPk) if user is None: return HttpResponseNotFound() else: user = get_object_or_404(DUser, pk=userPk) hproject = None else: from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) (_, _, hproject) = getPlugItObject(hproPk) user.ebuio_member = hproject.isMemberRead(user) user.ebuio_admin = hproject.isMemberWrite(user) user.subscription_labels = _get_subscription_labels(user, hproject) retour = {} # Append properties for the user data for prop in settings.PIAPI_USERDATA: if hasattr(user, prop): retour[prop] = getattr(user, prop) retour['id'] = str(retour['pk']) # Append the users organisation and access levels orgas = {} if user: limitedOrgas = [] if hproject and hproject.plugItLimitOrgaJoinable: # Get List of Plugit Available Orgas first projectOrgaIds = hproject.plugItOrgaJoinable.order_by('name').values_list('pk', flat=True) for (orga, isAdmin) in user.getOrgas(distinct=True): if orga.pk in projectOrgaIds: limitedOrgas.append((orga, isAdmin)) elif hasattr(user, 'getOrgas'): limitedOrgas = user.getOrgas(distinct=True) # Create List orgas = [{'id': orga.pk, 'name': orga.name, 'codops': orga.ebu_codops, 'is_admin': isAdmin} for (orga, isAdmin) in limitedOrgas] retour['orgas'] = orgas return HttpResponse(json.dumps(retour), content_type="application/json")
[ "def", "api_user", "(", "request", ",", "userPk", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "if", "settings", ".", ...
Return information about an user
[ "Return", "information", "about", "an", "user" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1010-L1064
ebu/PlugIt
plugit_proxy/views.py
api_user_uuid
def api_user_uuid(request, userUuid, key=None, hproPk=None): """Return information about an user based on uuid""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, uuid=userUuid) (_, _, hproject) = getPlugItObject(hproPk) user.ebuio_member = hproject.isMemberRead(user) user.ebuio_admin = hproject.isMemberWrite(user) user.subscription_labels = _get_subscription_labels(user, hproject) return api_user(request, user.pk, key, hproPk)
python
def api_user_uuid(request, userUuid, key=None, hproPk=None): """Return information about an user based on uuid""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, uuid=userUuid) (_, _, hproject) = getPlugItObject(hproPk) user.ebuio_member = hproject.isMemberRead(user) user.ebuio_admin = hproject.isMemberWrite(user) user.subscription_labels = _get_subscription_labels(user, hproject) return api_user(request, user.pk, key, hproPk)
[ "def", "api_user_uuid", "(", "request", ",", "userUuid", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "# From UUID to Pk",...
Return information about an user based on uuid
[ "Return", "information", "about", "an", "user", "based", "on", "uuid" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1067-L1084
ebu/PlugIt
plugit_proxy/views.py
api_subscriptions
def api_subscriptions(request, userPk, key=None, hproPk=None): """Return information about an user based on uuid""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) (_, _, hproject) = getPlugItObject(hproPk) retour = user.getActiveSubscriptionLabels(hproject) return HttpResponse(json.dumps(retour), content_type="application/json")
python
def api_subscriptions(request, userPk, key=None, hproPk=None): """Return information about an user based on uuid""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) (_, _, hproject) = getPlugItObject(hproPk) retour = user.getActiveSubscriptionLabels(hproject) return HttpResponse(json.dumps(retour), content_type="application/json")
[ "def", "api_subscriptions", "(", "request", ",", "userPk", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "# From UUID to Pk...
Return information about an user based on uuid
[ "Return", "information", "about", "an", "user", "based", "on", "uuid" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1087-L1102
ebu/PlugIt
plugit_proxy/views.py
api_orga
def api_orga(request, orgaPk, key=None, hproPk=None): """Return information about an organization""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden retour = {} if settings.PIAPI_STANDALONE: retour['pk'] = orgaPk if orgaPk == "-1": retour['name'] = 'EBU' retour['codops'] = 'zzebu' if orgaPk == "-2": retour['name'] = 'RTS' retour['codops'] = 'chrts' if orgaPk == "-3": retour['name'] = 'BBC' retour['codops'] = 'gbbbc' if orgaPk == "-4": retour['name'] = 'CNN' retour['codops'] = 'uscnn' else: from organizations.models import Organization orga = get_object_or_404(Organization, pk=orgaPk) retour['pk'] = orga.pk retour['name'] = orga.name retour['codops'] = orga.ebu_codops return HttpResponse(json.dumps(retour), content_type="application/json")
python
def api_orga(request, orgaPk, key=None, hproPk=None): """Return information about an organization""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden retour = {} if settings.PIAPI_STANDALONE: retour['pk'] = orgaPk if orgaPk == "-1": retour['name'] = 'EBU' retour['codops'] = 'zzebu' if orgaPk == "-2": retour['name'] = 'RTS' retour['codops'] = 'chrts' if orgaPk == "-3": retour['name'] = 'BBC' retour['codops'] = 'gbbbc' if orgaPk == "-4": retour['name'] = 'CNN' retour['codops'] = 'uscnn' else: from organizations.models import Organization orga = get_object_or_404(Organization, pk=orgaPk) retour['pk'] = orga.pk retour['name'] = orga.name retour['codops'] = orga.ebu_codops return HttpResponse(json.dumps(retour), content_type="application/json")
[ "def", "api_orga", "(", "request", ",", "orgaPk", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "retour", "=", "{", "...
Return information about an organization
[ "Return", "information", "about", "an", "organization" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1105-L1137
ebu/PlugIt
plugit_proxy/views.py
api_get_project_members
def api_get_project_members(request, key=None, hproPk=True): """Return the list of project members""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: users = [generate_user(pk="-1"), generate_user(pk="-2"), generate_user(pk="-3")] else: users = DUser.object.all() else: (_, _, hproject) = getPlugItObject(hproPk) users = [] for u in hproject.getMembers(): u.ebuio_member = True u.ebuio_admin = hproject.isMemberWrite(u) u.subscription_labels = _get_subscription_labels(u, hproject) users.append(u) liste = [] for u in users: retour = {} for prop in settings.PIAPI_USERDATA: if hasattr(u, prop): retour[prop] = getattr(u, prop) retour['id'] = str(retour['pk']) liste.append(retour) return HttpResponse(json.dumps({'members': liste}), content_type="application/json")
python
def api_get_project_members(request, key=None, hproPk=True): """Return the list of project members""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: users = [generate_user(pk="-1"), generate_user(pk="-2"), generate_user(pk="-3")] else: users = DUser.object.all() else: (_, _, hproject) = getPlugItObject(hproPk) users = [] for u in hproject.getMembers(): u.ebuio_member = True u.ebuio_admin = hproject.isMemberWrite(u) u.subscription_labels = _get_subscription_labels(u, hproject) users.append(u) liste = [] for u in users: retour = {} for prop in settings.PIAPI_USERDATA: if hasattr(u, prop): retour[prop] = getattr(u, prop) retour['id'] = str(retour['pk']) liste.append(retour) return HttpResponse(json.dumps({'members': liste}), content_type="application/json")
[ "def", "api_get_project_members", "(", "request", ",", "key", "=", "None", ",", "hproPk", "=", "True", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "if", "settings", ".", "P...
Return the list of project members
[ "Return", "the", "list", "of", "project", "members" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1140-L1177
ebu/PlugIt
plugit_proxy/views.py
api_techgroup_list
def api_techgroup_list(request, key, hproPk): """Return the list of techgroup""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden from users.models import TechGroup retour = [{ 'uuid': t.uuid, 'uid': t.uid, 'name': t.name, } for t in TechGroup.objects.filter(is_enabled=True)] return HttpResponse(json.dumps(retour), content_type="application/json")
python
def api_techgroup_list(request, key, hproPk): """Return the list of techgroup""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden from users.models import TechGroup retour = [{ 'uuid': t.uuid, 'uid': t.uid, 'name': t.name, } for t in TechGroup.objects.filter(is_enabled=True)] return HttpResponse(json.dumps(retour), content_type="application/json")
[ "def", "api_techgroup_list", "(", "request", ",", "key", ",", "hproPk", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "from", "users", ".", "models", "import", "TechGroup", "re...
Return the list of techgroup
[ "Return", "the", "list", "of", "techgroup" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1180-L1194
ebu/PlugIt
plugit_proxy/views.py
api_user_techgroup_list
def api_user_techgroup_list(request, userPk, key, hproPk): """Return the list of techgroup of a user""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) retour = [t.uuid for t in user.techgroup_set.filter(is_enabled=True)] return HttpResponse(json.dumps(retour), content_type="application/json")
python
def api_user_techgroup_list(request, userPk, key, hproPk): """Return the list of techgroup of a user""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden # From UUID to Pk from users.models import TechUser user = get_object_or_404(TechUser, pk=userPk) retour = [t.uuid for t in user.techgroup_set.filter(is_enabled=True)] return HttpResponse(json.dumps(retour), content_type="application/json")
[ "def", "api_user_techgroup_list", "(", "request", ",", "userPk", ",", "key", ",", "hproPk", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "# From UUID to Pk", "from", "users", "....
Return the list of techgroup of a user
[ "Return", "the", "list", "of", "techgroup", "of", "a", "user" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1197-L1210
ebu/PlugIt
plugit_proxy/views.py
generic_send_mail
def generic_send_mail(sender, dests, subject, message, key, origin='', html_message=False): """Generic mail sending function""" # If no EBUIO Mail settings have been set, then no e-mail shall be sent if settings.EBUIO_MAIL_SECRET_KEY and settings.EBUIO_MAIL_SECRET_HASH: headers = {} if key: from Crypto.Cipher import AES hash_key = hashlib.sha512(key + settings.EBUIO_MAIL_SECRET_HASH).hexdigest()[30:42] encrypter = AES.new(((settings.EBUIO_MAIL_SECRET_KEY) * 32)[:32], AES.MODE_CFB, '87447JEUPEBU4hR!') encrypted_key = encrypter.encrypt(hash_key + ':' + key) base64_key = base64.urlsafe_b64encode(encrypted_key) headers = {'Reply-To': settings.MAIL_SENDER.replace('@', '+' + base64_key + '@')} msg = EmailMessage(subject, message, sender, dests, headers=headers) if html_message: msg.content_subtype = "html" # Main content is now text/html msg.send(fail_silently=False) try: from main.models import MailSend MailSend(dest=','.join(dests), subject=subject, sender=sender, message=message, origin=origin).save() except ImportError: pass else: logger.debug( "E-Mail notification not sent, since no EBUIO_MAIL_SECRET_KEY and EBUIO_MAIL_SECRET_HASH set in settingsLocal.py.")
python
def generic_send_mail(sender, dests, subject, message, key, origin='', html_message=False): """Generic mail sending function""" # If no EBUIO Mail settings have been set, then no e-mail shall be sent if settings.EBUIO_MAIL_SECRET_KEY and settings.EBUIO_MAIL_SECRET_HASH: headers = {} if key: from Crypto.Cipher import AES hash_key = hashlib.sha512(key + settings.EBUIO_MAIL_SECRET_HASH).hexdigest()[30:42] encrypter = AES.new(((settings.EBUIO_MAIL_SECRET_KEY) * 32)[:32], AES.MODE_CFB, '87447JEUPEBU4hR!') encrypted_key = encrypter.encrypt(hash_key + ':' + key) base64_key = base64.urlsafe_b64encode(encrypted_key) headers = {'Reply-To': settings.MAIL_SENDER.replace('@', '+' + base64_key + '@')} msg = EmailMessage(subject, message, sender, dests, headers=headers) if html_message: msg.content_subtype = "html" # Main content is now text/html msg.send(fail_silently=False) try: from main.models import MailSend MailSend(dest=','.join(dests), subject=subject, sender=sender, message=message, origin=origin).save() except ImportError: pass else: logger.debug( "E-Mail notification not sent, since no EBUIO_MAIL_SECRET_KEY and EBUIO_MAIL_SECRET_HASH set in settingsLocal.py.")
[ "def", "generic_send_mail", "(", "sender", ",", "dests", ",", "subject", ",", "message", ",", "key", ",", "origin", "=", "''", ",", "html_message", "=", "False", ")", ":", "# If no EBUIO Mail settings have been set, then no e-mail shall be sent", "if", "settings", "...
Generic mail sending function
[ "Generic", "mail", "sending", "function" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1213-L1246
ebu/PlugIt
plugit_proxy/views.py
api_send_mail
def api_send_mail(request, key=None, hproPk=None): """Send a email. Posts parameters are used""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden sender = request.POST.get('sender', settings.MAIL_SENDER) dests = request.POST.getlist('dests') subject = request.POST['subject'] message = request.POST['message'] html_message = request.POST.get('html_message') if html_message and html_message.lower() == 'false': html_message = False if 'response_id' in request.POST: key = hproPk + ':' + request.POST['response_id'] else: key = None generic_send_mail(sender, dests, subject, message, key, 'PlugIt API (%s)' % (hproPk or 'StandAlone',), html_message) return HttpResponse(json.dumps({}), content_type="application/json")
python
def api_send_mail(request, key=None, hproPk=None): """Send a email. Posts parameters are used""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden sender = request.POST.get('sender', settings.MAIL_SENDER) dests = request.POST.getlist('dests') subject = request.POST['subject'] message = request.POST['message'] html_message = request.POST.get('html_message') if html_message and html_message.lower() == 'false': html_message = False if 'response_id' in request.POST: key = hproPk + ':' + request.POST['response_id'] else: key = None generic_send_mail(sender, dests, subject, message, key, 'PlugIt API (%s)' % (hproPk or 'StandAlone',), html_message) return HttpResponse(json.dumps({}), content_type="application/json")
[ "def", "api_send_mail", "(", "request", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "sender", "=", "request", ".", "P...
Send a email. Posts parameters are used
[ "Send", "a", "email", ".", "Posts", "parameters", "are", "used" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1250-L1272
ebu/PlugIt
plugit_proxy/views.py
api_orgas
def api_orgas(request, key=None, hproPk=None): """Return the list of organizations pk""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden list_orgas = [] if settings.PIAPI_STANDALONE: list_orgas = [{'id': -1, 'name': 'EBU', 'codops': 'ZZEBU'}, {'id': -2, 'name': 'RTS', 'codops': 'CHRTS'}, {'id': -3, 'name': 'BBC', 'codops': 'GBEBU'}, {'id': -4, 'name': 'CNN', 'codops': 'USCNN'}] else: from organizations.models import Organization (_, _, hproject) = getPlugItObject(hproPk) if hproject and hproject.plugItLimitOrgaJoinable: orgas = hproject.plugItOrgaJoinable.order_by('name').all() else: orgas = Organization.objects.order_by('name').all() list_orgas = [{'id': orga.pk, 'name': orga.name, 'codops': orga.ebu_codops} for orga in orgas] retour = {'data': list_orgas} return HttpResponse(json.dumps(retour), content_type="application/json")
python
def api_orgas(request, key=None, hproPk=None): """Return the list of organizations pk""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden list_orgas = [] if settings.PIAPI_STANDALONE: list_orgas = [{'id': -1, 'name': 'EBU', 'codops': 'ZZEBU'}, {'id': -2, 'name': 'RTS', 'codops': 'CHRTS'}, {'id': -3, 'name': 'BBC', 'codops': 'GBEBU'}, {'id': -4, 'name': 'CNN', 'codops': 'USCNN'}] else: from organizations.models import Organization (_, _, hproject) = getPlugItObject(hproPk) if hproject and hproject.plugItLimitOrgaJoinable: orgas = hproject.plugItOrgaJoinable.order_by('name').all() else: orgas = Organization.objects.order_by('name').all() list_orgas = [{'id': orga.pk, 'name': orga.name, 'codops': orga.ebu_codops} for orga in orgas] retour = {'data': list_orgas} return HttpResponse(json.dumps(retour), content_type="application/json")
[ "def", "api_orgas", "(", "request", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "list_orgas", "=", "[", "]", "if", ...
Return the list of organizations pk
[ "Return", "the", "list", "of", "organizations", "pk" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1275-L1303
ebu/PlugIt
plugit_proxy/views.py
api_ebuio_forum
def api_ebuio_forum(request, key=None, hproPk=None): """Create a topic on the forum of the ioproject. EBUIo only !""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_type="application/json") (_, _, hproject) = getPlugItObject(hproPk) error = '' subject = request.POST.get('subject') author_pk = request.POST.get('author') message = request.POST.get('message') tags = request.POST.get('tags', '') if not subject: error = 'no-subject' if not author_pk: error = 'no-author' else: try: from users.models import TechUser author = TechUser.objects.get(pk=author_pk) except TechUser.DoesNotExist: error = 'author-no-found' if not message: error = 'no-message' if error: return HttpResponse(json.dumps({'error': error}), content_type="application/json") # Create the topic from discuss.models import Post, PostTag if tags: real_tags = [] for tag in tags.split(','): (pt, __) = PostTag.objects.get_or_create(tag=tag) real_tags.append(str(pt.pk)) tags = ','.join(real_tags) post = Post(content_object=hproject, who=author, score=0, title=subject, text=message) post.save() from app.tags_utils import update_object_tag update_object_tag(post, PostTag, tags) post.send_email() # Return the URL return HttpResponse(json.dumps({'result': 'ok', 'url': settings.EBUIO_BASE_URL + reverse('hprojects.views.forum_topic', args=(hproject.pk, post.pk))}), content_type="application/json")
python
def api_ebuio_forum(request, key=None, hproPk=None): """Create a topic on the forum of the ioproject. EBUIo only !""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_type="application/json") (_, _, hproject) = getPlugItObject(hproPk) error = '' subject = request.POST.get('subject') author_pk = request.POST.get('author') message = request.POST.get('message') tags = request.POST.get('tags', '') if not subject: error = 'no-subject' if not author_pk: error = 'no-author' else: try: from users.models import TechUser author = TechUser.objects.get(pk=author_pk) except TechUser.DoesNotExist: error = 'author-no-found' if not message: error = 'no-message' if error: return HttpResponse(json.dumps({'error': error}), content_type="application/json") # Create the topic from discuss.models import Post, PostTag if tags: real_tags = [] for tag in tags.split(','): (pt, __) = PostTag.objects.get_or_create(tag=tag) real_tags.append(str(pt.pk)) tags = ','.join(real_tags) post = Post(content_object=hproject, who=author, score=0, title=subject, text=message) post.save() from app.tags_utils import update_object_tag update_object_tag(post, PostTag, tags) post.send_email() # Return the URL return HttpResponse(json.dumps({'result': 'ok', 'url': settings.EBUIO_BASE_URL + reverse('hprojects.views.forum_topic', args=(hproject.pk, post.pk))}), content_type="application/json")
[ "def", "api_ebuio_forum", "(", "request", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "if", "settings", ".", "PIAPI_STA...
Create a topic on the forum of the ioproject. EBUIo only !
[ "Create", "a", "topic", "on", "the", "forum", "of", "the", "ioproject", ".", "EBUIo", "only", "!" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1307-L1367
ebu/PlugIt
plugit_proxy/views.py
api_ebuio_forum_get_topics_by_tag_for_user
def api_ebuio_forum_get_topics_by_tag_for_user(request, key=None, hproPk=None, tag=None, userPk=None): """Return the list of topics using the tag pk""" # Check API key (in order to be sure that we have a valid one and that's correspond to the project if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_type="application/json") # We get the plugit object representing the project (_, _, hproject) = getPlugItObject(hproPk) # We get the user and we check his rights author_pk = request.GET.get('u') if author_pk and author_pk.isdigit(): try: from users.models import TechUser user = TechUser.objects.get(pk=author_pk) except TechUser.DoesNotExist: error = 'user-no-found' user = generate_user(mode='ano') else: user = generate_user(mode='ano') if not hproject.discuss_can_display_posts(user): return HttpResponseForbidden # Verify the existence of the tag if not tag: raise Http404 # We get the posts (only topics ones-the parent) related to the project and to the tag. # We dont' take the deleted ones. from discuss.models import Post posts = Post.objects.filter(is_deleted=False).filter(object_id=hproPk).filter(tags__tag=tag).order_by('-when') # We convert the posts list to json posts_json = [ {'id': post.id, 'link': post.discuss_get_forum_topic_link(), 'subject': post.title, 'author': post.who_id, 'when': post.when.strftime('%a, %d %b %Y %H:%M GMT'), 'score': post.score, 'replies_number': post.direct_subposts_size()} for post in posts] return HttpResponse(json.dumps({'data': posts_json}), content_type="application/json")
python
def api_ebuio_forum_get_topics_by_tag_for_user(request, key=None, hproPk=None, tag=None, userPk=None): """Return the list of topics using the tag pk""" # Check API key (in order to be sure that we have a valid one and that's correspond to the project if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_type="application/json") # We get the plugit object representing the project (_, _, hproject) = getPlugItObject(hproPk) # We get the user and we check his rights author_pk = request.GET.get('u') if author_pk and author_pk.isdigit(): try: from users.models import TechUser user = TechUser.objects.get(pk=author_pk) except TechUser.DoesNotExist: error = 'user-no-found' user = generate_user(mode='ano') else: user = generate_user(mode='ano') if not hproject.discuss_can_display_posts(user): return HttpResponseForbidden # Verify the existence of the tag if not tag: raise Http404 # We get the posts (only topics ones-the parent) related to the project and to the tag. # We dont' take the deleted ones. from discuss.models import Post posts = Post.objects.filter(is_deleted=False).filter(object_id=hproPk).filter(tags__tag=tag).order_by('-when') # We convert the posts list to json posts_json = [ {'id': post.id, 'link': post.discuss_get_forum_topic_link(), 'subject': post.title, 'author': post.who_id, 'when': post.when.strftime('%a, %d %b %Y %H:%M GMT'), 'score': post.score, 'replies_number': post.direct_subposts_size()} for post in posts] return HttpResponse(json.dumps({'data': posts_json}), content_type="application/json")
[ "def", "api_ebuio_forum_get_topics_by_tag_for_user", "(", "request", ",", "key", "=", "None", ",", "hproPk", "=", "None", ",", "tag", "=", "None", ",", "userPk", "=", "None", ")", ":", "# Check API key (in order to be sure that we have a valid one and that's correspond to...
Return the list of topics using the tag pk
[ "Return", "the", "list", "of", "topics", "using", "the", "tag", "pk" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L1370-L1415
snowball-one/addressify
addressify/client.py
Client.auto_complete
def auto_complete(self, term, state=None, postcode=None, max_results=None): """ Gets a list of addresses that begin with the given term. """ self._validate_state(state) params = {"term": term, "state": state, "postcode": postcode, "max_results": max_results or self.max_results} return self._make_request('/address/autoComplete', params)
python
def auto_complete(self, term, state=None, postcode=None, max_results=None): """ Gets a list of addresses that begin with the given term. """ self._validate_state(state) params = {"term": term, "state": state, "postcode": postcode, "max_results": max_results or self.max_results} return self._make_request('/address/autoComplete', params)
[ "def", "auto_complete", "(", "self", ",", "term", ",", "state", "=", "None", ",", "postcode", "=", "None", ",", "max_results", "=", "None", ")", ":", "self", ".", "_validate_state", "(", "state", ")", "params", "=", "{", "\"term\"", ":", "term", ",", ...
Gets a list of addresses that begin with the given term.
[ "Gets", "a", "list", "of", "addresses", "that", "begin", "with", "the", "given", "term", "." ]
train
https://github.com/snowball-one/addressify/blob/3b2c7b5eb5c1c21747ce1ce7a29a31016ab9a70f/addressify/client.py#L36-L43
snowball-one/addressify
addressify/client.py
Client.parse_address
def parse_address(self, address_line): """ Parses the given address into it's individual address fields. """ params = {"term": address_line} json = self._make_request('/address/getParsedAddress', params) if json is None: return None return Address.from_json(json)
python
def parse_address(self, address_line): """ Parses the given address into it's individual address fields. """ params = {"term": address_line} json = self._make_request('/address/getParsedAddress', params) if json is None: return None return Address.from_json(json)
[ "def", "parse_address", "(", "self", ",", "address_line", ")", ":", "params", "=", "{", "\"term\"", ":", "address_line", "}", "json", "=", "self", ".", "_make_request", "(", "'/address/getParsedAddress'", ",", "params", ")", "if", "json", "is", "None", ":", ...
Parses the given address into it's individual address fields.
[ "Parses", "the", "given", "address", "into", "it", "s", "individual", "address", "fields", "." ]
train
https://github.com/snowball-one/addressify/blob/3b2c7b5eb5c1c21747ce1ce7a29a31016ab9a70f/addressify/client.py#L91-L99
snowball-one/addressify
addressify/client.py
Client.similar
def similar(self, address_line, max_results=None): """ Gets a list of valid addresses that are similar to the given term, can be used to match invalid addresses to valid addresses. """ params = {"term": address_line, "max_results": max_results or self.max_results} return self._make_request('/address/getSimilar', params)
python
def similar(self, address_line, max_results=None): """ Gets a list of valid addresses that are similar to the given term, can be used to match invalid addresses to valid addresses. """ params = {"term": address_line, "max_results": max_results or self.max_results} return self._make_request('/address/getSimilar', params)
[ "def", "similar", "(", "self", ",", "address_line", ",", "max_results", "=", "None", ")", ":", "params", "=", "{", "\"term\"", ":", "address_line", ",", "\"max_results\"", ":", "max_results", "or", "self", ".", "max_results", "}", "return", "self", ".", "_...
Gets a list of valid addresses that are similar to the given term, can be used to match invalid addresses to valid addresses.
[ "Gets", "a", "list", "of", "valid", "addresses", "that", "are", "similar", "to", "the", "given", "term", "can", "be", "used", "to", "match", "invalid", "addresses", "to", "valid", "addresses", "." ]
train
https://github.com/snowball-one/addressify/blob/3b2c7b5eb5c1c21747ce1ce7a29a31016ab9a70f/addressify/client.py#L101-L108
Gjum/agarnet
agarnet/client.py
Client.connect
def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True
python
def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True
[ "def", "connect", "(", "self", ",", "address", ",", "token", "=", "None", ")", ":", "if", "self", ".", "connected", ":", "self", ".", "subscriber", ".", "on_connect_error", "(", "'Already connected to \"%s\"'", "%", "self", ".", "address", ")", "return", "...
Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not
[ "Connect", "the", "underlying", "websocket", "to", "the", "address", "send", "a", "handshake", "and", "optionally", "a", "token", "packet", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L83-L126
Gjum/agarnet
agarnet/client.py
Client.disconnect
def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed()
python
def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed()
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "ws", ".", "close", "(", ")", "self", ".", "ingame", "=", "False", "self", ".", "subscriber", ".", "on_sock_closed", "(", ")" ]
Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed.
[ "Disconnect", "from", "server", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L128-L136
Gjum/agarnet
agarnet/client.py
Client.listen
def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect()
python
def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect()
[ "def", "listen", "(", "self", ")", ":", "import", "select", "while", "self", ".", "connected", ":", "r", ",", "w", ",", "e", "=", "select", ".", "select", "(", "(", "self", ".", "ws", ".", "sock", ",", ")", ",", "(", ")", ",", "(", ")", ")", ...
Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events.
[ "Set", "up", "a", "quick", "connection", ".", "Returns", "on", "disconnect", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L139-L153
Gjum/agarnet
agarnet/client.py
Client.on_message
def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name
python
def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name
[ "def", "on_message", "(", "self", ",", "msg", "=", "None", ")", ":", "if", "msg", "is", "None", ":", "try", ":", "msg", "=", "self", ".", "ws", ".", "recv", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "subscriber", ".", "on_mess...
Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket.
[ "Poll", "the", "websocket", "for", "a", "new", "packet", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L155-L200
Gjum/agarnet
agarnet/client.py
Client.send_struct
def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data))
python
def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data))
[ "def", "send_struct", "(", "self", ",", "fmt", ",", "*", "data", ")", ":", "if", "self", ".", "connected", ":", "self", ".", "ws", ".", "send", "(", "struct", ".", "pack", "(", "fmt", ",", "*", "data", ")", ")" ]
If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods.
[ "If", "connected", "formats", "the", "data", "to", "a", "struct", "and", "sends", "it", "to", "the", "server", ".", "Used", "internally", "by", "all", "other", "send_", "*", "()", "methods", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L363-L369
Gjum/agarnet
agarnet/client.py
Client.send_token
def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token
python
def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token
[ "def", "send_token", "(", "self", ",", "token", ")", ":", "self", ".", "send_struct", "(", "'<B%iB'", "%", "len", "(", "token", ")", ",", "80", ",", "*", "map", "(", "ord", ",", "token", ")", ")", "self", ".", "server_token", "=", "token" ]
Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet.
[ "Used", "by", "Client", ".", "connect", "()", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L382-L392
Gjum/agarnet
agarnet/client.py
Client.send_facebook
def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token
python
def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token
[ "def", "send_facebook", "(", "self", ",", "token", ")", ":", "self", ".", "send_struct", "(", "'<B%iB'", "%", "len", "(", "token", ")", ",", "81", ",", "*", "map", "(", "ord", ",", "token", ")", ")", "self", ".", "facebook_token", "=", "token" ]
Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game.
[ "Tells", "the", "server", "which", "Facebook", "account", "this", "client", "uses", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L394-L404
Gjum/agarnet
agarnet/client.py
Client.send_respawn
def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick))
python
def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick))
[ "def", "send_respawn", "(", "self", ")", ":", "nick", "=", "self", ".", "player", ".", "nick", "self", ".", "send_struct", "(", "'<B%iH'", "%", "len", "(", "nick", ")", ",", "0", ",", "*", "map", "(", "ord", ",", "nick", ")", ")" ]
Respawns the player.
[ "Respawns", "the", "player", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L406-L411
Gjum/agarnet
agarnet/client.py
Client.send_target
def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid)
python
def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid)
[ "def", "send_target", "(", "self", ",", "x", ",", "y", ",", "cid", "=", "0", ")", ":", "self", ".", "send_struct", "(", "'<BiiI'", ",", "16", ",", "int", "(", "x", ")", ",", "int", "(", "y", ")", ",", "cid", ")" ]
Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client.
[ "Sets", "the", "target", "position", "of", "all", "cells", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L413-L427
Gjum/agarnet
agarnet/client.py
Client.send_explode
def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
python
def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
[ "def", "send_explode", "(", "self", ")", ":", "self", ".", "send_struct", "(", "'<B'", ",", "20", ")", "self", ".", "player", ".", "own_ids", ".", "clear", "(", ")", "self", ".", "player", ".", "cells_changed", "(", ")", "self", ".", "ingame", "=", ...
In earlier versions of the game, sending this caused your cells to split into lots of small cells and die.
[ "In", "earlier", "versions", "of", "the", "game", "sending", "this", "caused", "your", "cells", "to", "split", "into", "lots", "of", "small", "cells", "and", "die", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L461-L470
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/time_slide.py
get_time_slide_id
def get_time_slide_id(xmldoc, time_slide, create_new = None, superset_ok = False, nonunique_ok = False): """ Return the time_slide_id corresponding to the offset vector described by time_slide, a dictionary of instrument/offset pairs. Example: >>> get_time_slide_id(xmldoc, {"H1": 0, "L1": 0}) 'time_slide:time_slide_id:10' This function is a wrapper around the .get_time_slide_id() method of the pycbc_glue.ligolw.lsctables.TimeSlideTable class. See the documentation for that class for the meaning of the create_new, superset_ok and nonunique_ok keyword arguments. This function requires the document to contain exactly one time_slide table. If the document does not contain exactly one time_slide table then ValueError is raised, unless the optional create_new argument is not None. In that case a new table is created. This effect of the create_new argument is in addition to the affects described by the TimeSlideTable class. """ try: tisitable = lsctables.TimeSlideTable.get_table(xmldoc) except ValueError: # table not found if create_new is None: raise tisitable = lsctables.New(lsctables.TimeSlideTable) xmldoc.childNodes[0].appendChild(tisitable) # make sure the next_id attribute is correct tisitable.sync_next_id() # get the id return tisitable.get_time_slide_id(time_slide, create_new = create_new, superset_ok = superset_ok, nonunique_ok = nonunique_ok)
python
def get_time_slide_id(xmldoc, time_slide, create_new = None, superset_ok = False, nonunique_ok = False): """ Return the time_slide_id corresponding to the offset vector described by time_slide, a dictionary of instrument/offset pairs. Example: >>> get_time_slide_id(xmldoc, {"H1": 0, "L1": 0}) 'time_slide:time_slide_id:10' This function is a wrapper around the .get_time_slide_id() method of the pycbc_glue.ligolw.lsctables.TimeSlideTable class. See the documentation for that class for the meaning of the create_new, superset_ok and nonunique_ok keyword arguments. This function requires the document to contain exactly one time_slide table. If the document does not contain exactly one time_slide table then ValueError is raised, unless the optional create_new argument is not None. In that case a new table is created. This effect of the create_new argument is in addition to the affects described by the TimeSlideTable class. """ try: tisitable = lsctables.TimeSlideTable.get_table(xmldoc) except ValueError: # table not found if create_new is None: raise tisitable = lsctables.New(lsctables.TimeSlideTable) xmldoc.childNodes[0].appendChild(tisitable) # make sure the next_id attribute is correct tisitable.sync_next_id() # get the id return tisitable.get_time_slide_id(time_slide, create_new = create_new, superset_ok = superset_ok, nonunique_ok = nonunique_ok)
[ "def", "get_time_slide_id", "(", "xmldoc", ",", "time_slide", ",", "create_new", "=", "None", ",", "superset_ok", "=", "False", ",", "nonunique_ok", "=", "False", ")", ":", "try", ":", "tisitable", "=", "lsctables", ".", "TimeSlideTable", ".", "get_table", "...
Return the time_slide_id corresponding to the offset vector described by time_slide, a dictionary of instrument/offset pairs. Example: >>> get_time_slide_id(xmldoc, {"H1": 0, "L1": 0}) 'time_slide:time_slide_id:10' This function is a wrapper around the .get_time_slide_id() method of the pycbc_glue.ligolw.lsctables.TimeSlideTable class. See the documentation for that class for the meaning of the create_new, superset_ok and nonunique_ok keyword arguments. This function requires the document to contain exactly one time_slide table. If the document does not contain exactly one time_slide table then ValueError is raised, unless the optional create_new argument is not None. In that case a new table is created. This effect of the create_new argument is in addition to the affects described by the TimeSlideTable class.
[ "Return", "the", "time_slide_id", "corresponding", "to", "the", "offset", "vector", "described", "by", "time_slide", "a", "dictionary", "of", "instrument", "/", "offset", "pairs", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/time_slide.py#L46-L79
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/time_slide.py
time_slides_vacuum
def time_slides_vacuum(time_slides, verbose = False): """ Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return a mapping indicating time slide equivalences. This can be used to delete redundant time slides from a time slide table, and then also used via the applyKeyMapping() method of pycbc_glue.ligolw.table.Table instances to update cross references (for example in the coinc_event table). Example: >>> slides = {"time_slide_id:0": {"H1": 0, "H2": 0}, "time_slide_id:1": {"H1": 10, "H2": 10}, "time_slide_id:2": {"H1": 0, "H2": 10}} >>> time_slides_vacuum(slides) {'time_slide_id:1': 'time_slide_id:0'} indicating that time_slide_id:1 describes a time slide that is equivalent to time_slide_id:0. The calling code could use this information to delete time_slide_id:1 from the time_slide table, and replace references to that ID in other tables with references to time_slide_id:0. """ # convert offsets to deltas time_slides = dict((time_slide_id, offsetvect.deltas) for time_slide_id, offsetvect in time_slides.items()) if verbose: progressbar = ProgressBar(max = len(time_slides)) else: progressbar = None # old --> new mapping mapping = {} # while there are time slide offset dictionaries remaining while time_slides: # pick an ID/offset dictionary pair at random id1, deltas1 = time_slides.popitem() # for every other ID/offset dictionary pair in the time # slides ids_to_delete = [] for id2, deltas2 in time_slides.items(): # if the relative offset dictionaries are # equivalent record in the old --> new mapping if deltas2 == deltas1: mapping[id2] = id1 ids_to_delete.append(id2) for id2 in ids_to_delete: time_slides.pop(id2) if progressbar is not None: progressbar.update(progressbar.max - len(time_slides)) # done del progressbar return mapping
python
def time_slides_vacuum(time_slides, verbose = False): """ Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return a mapping indicating time slide equivalences. This can be used to delete redundant time slides from a time slide table, and then also used via the applyKeyMapping() method of pycbc_glue.ligolw.table.Table instances to update cross references (for example in the coinc_event table). Example: >>> slides = {"time_slide_id:0": {"H1": 0, "H2": 0}, "time_slide_id:1": {"H1": 10, "H2": 10}, "time_slide_id:2": {"H1": 0, "H2": 10}} >>> time_slides_vacuum(slides) {'time_slide_id:1': 'time_slide_id:0'} indicating that time_slide_id:1 describes a time slide that is equivalent to time_slide_id:0. The calling code could use this information to delete time_slide_id:1 from the time_slide table, and replace references to that ID in other tables with references to time_slide_id:0. """ # convert offsets to deltas time_slides = dict((time_slide_id, offsetvect.deltas) for time_slide_id, offsetvect in time_slides.items()) if verbose: progressbar = ProgressBar(max = len(time_slides)) else: progressbar = None # old --> new mapping mapping = {} # while there are time slide offset dictionaries remaining while time_slides: # pick an ID/offset dictionary pair at random id1, deltas1 = time_slides.popitem() # for every other ID/offset dictionary pair in the time # slides ids_to_delete = [] for id2, deltas2 in time_slides.items(): # if the relative offset dictionaries are # equivalent record in the old --> new mapping if deltas2 == deltas1: mapping[id2] = id1 ids_to_delete.append(id2) for id2 in ids_to_delete: time_slides.pop(id2) if progressbar is not None: progressbar.update(progressbar.max - len(time_slides)) # done del progressbar return mapping
[ "def", "time_slides_vacuum", "(", "time_slides", ",", "verbose", "=", "False", ")", ":", "# convert offsets to deltas", "time_slides", "=", "dict", "(", "(", "time_slide_id", ",", "offsetvect", ".", "deltas", ")", "for", "time_slide_id", ",", "offsetvect", "in", ...
Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return a mapping indicating time slide equivalences. This can be used to delete redundant time slides from a time slide table, and then also used via the applyKeyMapping() method of pycbc_glue.ligolw.table.Table instances to update cross references (for example in the coinc_event table). Example: >>> slides = {"time_slide_id:0": {"H1": 0, "H2": 0}, "time_slide_id:1": {"H1": 10, "H2": 10}, "time_slide_id:2": {"H1": 0, "H2": 10}} >>> time_slides_vacuum(slides) {'time_slide_id:1': 'time_slide_id:0'} indicating that time_slide_id:1 describes a time slide that is equivalent to time_slide_id:0. The calling code could use this information to delete time_slide_id:1 from the time_slide table, and replace references to that ID in other tables with references to time_slide_id:0.
[ "Given", "a", "dictionary", "mapping", "time", "slide", "IDs", "to", "instrument", "--", ">", "offset", "mappings", "for", "example", "as", "returned", "by", "the", "as_dict", "()", "method", "of", "the", "TimeSlideTable", "class", "in", "pycbc_glue", ".", "...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/time_slide.py#L91-L144
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/time_slide.py
time_slide_list_merge
def time_slide_list_merge(slides1, slides2): """ Merges two lists of offset dictionaries into a single list with no duplicate (equivalent) time slides. """ deltas1 = set(frozenset(offsetvect1.deltas.items()) for offsetvect1 in slides1) return slides1 + [offsetvect2 for offsetvect2 in slides2 if frozenset(offsetvect2.deltas.items()) not in deltas1]
python
def time_slide_list_merge(slides1, slides2): """ Merges two lists of offset dictionaries into a single list with no duplicate (equivalent) time slides. """ deltas1 = set(frozenset(offsetvect1.deltas.items()) for offsetvect1 in slides1) return slides1 + [offsetvect2 for offsetvect2 in slides2 if frozenset(offsetvect2.deltas.items()) not in deltas1]
[ "def", "time_slide_list_merge", "(", "slides1", ",", "slides2", ")", ":", "deltas1", "=", "set", "(", "frozenset", "(", "offsetvect1", ".", "deltas", ".", "items", "(", ")", ")", "for", "offsetvect1", "in", "slides1", ")", "return", "slides1", "+", "[", ...
Merges two lists of offset dictionaries into a single list with no duplicate (equivalent) time slides.
[ "Merges", "two", "lists", "of", "offset", "dictionaries", "into", "a", "single", "list", "with", "no", "duplicate", "(", "equivalent", ")", "time", "slides", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/time_slide.py#L147-L153
blaklites/fb
fb/wiring.py
send_request
def send_request(req_cat, con, req_str, kwargs): """ Sends request to facebook graph Returns the facebook-json response converted to python object """ try: kwargs = parse.urlencode(kwargs) #python3x except: kwargs = urllib.urlencode(kwargs) #python2x """ Wrapper to keep TCP connection ESTABLISHED. Rather the connection go to CLOSE_WAIT and raise errors CannotSendRequest or the server reply with empty and it raise BadStatusLine """ try: con.request(req_cat, req_str, kwargs) #send request to facebook graph except httplib.CannotSendRequest: con = create() con.request(req_cat, req_str, kwargs) try: res = con.getresponse().read() #read response except (IOError, httplib.BadStatusLine): con = create() con.request(req_cat, req_str, kwargs) res = con.getresponse().read() t = type(res) if type(res) == t: res = bytes.decode(res) return json.loads(res)
python
def send_request(req_cat, con, req_str, kwargs): """ Sends request to facebook graph Returns the facebook-json response converted to python object """ try: kwargs = parse.urlencode(kwargs) #python3x except: kwargs = urllib.urlencode(kwargs) #python2x """ Wrapper to keep TCP connection ESTABLISHED. Rather the connection go to CLOSE_WAIT and raise errors CannotSendRequest or the server reply with empty and it raise BadStatusLine """ try: con.request(req_cat, req_str, kwargs) #send request to facebook graph except httplib.CannotSendRequest: con = create() con.request(req_cat, req_str, kwargs) try: res = con.getresponse().read() #read response except (IOError, httplib.BadStatusLine): con = create() con.request(req_cat, req_str, kwargs) res = con.getresponse().read() t = type(res) if type(res) == t: res = bytes.decode(res) return json.loads(res)
[ "def", "send_request", "(", "req_cat", ",", "con", ",", "req_str", ",", "kwargs", ")", ":", "try", ":", "kwargs", "=", "parse", ".", "urlencode", "(", "kwargs", ")", "#python3x", "except", ":", "kwargs", "=", "urllib", ".", "urlencode", "(", "kwargs", ...
Sends request to facebook graph Returns the facebook-json response converted to python object
[ "Sends", "request", "to", "facebook", "graph", "Returns", "the", "facebook", "-", "json", "response", "converted", "to", "python", "object" ]
train
https://github.com/blaklites/fb/blob/4ddba4dae204463ed24f473872215c5a26370a81/fb/wiring.py#L21-L52
ebu/PlugIt
plugit/utils.py
action
def action(route, template='', methods=['GET']): """Decorator to create an action""" def real_decorator(function): function.pi_api_action = True function.pi_api_route = route function.pi_api_template = template function.pi_api_methods = methods if hasattr(function, 'pi_api_crossdomain'): if not function.pi_api_crossdomain_data['methods']: function.pi_api_crossdomain_data['methods'] = methods if 'OPTIONS' not in function.pi_api_methods: function.pi_api_methods += ['OPTIONS'] return function return real_decorator
python
def action(route, template='', methods=['GET']): """Decorator to create an action""" def real_decorator(function): function.pi_api_action = True function.pi_api_route = route function.pi_api_template = template function.pi_api_methods = methods if hasattr(function, 'pi_api_crossdomain'): if not function.pi_api_crossdomain_data['methods']: function.pi_api_crossdomain_data['methods'] = methods if 'OPTIONS' not in function.pi_api_methods: function.pi_api_methods += ['OPTIONS'] return function return real_decorator
[ "def", "action", "(", "route", ",", "template", "=", "''", ",", "methods", "=", "[", "'GET'", "]", ")", ":", "def", "real_decorator", "(", "function", ")", ":", "function", ".", "pi_api_action", "=", "True", "function", ".", "pi_api_route", "=", "route",...
Decorator to create an action
[ "Decorator", "to", "create", "an", "action" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/utils.py#L12-L28
ebu/PlugIt
plugit/utils.py
cache
def cache(time=0, byUser=None): """Decorator to specify the number of seconds the result should be cached, and if cache can be shared between users :param time: Cache timeout in seconds :param byUser: False by default, if true, cache is shared among users """ def real_decorator(function): function.pi_api_cache_time = time function.pi_api_cache_by_user = byUser return function return real_decorator
python
def cache(time=0, byUser=None): """Decorator to specify the number of seconds the result should be cached, and if cache can be shared between users :param time: Cache timeout in seconds :param byUser: False by default, if true, cache is shared among users """ def real_decorator(function): function.pi_api_cache_time = time function.pi_api_cache_by_user = byUser return function return real_decorator
[ "def", "cache", "(", "time", "=", "0", ",", "byUser", "=", "None", ")", ":", "def", "real_decorator", "(", "function", ")", ":", "function", ".", "pi_api_cache_time", "=", "time", "function", ".", "pi_api_cache_by_user", "=", "byUser", "return", "function", ...
Decorator to specify the number of seconds the result should be cached, and if cache can be shared between users :param time: Cache timeout in seconds :param byUser: False by default, if true, cache is shared among users
[ "Decorator", "to", "specify", "the", "number", "of", "seconds", "the", "result", "should", "be", "cached", "and", "if", "cache", "can", "be", "shared", "between", "users", ":", "param", "time", ":", "Cache", "timeout", "in", "seconds", ":", "param", "byUse...
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/utils.py#L71-L80
ebu/PlugIt
plugit/utils.py
add_unique_postfix
def add_unique_postfix(fn): """__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'""" if not os.path.exists(fn): return fn path, name = os.path.split(fn) name, ext = os.path.splitext(name) make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext)) for i in xrange(2, sys.maxint): uni_fn = make_fn(i) if not os.path.exists(uni_fn): return uni_fn
python
def add_unique_postfix(fn): """__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'""" if not os.path.exists(fn): return fn path, name = os.path.split(fn) name, ext = os.path.splitext(name) make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext)) for i in xrange(2, sys.maxint): uni_fn = make_fn(i) if not os.path.exists(uni_fn): return uni_fn
[ "def", "add_unique_postfix", "(", "fn", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "return", "fn", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "fn", ")", "name", ",", "ext", "=", "os", ".",...
__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/
[ "__source__", "=", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "577200", "-", "make", "-", "unique", "-", "file", "-", "name", "/" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/utils.py#L182-L195