code stringlengths 1 18.2k |
|---|
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(rowNa... |
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 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 init_db(): """ Drops and re-creates the SQL schema """ db.drop_all() db.configure_mappers() db.create_all() db.session.commit() |
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 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_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(pat... |
def _rel_path(self, path, basepath=None): """ trim off basepath """ basepath = basepath or self.src_dir return path[len(basepath) + 1:] |
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 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': 'P... |
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_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 act... |
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 = ... |
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... |
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 imag... |
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 argu... |
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_UR... |
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 tra... |
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) ex... |
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... |
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 wa... |
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.LinkNotFoundEr... |
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:... |
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 t... |
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.st... |
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=hproP... |
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... |
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_la... |
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=... |
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 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 = Organizatio... |
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_log... |
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 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 pr... |
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 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 n... |
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... |
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... |
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[... |
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 =... |
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(... |
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... |
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... |
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 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... |
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_n... |
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... |
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('plu... |
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_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 firs... |
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 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 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_REA... |
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.P... |
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) i... |
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,... |
= 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, resu... |
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 Excepti... |
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 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 Org... |
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 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... |
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_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 =... |
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), ... |
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) = getPlugItObj... |
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) = getPlugItObjec... |
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 == ... |
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")] e... |
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... |
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.... |
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 AE... |
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.PO... |
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':... |
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") (_, _, h... |
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_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 HttpResponseForbid... |
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(), 'su... |
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/autoC... |
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 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 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.f... |
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 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: ... |
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_err... |
packet' % packet_name self.subscriber.on_message_error(msg) return packet_name |
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_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' % le... |
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_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) |
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 spe... |
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 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:... |
= 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_slid... |
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 map... |
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: prog... |
- len(time_slides)) # done del progressbar return mapping |
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.de... |
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... |
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_crossdom... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.