Example #1
1
def getPersonnelData(person_id):
    data = {}
    try:
        personnel = DirPersonnel.objects.get(pk=person_id)
    except DirPersonnel.DoesNotExist:
        print("No such personnel to get data")
        return data

    data["user_name"] = personnel.user_name
    data["first_name"] = personnel.first_name
    data["last_name"] = personnel.last_name
    data["name"] = data["first_name"] + " " + data["last_name"]
    data["city"] = personnel.city
    data["occupation"] = personnel.occupation
    data["creation_date"] = personnel.creation_date
    data["modified_date"] = personnel.modified_date
    data["id"] = personnel.person_id
    attr = [
        "openid",
        "header_url",
        "middle_name",
        "gender",
        "province_state",
        "country",
        "email_address",
        "self_introduction",
        "executive_team_member",
    ]
    for field in attr:
        value = getattr(personnel, field)
        if value is None:
            value = ""
        data[field] = value

    return data
Example #2
1
 def parseSEED(self, blockette, data):
     """
     """
     try:
         self.length = int(getattr(blockette, self.index_field))
     except:
         msg = "Missing attribute %s in Blockette %s"
         raise Exception(msg % (self.index_field, blockette))
     # loop over number of entries
     debug = blockette.debug
     blockette.debug = False
     temp = []
     for _i in xrange(0, self.length):
         # loop over data fields within one entry
         for field in self.data_fields:
             field.parseSEED(blockette, data)
             if debug:
                 temp.append(field.data)
     # debug
     if debug:
         if len(temp) > 3:
             print("  LOOP: ... (%d elements) " % (len(temp)))
         else:
             print("  LOOP: %s" % (temp))
         blockette.debug = debug
Example #3
1
    def on_load(self, container):

        self.Builder = Gtk.Builder()
        self.Builder.set_translation_domain("blueman")
        self.Builder.add_from_file(UI_PATH + "/services-network.ui")
        self.widget = self.Builder.get_object("network")

        self.ignored_keys = []

        container.pack_start(self.widget, True, True, 0)

        self.interfaces = []
        for iface in get_net_interfaces():
            if iface != "lo" and iface != "pan1":
                print(iface)
                ip = inet_aton(get_net_address(iface))
                mask = inet_aton(get_net_netmask(iface))
                self.interfaces.append((iface, ip, mask, mask_ip4_address(ip, mask)))

        self.setup_network()
        try:
            self.ip_check()
        except:
            pass
        return (_("Network"), "network-workgroup")
def main():
    """Extract all Python tutorials urls from this page:
    http://www.bogotobogo.com/python/pytut.php
    """
    import itertools
    import os.path
    import re

    line_generator = fetchPage("http://www.bogotobogo.com/python/pytut.php")

    # We can call builtin function iter in two ways(Please refer to the manual):
    # 1. iter(iterable)
    # 2. iter(callable, sentinel)
    # It seems that we can't pass a generator function to 'callable' in the 2nd
    # form, so I use itertools.takewhile here.
    for line in itertools.takewhile(lambda x: x.strip() != "<h1>List of Python Tutorials</h1>", line_generator):
        pass

    # Ignore all lines until we find the HTML list's start tag: <ul>
    for line in itertools.takewhile(lambda x: x.strip() != "<ul>", line_generator):
        pass

    # Extract all the urls in the HTML list until we reach the end tag: </ul>
    with open(os.path.join(os.path.expanduser("~"), "List_of_Python_Tutorials.txt"), "w") as fp:
        url_pattern = re.compile(r'<a href="(.*)">')

        for line in itertools.takewhile(lambda x: x.strip() != "</ul>", line_generator):
            search_res = url_pattern.search(line)
            if search_res:
                print(search_res.group(1), file=fp)
Example #5
1
def jiraupdate(options, url, data):
    if options.verbose:
        handler = urllib2.HTTPSHandler(debuglevel=1)
    else:
        handler = urllib2.HTTPSHandler()

    opener = urllib2.build_opener(handler)
    urllib2.install_opener(opener)

    jdata = json.dumps(data)

    request = urllib2.Request(options.jiraserver + url, jdata)
    base64string = base64.encodestring("%s:%s" % (options.username, options.password)).replace("\n", "")
    request.add_header("Authorization", "Basic %s" % base64string)
    request.add_header("Content-Type", "application/json")
    request.get_method = lambda: "PUT"

    if options.verbose:
        print "Post: " + options.jiraserver + url
        print "Data: " + jdata

    response = ""

    try:
        response = urllib2.urlopen(request)
    except urllib2.HTTPError, e:
        print ("HTTPError = " + str(e.code) + " " + e.read())
        raise (e)
def tell_story(template):
    """ Run input grab and story based upon loop"""
    story_line = template
    if template == story:
        adjective = raw_input("Enter an adjective ")
        noun = raw_input("Enter a noun ")
        verb = raw_input("Enter a verb ")
        name = raw_input("Enter your name ")
        number = raw_input("Enter a number between 1-10 ")
        number_two = raw_input("Enter a number between 10-20 ")
        year = raw_input("Enter a year (Example: 1986) ")
        magic = template.format(**locals())
        print magic
        response = raw_input("Ready for the next Madlib? (yes or no) ")
        return response
    elif template == story2 and tell_next == "y":
        adjective = raw_input("Enter an adjective ")
        noun = raw_input("Enter a noun ")
        verb = raw_input("Enter a verb (past tense) ")
        name = raw_input("Enter your name ")
        magic = template.format(**locals())
        print magic
        response = raw_input("Ready for the next Madlib? (yes or no) ")
        return response
    else:
        name = raw_input("Enter a name ")
        noun = raw_input("Enter a noun ")
        verb = raw_input("Enter a verb ")
        magic = template.format(**locals())
        print magic
        print ("Thanks so much for playing. There are no more Madlibs to do.")
Example #7
1
def test_backup_projects(server, tmpdir, loop):
    Config.instance().set("Server", "projects_path", str(tmpdir))

    os.makedirs(str(tmpdir / "a"))
    with open(str(tmpdir / "a" / "a.gns3"), "w+") as f:
        f.write("hello")
    os.makedirs(str(tmpdir / "b"))
    with open(str(tmpdir / "b" / "b.gns3"), "w+") as f:
        f.write("world")

    response = server.get("/backup/projects.tar", api_version=None, raw=True)
    assert response.status == 200
    assert response.headers["CONTENT-TYPE"] == "application/x-gtar"

    with open(str(tmpdir / "projects.tar"), "wb+") as f:
        print(len(response.body))
        f.write(response.body)

    tar = tarfile.open(str(tmpdir / "projects.tar"), "r")
    os.makedirs(str(tmpdir / "extract"))
    os.chdir(str(tmpdir / "extract"))
    # Extract to current working directory
    tar.extractall()
    tar.close()

    assert os.path.exists(os.path.join("a", "a.gns3"))
    open(os.path.join("a", "a.gns3")).read() == "hello"

    assert os.path.exists(os.path.join("b", "b.gns3"))
    open(os.path.join("b", "b.gns3")).read() == "world"
Example #8
1
 def add_variable(self, name, dims, data=None, **kwargs):
     if data is None:
         char = "d"
     else:
         if isinstance(data, np.ndarray):
             char = data.dtype.char
         elif isinstance(data, float):
             char = "d"
         elif isinstance(data, int):
             char = "i"
         else:
             char = "c"
     print(("%-34s %s%s" % (name, char, tuple([self.nc.dimensions[dim] for dim in dims]))))
     var = self.nc.createVariable(name, char, dims)
     for attr, value in kwargs.items():
         setattr(var, attr, value)
     if data is not None:
         if len(dims) == 0:
             var.assignValue(data)
         else:
             if char == "c":
                 if len(dims) == 1:
                     var[: len(data)] = data
                 else:
                     for i, x in enumerate(data):
                         var[i, : len(x)] = x
             else:
                 var[:] = data
     return var
Example #9
0
 def on_done(self, idx):
     # if -1 < idx and False != self.base:
     if -1 < idx:
         command = self.commands[idx]
         print("running command : " + command)
         func = getattr(self, command)
         func()
Example #10
0
def read_metadata(local_file):
    metadata = metadata_feed = dict()
    # print("\nReading file: " + local_file)
    if not os.path.exists(local_file):
        print("File not found for metadata update")
        return 1

    cmd_line = ["ffmpeg", "-loglevel", "quiet", "-i", local_file, "-f", "ffmetadata", "-"]

    try:
        process = Popen(cmd_line, stdout=PIPE, stderr=PIPE)  # I'm not sure if I want to do anything with stderr yet
        stdout, stderr = process.communicate()
    except OSError as e:
        print >>sys.stderr, "FFMPEG Failed, aborting metadata updates:", e
        return 0
    for line in stdout.splitlines():
        line.rstrip()
        tokens = line.partition("=")
        if tokens[2]:
            # print("DATA: " + tokens[0] + " = " + tokens[2])
            if tokens[0] == "title":
                metadata["TITLE_MATCH"] = tokens[2]
            elif tokens[0] == "description" or tokens[0] == "TDES":
                metadata["DESCRIPTION_MATCH"] = tokens[2]
            # elif tokens[0] == 'album':
            #    metadata['ALBUM_MATCH'] = tokens[2]
            # elif tokens[0] == 'minor_version':
            #    metadata['EPISODE_MATCH'] = tokens[2]

            metadata[tokens[0]] = tokens[2]
        # else:
        #    print("Not valid metadata: ", line)

    return metadata
Example #11
0
def get_subscriptions(cur, conn):
    try:
        cur.execute("SELECT * FROM subscriptions")
        return cur.fetchall()
    except sqlite3.OperationalError:
        print("There are no current subscriptions")
        return null
Example #12
0
 def test_time(self):
     n = 50000
     test_input = sample(range(n), n)
     test_functions = (merge_sort, merge_sort_not_recursion, quick_sort)
     for func in test_functions:
         running_time = timeit(lambda: func(test_input.copy()), number=1)
         print("{}: {}".format(func.__name__, running_time))
Example #13
0
    def __call__(self, parser, namespace, values, option_string):
        """Implement the action.

        Emits the deprecation warning message (only once for any given
        option string), then calls the real action (if any).

        :param parser: The ``argparse.ArgumentParser`` instance.
        :param namespace: The ``argparse.Namespace`` object which
                          should have an attribute set.
        :param values: Any arguments provided to the option.
        :param option_string: The option string that was used.
        """

        action = self._get_action(parser)

        # Only emit the deprecation warning once per option
        if option_string not in self.emitted:
            if self.use:
                print(
                    _('WARNING: Option "%(option)s" is deprecated; ' "%(use)s")
                    % {"option": option_string, "use": self.use},
                    file=sys.stderr,
                )
            else:
                print(_('WARNING: Option "%(option)s" is deprecated') % {"option": option_string}, file=sys.stderr)
            self.emitted.add(option_string)

        if action:
            action(parser, namespace, values, option_string)
Example #14
0
    def _get_action(self, parser):
        """Retrieve the action callable.

        This internal method is used to retrieve the callable
        implementing the action.  If ``real_action`` was specified as
        ``None`` or one of the standard string names, an internal
        method of the ``argparse.ArgumentParser`` instance is used to
        resolve it into an actual action class, which is then
        instantiated.  This is cached, in case the action is called
        multiple times.

        :param parser: The ``argparse.ArgumentParser`` instance.

        :returns: The action callable.
        """

        # If a lookup is needed, look up the action in the parser
        if self.real_action_args is not False:
            option_strings, dest, help, kwargs = self.real_action_args
            action_class = parser._registry_get("action", self.real_action)

            # Did we find the action class?
            if action_class is None:
                print(_("WARNING: Programming error: Unknown real action " '"%s"') % self.real_action, file=sys.stderr)
                self.real_action = None
            else:
                # OK, instantiate the action class
                self.real_action = action_class(option_strings, dest, help=help, **kwargs)

            # It's been resolved, no further need to look it up
            self.real_action_args = False

        return self.real_action
Example #15
0
def checkLDD(target, source, env):
    file = target[0]
    if not os.path.isfile(file.abspath):
        print ("ERROR: CheckLDD: target %s not found\n" % target[0])
        Exit(1)
    (status, output) = commands.getstatusoutput("ldd -r %s" % file)
    if status != 0:
        print "ERROR: ldd command returned with exit code %d" % ldd_ret
        os.system("rm %s" % target[0])
        sys.exit(1)
    lines = string.split(output, "\n")
    have_undef = 0
    for i_line in lines:
        # print repr(i_line)
        regex = re.compile("undefined symbol: (.*)\t\\((.*)\\)")
        if regex.match(i_line):
            symbol = regex.sub("\\1", i_line)
            try:
                env["ALLOWED_SYMBOLS"].index(symbol)
            except:
                have_undef = 1
    if have_undef:
        print output
        print "ERROR: undefined symbols"
        os.system("rm %s" % target[0])
        sys.exit(1)
Example #16
0
def updateTaskData(
    task_id,
    new_task_name=None,
    new_task_leader_id=None,
    new_task_description=None,
    new_signup_due_date=None,
    new_completion_date=None,
):
    try:
        task = DirTask.objects.get(pk=task_id)
    except DirTask.DoesNotExist:
        print("No such task to update")
        return 0

    if new_task_name:
        task.task_name = new_task_name
    if new_task_leader_id:
        task.task_leader_id = new_task_leader_id
    if new_task_description:
        task.task_description = new_task_description
    if new_signup_due_date:
        task.signup_due_date = new_signup_due_date
    if new_completion_date:
        task.completion_date = new_completion_date

    try:
        task.save()
    except:
        print("Error occured while updating task data")
        return -1
    return 1
Example #17
0
 def run(self):
     while self.running:
         print("Staring %s" % self.name)
         self.proc = multiprocessing.Process(target=__pluginLauncher__, args=(self.remote_pipe, self.name))
         self.proc.start()
         self.proc.join()
         print("Exited %s" % self.name)
def test_depgraph(pytestconfig):
    """ Creates template, runs setup.py depgraph
    """
    with PkgTemplate(name="acme.foo") as pkg:
        pkg.install_package("pytest-cov")
        print(pkg.run_with_coverage(["%s/setup.py" % pkg.trunk_dir, "develop", "-q"], pytestconfig, cd=HERE))
        print(pkg.run_with_coverage(["%s/setup.py" % pkg.trunk_dir, "depgraph"], pytestconfig, cd=HERE))
 def estimateWord(self, word, numberOfEstimates):
     wordEstimates = {}
     for key in self.model[word].freqdist():
         print(key + ": " + repr(self.model[word].prob(key)))
         wordEstimates[key] = self.model[word].prob(key)
     orderedEstimates = ((k, wordEstimates[k]) for k in sorted(wordEstimates, key=wordEstimates.get, reverse=True))
     return [(k, v) for k, v in orderedEstimates][:numberOfEstimates]
Example #20
0
 def t1(self):
     print("t1")
     try:
         self.t2()
     except RuntimeError as e:
         print(e.message)
     pass
Example #21
0
 def log_output(self, message):
     print("status is : " + str(message[0]))
     if 0 == message[0]:
         sublime.status_message("Command completed ok")
     else:
         sublime.error_message("Command had errors")
     self._output_to_view(message[1])
Example #22
0
def logout():
    print("Try to logout")
    session.pop("logged_in", None)
    session.pop("last", None)
    session.pop("user", None)
    flash("You were logged out")
    return redirect(url_for("login"))
Example #23
0
File: pr.py Project: navan93/gtfs
def main():

    i = 0
    employees = [random_mac() for _ in range(13)]
    for edge in edges[sys.argv[1]]:
        time.sleep(0.5)
        i += 1
        jsond = json.dumps(
            {
                "position": {"lat": edge[1], "lng": edge[0]},
                "trip_id": sys.argv[1],
                "time": datetime.datetime.now().strftime("%y-%m-%d-%H-%M-%S"),
                "det": {
                    "trip_id": "617_EY_PATTOM" + sys.argv[1],
                    "emp": employees,
                    "stops_visited": stops_visited,
                    "stops_rem": stops_rem,
                },
            }
        )
        redispub(jsond)
        print(jsond)
        if i == 30:
            i = 0
            employees.pop(0)
            employees.append(random_mac())
            place = stops_rem.pop(0)
            stops_visited.append(place)
            time.sleep(3)
Example #24
0
def api(type):
    l = lib.container(options)
    u = lib.user(options)
    d = lib.domain(options)
    db = lib.database(options)
    b = lib.backup(options)
    a = lib.admin(options)

    if request.method == "GET":
        if type == "container":
            return Response(json.dumps(l.list()), mimetype="application/json")
        elif type == "user":
            return Response(json.dumps(u.list()), mimetype="application/json")
        elif type == "domain":
            return Response(json.dumps(d.list()), mimetype="application/json")
        elif type == "database":
            return Response(json.dumps(db.list()), mimetype="application/json")
        elif type == "backup":
            return Response(json.dumps(b.list()), mimetype="application/json")
        elif type == "admin":
            return Response(json.dumps(a.list()), mimetype="application/json")
        elif type == "images":
            return Response(json.dumps(l.images()), mimetype="application/json")
        else:
            return Response(
                json.dumps({"status": "Error", "extstatus": "service not defined"}), mimetype="application/json"
            )
    else:
        print("not implemented")

    return json.dumps({})
Example #25
0
 def parseXML(self, blockette, xml_doc, pos=0):
     """
     """
     try:
         text = xml_doc.xpath(self.field_name + "/text()")[pos]
     except:
         setattr(blockette, self.attribute_name, self.default_value)
         # debug
         if blockette.debug:
             print("  %s: set to default value %s" % (self, self.default_value))
         return
     # Parse X-Path if necessary. The isdigit test assures legacy support
     # for XSEED without XPaths.
     if self.xpath and not text.isdigit():
         text = utils.getXPath(text)
     # check if already exists
     if hasattr(blockette, self.attribute_name):
         temp = getattr(blockette, self.attribute_name)
         if not isinstance(temp, list):
             temp = [temp]
         temp.append(text)
         text = temp
     setattr(blockette, self.attribute_name, self.convert(text))
     # debug
     if blockette.debug:
         print("  %s: %s" % (self, text))
Example #26
0
    def testResults(self):
        """ Provide in-browser test results in hash format.
    
    This is an overloaded method and represents:
    1. Querying test results; and
    2. Asking testcases to terminate after 'test_timout' value specified
      in startTest() method parameter if the tests haven't been completed 
      between calling startTest() and invoking this method.
    """
        if not self.test_instance_is_running:
            raise StandardError("None of the tests were started")

        self.test_completion_lock.wait(self.test_timeout)
        test_result = ""
        if self.test_completion_lock.isSet():
            test_result = self.json_test_result
        else:
            print(
                "Browser tests failed to complete and timed out.  "
                "It is likely that either the test webserver failed "
                "to start, or one of the test cases hung."
            )
            test_result = "TIMED-OUT"
        self.test_completion_lock.clear()
        self.test_instance_is_running = False
        self.json_test_result = ""
        return test_result
Example #27
0
def find_average_change(stats_df, start_year, start_round, team):
    def remove_header(index):
        list_from_index = index.tolist()
        for ind, index_name in enumerate(list_from_index):
            list_from_index[ind] = index_name[3:]
        return list_from_index

    this_round = stats_df.loc[(stats_df.year == start_year) & (stats_df.round == start_round) & (stats_df.away == team)]
    this_round = this_round.filter(regex="aw_avg_")
    this_round.columns = remove_header(this_round.columns)
    if this_round.empty:
        this_round = stats_df.loc[
            (stats_df.year == start_year) & (stats_df.round == start_round) & (stats_df.home == team)
        ]
        this_round = this_round.filter(regex="hm_avg_")
        this_round.columns = remove_header(this_round.columns)
    last_round = stats_df.loc[
        (stats_df.year == start_year) & (stats_df.round == (start_round - 1)) & (stats_df.away == team)
    ]
    last_round = last_round.filter(regex="aw_avg_")
    last_round.columns = remove_header(last_round.columns)
    if last_round.empty:
        last_round = stats_df.loc[
            (stats_df.year == start_year) & (stats_df.round == (start_round - 1)) & (stats_df.home == team)
        ]
        last_round = last_round.filter(regex="hm_avg_")
        last_round.columns = remove_header(last_round.columns)
    print(this_round.iloc[0, 0])
    print(last_round.iloc[0, 0])
    return this_round.iloc[0] - last_round.iloc[0]
Example #28
0
    def new_func():

        starttime = datetime.now()

        func()

        print("exectime: ", datetime.now() - starttime)
Example #29
0
 def mk(n):
     res = []
     for i in xrange(n):
         res.append("x")
     res = "".join(res)
     print(len(res))
     return res
Example #30
0
 def cal_dimension(self, ids, context={}):
     all_vals = {}
     dbname = database.get_active_db()
     for obj in self.browse(ids):
         master_img = obj.product_id.image
         master_path = os.path.join("static/db/", dbname, "files", master_img)
         frame = int(obj.get("rotate_frame"))
         column = int(obj.get("rotate_footage"))
         row = 1
         if frame and column:
             row = frame / column
         vals = {}
         im_path = obj.image
         if im_path and frame and column:
             filename = os.path.join("static/db/", dbname, "files", im_path)
             img = Image.open(filename)
             (width, height) = img.size
             swidth = math.floor(width / column)
             sheight = math.floor(height / row)
             vals["rotate_width"] = swidth
             vals["rotate_height"] = sheight
             vals["master_image"] = master_path
             all_vals[obj.id] = vals
         else:
             print("Not enough arguments given")
     return all_vals