_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q39500
Client.show_domain_record
train
def show_domain_record(self, domain_id, record_id): """ This method returns the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve a record. record_id: Integer, specifies the record_id to retrieve. """ json = self.request('/domains/%s/records/%s' % (domain_id, record_id), method='GET') status = json.get('status') if status == 'OK': domain_record_json = json.get('record') domain_record = Record.from_json(domain_record_json) return domain_record else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
{ "resource": "" }
q39501
Client.destroy_domain_record
train
def destroy_domain_record(self, domain_id, record_id): """ This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. record_id: Integer, specifies the record_id to destroy. """ json = self.request('/domains/%s/records/%s/destroy' % (domain_id, record_id), method='GET') status = json.get('status') return status
python
{ "resource": "" }
q39502
Client.events
train
def events(self, event_id): """ This method is primarily used to report on the progress of an event by providing the percentage of completion. Required parameters event_id: Numeric, this is the id of the event you would like more information about """ json = self.request('/events/%s' % event_id, method='GET') status = json.get('status') if status == 'OK': event_json = json.get('event') event = Event.from_json(event_json) return event else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
{ "resource": "" }
q39503
get_ebuio_headers
train
def get_ebuio_headers(request): """Return a dict with ebuio headers""" retour = {} for (key, value) in request.headers: if key.startswith('X-Plugit-'): key = key[9:] retour[key] = value return retour
python
{ "resource": "" }
q39504
demo
train
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
{ "resource": "" }
q39505
ProgressBar.show
train
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
{ "resource": "" }
q39506
SinkhornKnopp.fit
train
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
{ "resource": "" }
q39507
request_ligodotorg
train
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
{ "resource": "" }
q39508
publish_cat1
train
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
{ "resource": "" }
q39509
get_object_cat1
train
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
{ "resource": "" }
q39510
Match.get_variables_substitution_dictionaries
train
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
{ "resource": "" }
q39511
readTableFromDelimited
train
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
{ "resource": "" }
q39512
readTableFromCSV
train
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
{ "resource": "" }
q39513
Table.cell
train
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
{ "resource": "" }
q39514
Table.rows
train
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
{ "resource": "" }
q39515
init_db
train
def init_db(): """ Drops and re-creates the SQL schema """ db.drop_all() db.configure_mappers() db.create_all() db.session.commit()
python
{ "resource": "" }
q39516
ZipWrap.load_zipfile
train
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
{ "resource": "" }
q39517
ZipWrap.load_dir
train
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
{ "resource": "" }
q39518
ZipWrap._rel_path
train
def _rel_path(self, path, basepath=None): """ trim off basepath """ basepath = basepath or self.src_dir return path[len(basepath) + 1:]
python
{ "resource": "" }
q39519
ZipWrap.unzip
train
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
{ "resource": "" }
q39520
GraphDatabase.query
train
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
{ "resource": "" }
q39521
GraphDatabase.__query_with_builder
train
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
{ "resource": "" }
q39522
create_secret
train
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
{ "resource": "" }
q39523
main
train
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
{ "resource": "" }
q39524
pesaplyMM.make_payment
train
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
{ "resource": "" }
q39525
pesaplyMM.get_balance
train
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
{ "resource": "" }
q39526
pesaplyMM.get_url
train
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
{ "resource": "" }
q39527
pesaplyMM.post_url
train
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
{ "resource": "" }
q39528
pesaplyMM._parse_transactions
train
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
{ "resource": "" }
q39529
getPlugItObject
train
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
{ "resource": "" }
q39530
generate_user
train
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
{ "resource": "" }
q39531
gen404
train
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
{ "resource": "" }
q39532
gen500
train
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
{ "resource": "" }
q39533
gen403
train
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
{ "resource": "" }
q39534
get_cache_key
train
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
{ "resource": "" }
q39535
check_rights_and_access
train
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
{ "resource": "" }
q39536
is_requestaddress_in_networks
train
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
{ "resource": "" }
q39537
is_address_in_network
train
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
{ "resource": "" }
q39538
find_in_cache
train
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
{ "resource": "" }
q39539
build_base_parameters
train
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
{ "resource": "" }
q39540
build_user_requested_parameters
train
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
{ "resource": "" }
q39541
build_parameters
train
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
{ "resource": "" }
q39542
build_extra_headers
train
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
{ "resource": "" }
q39543
handle_special_cases
train
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
{ "resource": "" }
q39544
build_final_response
train
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
{ "resource": "" }
q39545
render_data
train
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
{ "resource": "" }
q39546
cache_if_needed
train
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
{ "resource": "" }
q39547
get_current_orga
train
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
{ "resource": "" }
q39548
update_session
train
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
{ "resource": "" }
q39549
get_current_session
train
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
{ "resource": "" }
q39550
media
train
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
{ "resource": "" }
q39551
setUser
train
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
{ "resource": "" }
q39552
setOrga
train
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
{ "resource": "" }
q39553
check_api_key
train
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
{ "resource": "" }
q39554
home
train
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
{ "resource": "" }
q39555
api_home
train
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
{ "resource": "" }
q39556
api_user
train
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
{ "resource": "" }
q39557
api_orga
train
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
{ "resource": "" }
q39558
api_get_project_members
train
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
{ "resource": "" }
q39559
api_techgroup_list
train
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
{ "resource": "" }
q39560
api_user_techgroup_list
train
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
{ "resource": "" }
q39561
generic_send_mail
train
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
{ "resource": "" }
q39562
api_send_mail
train
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
{ "resource": "" }
q39563
api_orgas
train
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
{ "resource": "" }
q39564
api_ebuio_forum
train
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
{ "resource": "" }
q39565
api_ebuio_forum_get_topics_by_tag_for_user
train
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
{ "resource": "" }
q39566
Client.auto_complete
train
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
{ "resource": "" }
q39567
Client.parse_address
train
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
{ "resource": "" }
q39568
Client.similar
train
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
{ "resource": "" }
q39569
Client.connect
train
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
{ "resource": "" }
q39570
Client.listen
train
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
{ "resource": "" }
q39571
Client.on_message
train
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
{ "resource": "" }
q39572
Client.send_facebook
train
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
{ "resource": "" }
q39573
Client.send_respawn
train
def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick))
python
{ "resource": "" }
q39574
Client.send_target
train
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
{ "resource": "" }
q39575
Client.send_explode
train
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
{ "resource": "" }
q39576
send_request
train
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
{ "resource": "" }
q39577
action
train
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
{ "resource": "" }
q39578
Command.handle
train
def handle(self, *args, **options): """ Handle liquibase command parameters """ database = getattr( settings, 'LIQUIMIGRATE_DATABASE', options['database']) try: dbsettings = databases[database] except KeyError: raise CommandError("don't know such a connection: %s" % database) verbosity = int(options.get('verbosity')) # get driver driver_class = ( options.get('driver') or dbsettings.get('ENGINE').split('.')[-1]) dbtag, driver, classpath = LIQUIBASE_DRIVERS.get( driver_class, (None, None, None)) classpath = options.get('classpath') or classpath if driver is None: raise CommandError( "unsupported db driver '%s'\n" "available drivers: %s" % ( driver_class, ' '.join(LIQUIBASE_DRIVERS.keys()))) # command options changelog_file = ( options.get('changelog_file') or _get_changelog_file(options['database'])) username = options.get('username') or dbsettings.get('USER') or '' password = options.get('password') or dbsettings.get('PASSWORD') or '' url = options.get('url') or _get_url_for_db(dbtag, dbsettings) command = options['command'] cmdargs = { 'jar': LIQUIBASE_JAR, 'changelog_file': changelog_file, 'username': username, 'password': password, 'command': command, 'driver': driver, 'classpath': classpath, 'url': url, 'args': ' '.join(args), } cmdline = "java -jar %(jar)s --changeLogFile %(changelog_file)s \ --username=%(username)s --password=%(password)s \ --driver=%(driver)s --classpath=%(classpath)s --url=%(url)s \ %(command)s %(args)s" % (cmdargs) if verbosity > 0: print("changelog file: %s" % (changelog_file,)) print("executing: %s" % (cmdline,)) created_models = None # we dont know it if emit_pre_migrate_signal and not options.get('no_signals'): if django_19_or_newer: emit_pre_migrate_signal( 1, options.get('interactive'), database) else: emit_pre_migrate_signal( created_models, 1, options.get('interactive'), database) rc = os.system(cmdline) if rc == 0: try: if not options.get('no_signals'): if emit_post_migrate_signal: if django_19_or_newer: emit_post_migrate_signal( 0, options.get('interactive'), database) else: emit_post_migrate_signal( created_models, 0, options.get('interactive'), database) elif emit_post_sync_signal: emit_post_sync_signal( created_models, 0, options.get('interactive'), database) if not django_19_or_newer: call_command( 'loaddata', 'initial_data', verbosity=1, database=database) except TypeError: # singledb (1.1 and older) emit_post_sync_signal( created_models, 0, options.get('interactive')) call_command( 'loaddata', 'initial_data', verbosity=0) else: raise CommandError('Liquibase returned an error code %s' % rc)
python
{ "resource": "" }
q39579
lines
train
def lines(fp): """ Read lines of UTF-8 from the file-like object given in ``fp``, making sure that when reading from STDIN, reads are at most line-buffered. UTF-8 decoding errors are handled silently. Invalid characters are replaced by U+FFFD REPLACEMENT CHARACTER. Line endings are normalised to newlines by Python's universal newlines feature. Returns an iterator yielding lines. """ if fp.fileno() == sys.stdin.fileno(): close = True try: # Python 3 fp = open(fp.fileno(), mode='r', buffering=BUF_LINEBUFFERED, errors='replace') decode = False except TypeError: fp = os.fdopen(fp.fileno(), 'rU', BUF_LINEBUFFERED) decode = True else: close = False try: # only decode if the fp doesn't already have an encoding decode = (fp.encoding != UTF8) except AttributeError: # fp has been opened in binary mode decode = True try: while 1: l = fp.readline() if l: if decode: l = l.decode(UTF8, 'replace') yield l else: break finally: if close: fp.close()
python
{ "resource": "" }
q39580
api.publish
train
def publish(self, cat, **kwargs): """ This method is used for creating objects in the facebook graph. The first paramter is "cat", the category of publish. In addition to "cat" "id" must also be passed and is catched by "kwargs" """ res=request.publish_cat1("POST", self.con, self.token, cat, kwargs) return res
python
{ "resource": "" }
q39581
api.get_object
train
def get_object(self, cat, **kwargs): """ This method is used for retrieving objects from facebook. "cat", the category, must be passed. When cat is "single", pass the "id "and desired "fields" of the single object. If the cat is "multiple", only pass the "ids" of the objects to be fetched. """ if 'id' not in kwargs.keys(): kwargs['id']='' res=request.get_object_cat1(self.con, self.token, cat, kwargs) return res
python
{ "resource": "" }
q39582
StripTableName
train
def StripTableName(name): """ Return the significant portion of a table name according to LIGO LW naming conventions. Example: >>> StripTableName("sngl_burst_group:sngl_burst:table") 'sngl_burst' >>> StripTableName("sngl_burst:table") 'sngl_burst' >>> StripTableName("sngl_burst") 'sngl_burst' """ if name.lower() != name: warnings.warn("table name \"%s\" is not lower case" % name) try: return TablePattern.search(name).group("Name") except AttributeError: return name
python
{ "resource": "" }
q39583
use_in
train
def use_in(ContentHandler): """ Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table, Column, and Stream classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class LIGOLWContentHandler(ligolw.LIGOLWContentHandler): ... pass ... >>> use_in(LIGOLWContentHandler) <class 'pycbc_glue.ligolw.table.LIGOLWContentHandler'> """ def startColumn(self, parent, attrs): return Column(attrs) def startStream(self, parent, attrs, __orig_startStream = ContentHandler.startStream): if parent.tagName == ligolw.Table.tagName: parent._end_of_columns() return TableStream(attrs).config(parent) return __orig_startStream(self, parent, attrs) def startTable(self, parent, attrs): return Table(attrs) ContentHandler.startColumn = startColumn ContentHandler.startStream = startStream ContentHandler.startTable = startTable return ContentHandler
python
{ "resource": "" }
q39584
Column.count
train
def count(self, value): """ Return the number of rows with this column equal to value. """ return sum(getattr(row, self.Name) == value for row in self.parentNode)
python
{ "resource": "" }
q39585
Table.appendColumn
train
def appendColumn(self, name): """ Append a Column element named "name" to the table. Returns the new child. Raises ValueError if the table already has a column by that name, and KeyError if the validcolumns attribute of this table does not contain an entry for a column by that name. Note that the name string is assumed to be "pre-stripped", that is it is the significant portion of the elements Name attribute. The Column element's Name attribute will be constructed by pre-pending the stripped Table element's name and a colon. Example: >>> import lsctables >>> process_table = lsctables.New(lsctables.ProcessTable, []) >>> col = process_table.appendColumn("program") >>> col.getAttribute("Name") 'process:program' >>> col.Name 'program' """ try: self.getColumnByName(name) # if we get here the table already has that column raise ValueError("duplicate Column '%s'" % name) except KeyError: pass column = Column(AttributesImpl({u"Name": "%s:%s" % (StripTableName(self.tableName), name), u"Type": self.validcolumns[name]})) streams = self.getElementsByTagName(ligolw.Stream.tagName) if streams: self.insertBefore(column, streams[0]) else: self.appendChild(column) return column
python
{ "resource": "" }
q39586
Table.appendRow
train
def appendRow(self, *args, **kwargs): """ Create and append a new row to this table, then return it All positional and keyword arguments are passed to the RowType constructor for this table. """ row = self.RowType(*args, **kwargs) self.append(row) return row
python
{ "resource": "" }
q39587
Table.removeChild
train
def removeChild(self, child): """ Remove a child from this element. The child element is returned, and it's parentNode element is reset. """ super(Table, self).removeChild(child) if child.tagName == ligolw.Column.tagName: self._update_column_info() return child
python
{ "resource": "" }
q39588
Table.sync_next_id
train
def sync_next_id(self): """ Determines the highest-numbered ID in this table, and sets the table's .next_id attribute to the next highest ID in sequence. If the .next_id attribute is already set to a value greater than the highest value found, then it is left unmodified. The return value is the ID identified by this method. If the table's .next_id attribute is None, then this function is a no-op. Note that tables of the same name typically share a common .next_id attribute (it is a class attribute, not an attribute of each instance) so that IDs can be generated that are unique across all tables in the document. Running sync_next_id() on all the tables in a document that are of the same type will have the effect of setting the ID to the next ID higher than any ID in any of those tables. Example: >>> import lsctables >>> tbl = lsctables.New(lsctables.ProcessTable) >>> print tbl.sync_next_id() process:process_id:0 """ if self.next_id is not None: if len(self): n = max(self.getColumnByName(self.next_id.column_name)) + 1 else: n = type(self.next_id)(0) if n > self.next_id: self.set_next_id(n) return self.next_id
python
{ "resource": "" }
q39589
Table.applyKeyMapping
train
def applyKeyMapping(self, mapping): """ Used as the second half of the key reassignment algorithm. Loops over each row in the table, replacing references to old row keys with the new values from the mapping. """ for coltype, colname in zip(self.columntypes, self.columnnames): if coltype in ligolwtypes.IDTypes and (self.next_id is None or colname != self.next_id.column_name): column = self.getColumnByName(colname) for i, old in enumerate(column): try: column[i] = mapping[old] except KeyError: pass
python
{ "resource": "" }
q39590
Get.input
train
def input(self, field): """Gets user input for given field. Can be interrupted with ^C. :field: Field name. :returns: User input. """ try: desc = Get.TYPES[field] return input("{}|{}[{}]> ".format( field, "-" * (Get._LEN - len(field) - len(desc)), desc )) except KeyboardInterrupt: print() exit(0)
python
{ "resource": "" }
q39591
Get.get
train
def get(self, field, value=None): """Gets user input for given field and checks if it is valid. If input is invalid, it will ask the user to enter it again. Defaults values to empty or :value:. It does not check validity of parent index. It can only be tested further down the road, so for now accept anything. :field: Field name. :value: Default value to use for field. :returns: User input. """ self.value = value val = self.input(field) if field == 'name': while True: if val != '': break print("Name cannot be empty.") val = self.input(field) elif field == 'priority': if val == '': # Use default priority return None while True: if val in Get.PRIORITIES.values(): break c, val = val, Get.PRIORITIES.get(val) if val: break print("Unrecognized priority number or name [{}].".format(c)) val = self.input(field) val = int(val) return val
python
{ "resource": "" }
q39592
Arg._getPattern
train
def _getPattern(self, ipattern, done=None): """Parses sort pattern. :ipattern: A pattern to parse. :done: If :ipattern: refers to done|undone, use this to indicate proper state. :returns: A pattern suitable for Model.modify. """ if ipattern is None: return None if ipattern is True: if done is not None: return ([(None, None, done)], {}) # REMEMBER: This False is for sort reverse! return ([(0, False)], {}) def _getReverse(pm): return pm == '-' def _getIndex(k): try: return int(k) except ValueError: raise InvalidPatternError(k, "Invalid level number") def _getDone(p): v = p.split('=') if len(v) == 2: try: return (Model.indexes[v[0]], v[1], done) except KeyError: raise InvalidPatternError(v[0], 'Invalid field name') return (None, v[0], done) ipattern1 = list() ipattern2 = dict() for s in ipattern.split(','): if done is not None: v = done else: v = _getReverse(s[-1]) k = s.split(':') if len(k) == 1: if done is not None: ipattern1.append(_getDone(k[0])) continue ko = k[0][:-1] try: if len(k[0]) == 1: k = 0 else: k = Model.indexes[ko] except KeyError: k = _getIndex(k[0][:-1]) else: ipattern1.append((k, v)) continue v = (0, v) elif len(k) == 2: try: if done is not None: v = _getDone(k[1]) else: v = (Model.indexes[k[1][:-1]], v) k = _getIndex(k[0]) except KeyError: raise InvalidPatternError(k[1][:-1], 'Invalid field name') else: raise InvalidPatternError(s, 'Unrecognized token in') ipattern2.setdefault(k, []).append(v) return (ipattern1, ipattern2)
python
{ "resource": "" }
q39593
Arg._getDone
train
def _getDone(self, done, undone): """Parses the done|undone state. :done: Done marking pattern. :undone: Not done marking pattern. :returns: Pattern for done|undone or None if neither were specified. """ if done: return self._getPattern(done, True) if undone: return self._getPattern(undone, False)
python
{ "resource": "" }
q39594
Arg.view
train
def view(self, sort=None, purge=False, done=None, undone=None, **kwargs): """Handles the 'v' command. :sort: Sort pattern. :purge: Whether to purge items marked as 'done'. :done: Done pattern. :undone: Not done pattern. :kwargs: Additional arguments to pass to the View object. """ View(self.model.modify( sort=self._getPattern(sort), purge=purge, done=self._getDone(done, undone) ), **kwargs)
python
{ "resource": "" }
q39595
Arg.modify
train
def modify(self, sort=None, purge=False, done=None, undone=None): """Handles the 'm' command. :sort: Sort pattern. :purge: Whether to purge items marked as 'done'. :done: Done pattern. :undone: Not done pattern. """ self.model.modifyInPlace( sort=self._getPattern(sort), purge=purge, done=self._getDone(done, undone) )
python
{ "resource": "" }
q39596
Arg.add
train
def add(self, **args): """Handles the 'a' command. :args: Arguments supplied to the 'a' command. """ kwargs = self.getKwargs(args) if kwargs: self.model.add(**kwargs)
python
{ "resource": "" }
q39597
Arg.edit
train
def edit(self, **args): """Handles the 'e' command. :args: Arguments supplied to the 'e' command. """ if self.model.exists(args["index"]): values = dict(zip( ['parent', 'name', 'priority', 'comment', 'done'], self.model.get(args["index"]) )) kwargs = self.getKwargs(args, values) if kwargs: self.model.edit(args["index"], **kwargs)
python
{ "resource": "" }
q39598
Arg.rm
train
def rm(self, index): """Handles the 'r' command. :index: Index of the item to remove. """ if self.model.exists(index): self.model.remove(index)
python
{ "resource": "" }
q39599
Arg.done
train
def done(self, index): """Handles the 'd' command. :index: Index of the item to mark as done. """ if self.model.exists(index): self.model.edit(index, done=True)
python
{ "resource": "" }