Example #1
0
def index():
    form = SearchForm()

    query = request.args.get('query', '').strip()

    db = TinyDB(recipyGui.config.get('tinydb'))

    if not query:
        runs = db.all()
    else:
        # Search run outputs using the query string
        runs = db.search(
            where('outputs').any(lambda x: listsearch(query, x)) |
            where('inputs').any(lambda x: listsearch(query, x)) |
            where('script').search(query) |
            where('notes').search(query) |
            where('unique_id').search(query))
    runs = sorted(runs, key = lambda x: parse(x['date'].replace('{TinyDate}:', '')) if x['date'] is not None else x['eid'], reverse=True)

    run_ids = []
    for run in runs:
        if 'notes' in run.keys():
            run['notes'] = str(escape(run['notes']))
        run_ids.append(run.eid)

    db.close()

    return render_template('list.html', runs=runs, query=query, form=form,
                           run_ids=str(run_ids),
                           dbfile=recipyGui.config.get('tinydb'))
Example #2
0
def getfeed(cid):
    postrec = []
    print "feed"
    for bid in msgtable.search(where ('customer_id') == cid):
        print bid
        postrec.append(posttable.search(where ('busid') == bid['busid']))
    return postrec
Example #3
0
    def match(self, field, table_name=None, regex=None, test=None):
        """Find records where `field` matches `regex` or `test`.
        
        Either `regex` or `test` may be specified, not both.  
        If `regex` is given, then all records with `field` matching the regular expression are returned.
        If test is given then all records with `field` set to a value that caues `test` to return True are returned. 
        If neither is given, return all records where `field` is set to any value. 
        
        Args:
            table_name (str): Name of the table to operate on.  See :any:`AbstractDatabase.table`.
            field (string): Name of the data field to match.
            regex (string): Regular expression string.
            test: Callable returning a boolean value.  

        Returns:
            list: Matching data records.
            
        Raises:
            ValueError: Invalid value for `keys`.
        """
        table = self.table(table_name)
        if test is not None:
            LOGGER.debug("%s: search(where(%s).test(%r))", table_name, field, test)
            return [self.Record(self, element=elem) for elem in table.search(tinydb.where(field).test(test))]
        elif regex is not None:
            LOGGER.debug("%s: search(where(%s).matches(%r))", table_name, field, regex)
            return [self.Record(self, element=elem) for elem in table.search(tinydb.where(field).matches(regex))]
        else:
            LOGGER.debug("%s: search(where(%s).matches('.*'))", table_name, field)
            return [self.Record(self, element=elem) for elem in table.search(tinydb.where(field).matches(".*"))]
Example #4
0
 def delete_driver_name_correction(self, year, name_incorrect, name_correct):
     corrections_table = self.get_db_connection().table('driver_name_corrections')
     corrections_table.remove(
         (where('season') == year) &
         (where('name_incorrect') == name_incorrect) &
         (where('name_correct') == name_correct)
     )
Example #5
0
def start():
    """Start monitoring the Indiegogo campaign.
    """
    # Retrieve the current campaign information
    campaign = get_campaign_info()
    CONFIGS['slug'] = campaign['slug']
    CONFIGS['campaign_id'] = campaign['id']
    CONFIGS['campaign_preview_url'] = campaign['preview_url']
    CONFIGS['campaign_thumbnail_image_url'] = campaign['thumbnail_image_url']
    # Initialize timestamps
    last_comment_ts = DB.search(where('type') == 'comment')
    if not last_comment_ts:
        DB.insert({'ts': 0, 'type': 'comment'})
    last_contrib_ts = DB.search(where('type') == 'contrib')
    if not last_contrib_ts:
        DB.insert({'ts': 0, 'type': 'contrib'})
    # Insert markers for each campaign goal
    goal = campaign['goal']
    funds = campaign['collected_funds']
    achieved = int(funds * 100 / goal)
    for i in [30, 70, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]:
        # notify at each achievement
        p = 'p' + str(i)
        marker = DB.search(where('type') == p)
        if not marker and achieved >= i:
            DB.insert({'ts': time.time(), 'type': p})
    update_interval = CONFIGS['update_interval']
    print "Start monitoring (CTRL-c to stop)..."
    try:
        while True:
            check_now()
            time.sleep(update_interval)
    except:
        pass
    print "Monitoring stopped."
Example #6
0
def test_smart_query_cache(db):
    db.table_class = SmartCacheTable
    table = db.table('table3')
    query = where('int') == 1
    dummy = where('int') == 2

    assert not table.search(query)
    assert not table.search(dummy)

    # Test insert
    table.insert({'int': 1})

    assert len(table._query_cache) == 2
    assert len(table._query_cache[query]) == 1

    # Test update
    table.update({'int': 2}, where('int') == 1)

    assert len(table._query_cache[dummy]) == 1
    assert table.count(query) == 0

    # Test remove
    table.insert({'int': 1})
    table.remove(where('int') == 1)

    assert table.count(where('int') == 1) == 0
Example #7
0
def print_month_usage(): 
    M = strftime("%m", NOW)
    Y = strftime("%y", NOW)
    month= raw_input("Month[{}]:".format(M)) or M
    year = raw_input("Year [{}]:".format(Y)) or Y
    assert(month)
    assert(year)
    R = DB.search((where('year') == year) & (where('month')==month))
    R.sort(key=lambda x: (x['mess'],x['host'],int(x['day']),["B","L","S","D"].index(x['session'])))
    messes = set([r['mess'] for r in R])
    hosts  = set([r['host'] for r in R])
    days   = set([r['day' ] for r in R]) 
    print ""
    print "Summary for month {}".format(month)
    for mess in messes:
        print "Mess : {}  ".format(mess),
        for host in hosts:
            print "Host : {}".format(host)
            for day in sorted(days, key=lambda x:int(x)):
                print "{:2s} ".format(day),
                D = [r for r in R if r['mess']==mess and r['host']==host and r['day']==day]
                D.sort(key=lambda x: (["B","L","S","D"].index(x['session'])))
                for d in D:
                    print d['session'],
                print ""
Example #8
0
    def scan(self):
        print "Scan Start"
        while True:
            cell = Cell.all(interface)
            print "Rescanning"
            timer = 0
            while timer < 100:
                timer +=1
                S = []
                count = 0
                for c in cell:
                    count += 1
                    #print ":"+ str(count), " ssid:", c.ssid
                        #create dictionary with informnation on the accesss point
                    SSIDS = {"no" : count ,"ssid": c.ssid, "channel":c.channel,"encrypted":c.encrypted, \
                                "frequency":c.frequency,"address":c.address, "signal":c.signal, "mode":c.mode}

                    #if not db.search((where('ssid') == ap["ssid"])) == []:
                   # res =  db.search(where('ssid') == c.ssid)
                    #print db.search(where('ssid') == c.ssid)
                    
                    print  "=----------------------------------"
                   # print  c.address
                    print "---------------------------------------"
                    if db.contains(where('ssid') == c.ssid):
                        print (db.contains((where('ssid') == c.ssid) & (where('address') == str(c.address))))
Example #9
0
def test_json_readwrite(tmpdir):
    """
    Regression test for issue #1
    """
    path = str(tmpdir.join('test.db'))

    # Create TinyDB instance
    db = TinyDB(path, storage=JSONStorage)

    item = {'name': 'A very long entry'}
    item2 = {'name': 'A short one'}

    get = lambda s: db.get(where('name') == s)

    db.insert(item)
    assert get('A very long entry') == item

    db.remove(where('name') == 'A very long entry')
    assert get('A very long entry') is None

    db.insert(item2)
    assert get('A short one') == item2

    db.remove(where('name') == 'A short one')
    assert get('A short one') is None
Example #10
0
def search(args):
  filename = args['<outputfile>']

  if args['--fuzzy']:
    results = db.search(where('outputs').any(lambda x: re.match(".+%s.+" % filename, x)))
  elif args['--regex']:
    results = db.search(where('outputs').any(lambda x: re.match(filename, x)))
  else:
    results = db.search(where('outputs').any(os.path.abspath(filename)))

  results = [_change_date(result) for result in results]

  # Sort the results
  results = sorted(results, key = lambda x: parse(x['date']))

  if len(results) == 0:
      print("No results found")
  else:
      if args['--all']:
          for r in results:
              print_result(r)
              print("-"*40)
      else:
          print_result(results[-1])
          if len(results) > 1:
              print("** Previous runs creating this output have been found. Run with --all to show. **")

          if args['--diff']:
            if 'diff' in results[-1]:
              print("\n\n")
              print(results[-1]['diff'])

  db.close()
Example #11
0
def test_search_path(db):
    assert not db._query_cache
    assert len(db.search(where('int'))) == 3
    assert len(db._query_cache) == 1

    assert len(db.search(where('asd'))) == 0
    assert len(db.search(where('int'))) == 3  # Query result from cache
 def update_document(self, field, new_val, doc_id):
     if type(new_val) is list:
         self._db.update(_update_entry_list(field, new_val), where('id') == doc_id)
     else:
         if type(new_val) is set:
             new_val = list(new_val)
         self._db.update({field: new_val}, where('id') == doc_id)
Example #13
0
def is_user_existent(name):
    field_existence = user_table.search(where('name').exists())
    if not field_existence:
        return False

    user_existence = user_table.search(where('name') == name)
    return True if len(user_existence) is 1 else False
Example #14
0
def main():
    if len(sys.argv) == 1 or sys.argv[1] == "proximity":
        pprint(db.search(tinydb.where('seen') >= int(time.time()) - 60*15))
    elif sys.argv[1] == "hostnames":
        pprint(db.search(tinydb.where('hostname')))
    else:
        print("Unknown debug command")
Example #15
0
def test_update(db):
    assert db.count(where('int') == 1) == 3

    db.update({'int': 2}, where('char') == 'a')

    assert db.count(where('int') == 2) == 1
    assert db.count(where('int') == 1) == 2
Example #16
0
def test_one_table(db):
    table1 = db.table('table1')

    table1.insert_multiple({'int': 1, 'char': c} for c in 'abc')

    assert table1.get(where('int') == 1)['char'] == 'a'
    assert table1.get(where('char') == 'b')['char'] == 'b'
Example #17
0
 def get_obj_by_brush_and_mtl(self, brush, mtl):
     if self.db.contains(
         (where("brush") == str(brush)) & (where("mtl") == str(mtl))
     ):
         return self.db.search(
             (where("brush") == str(brush)) & (where("mtl") == str(mtl))
         )[0]
Example #18
0
def test_write_back(db):
    docs = db.search(where('int') == 1)
    for doc in docs:
        doc['int'] = [1, 2, 3]

    db.write_back(docs)
    assert db.count(where('int') == [1, 2, 3]) == 3
Example #19
0
def ticket_detail(ticket_id):
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    else:
        if request.method == "GET":
            results = ticket_db.search(where("uuid") == ticket_id)
            action_url = request.path
            status = int(request.args.get("status", 10))
            if status < 0 or status > 3:
                pass
            else:
                t = ticket_db.get(where('uuid') == ticket_id)
                t["status"] = status
                ticket_db.update(t, eids=[t.eid])
            if len(results) == 0:
                abort(404)
            else:
                results[0]["text"].replace("\;", ";")
                return render_template("ticket_detail.html", details=results[0], actionurl=action_url)
        else:
            content = request.form["content"].replace("\n", "<br>")
            user = session.get("username")
            t = ticket_db.get(where('uuid') == ticket_id)
            if t["replies"] == None:
                t["replies"] = []
            t["replies"].append({"content" : content, "author": user})
            ticket_db.update(t, eids=[t.eid])
            return redirect(request.path)
Example #20
0
    def reference_energy(self, phase, symbols, param_search):
        """
        Returns the weighted average of the endmember energies
        in symbolic form.
        """
        # TODO: Handle wildcards in constituent array
        pure_energy_term = S.Zero
        # Normalize site ratios
        site_ratio_normalization = 0
        for idx, sublattice in enumerate(phase.constituents):
            # sublattices with only vacancies don't count
            if len(sublattice) == 1 and sublattice[0] == 'VA':
                continue
            site_ratio_normalization += phase.sublattices[idx]

        pure_param_query = (
            (where('phase_name') == phase.name) & \
            (where('parameter_order') == 0) & \
            (where('parameter_type') == "G") & \
            (where('constituent_array').test(self._purity_test))
        )

        pure_params = param_search(pure_param_query)

        for param in pure_params:
            site_fraction_product = S.One
            for subl_index, comp in enumerate(param['constituent_array']):
                # We know that comp has one entry, by filtering
                sitefrac = \
                    v.SiteFraction(phase.name, subl_index, comp[0])
                site_fraction_product *= sitefrac
            pure_energy_term += (
                site_fraction_product * param['parameter'].subs(symbols)
            ) / site_ratio_normalization
        return pure_energy_term
Example #21
0
def dislikepost(pid):
    l = posttable.search(where ('postid') == pid)
    if not l:
        return -1
    likes = l[0]['n_dislikes']
    likes = likes + 1
    posttable.update({'n_dislikes':likes}, where ('postid') == pid)
    return 0
Example #22
0
def confirm_user(username):
	usr = users.search(where('username') == username)
	if usr and (len(usr) == 1):
		if usr[0]["confirmed"] == 0:
			users.update(increment('confirmed'), where('username') == username)
			print("Confirmed value: " + str(usr[0]['confirmed']))
		return True
	return False
Example #23
0
def set_user_key(email, appid, data):
    id_ = data['id'] = email + ':' + appid
    users = _DBS['users']

    if users.contains(where('id') == id_):
        users.update(data, where('id') == id_)
    else:
        users.insert(data)
Example #24
0
def get_data(start, end):
    start = int(time.mktime(time.strptime(start, "%m/%d/%Y")))
    start = start/86400
    end = int(time.mktime(time.strptime(end, "%m/%d/%Y")))
    end = end/86400

    data = db.search((where('date') >= start) & (where('date') <= end))
    return data
Example #25
0
 def __init__(self, db_path):
     self.db = TinyDB(db_path, storage=UnicodeJSONStorage)
     # Words that were already translated.
     self.already_translated = self.db.search(
             where('translation') != None)
     # Words that were attempted to translate but failed.
     self.non_translated = self.db.search(
             where('translation') == None)
Example #26
0
def test_update(db):
    eid = db.insert({'x': 1})

    with transaction(db) as tr:
        tr.update({'x': 2}, where('x') == 1)
        tr.update({'x': 3}, eids=[eid])

    assert db.get(where('x') == 3).eid == eid
Example #27
0
 def insert_or_update_counter(self, count, original, date_str):
     counter = {'count': count, 'original': original, 'date': date_str}
     if self.db.search(
             (where('date') == date_str) & (where('original') == original)):
         log.info('Updating counter for %s into db', original)
         self.db.update(counter, where('date') == date_str)
     else:
         log.info('Inserting counter for %s into db', original)
         self.db.insert(counter)
Example #28
0
def addmsg(cid, bid, msg=None, ts=None):
    d = msgtable.search((where ('customer_id') == cid) & (where('busid') == bid))
    if not d:
        l = [(msg, ts)]
        msgtable.insert({'customer_id':cid, 'busid':bid, 'msg_id':l} )
    else:
	l = d[0]['msg_id']
	l.append([(msg, ts)])
        msgtable.update({'msg_id':l}, (where ('customer_id') == cid) & (where('busid') == bid))
Example #29
0
def test_caching(db):
    table1 = db.table('table1')
    table2 = db.table('table1')

    table1.insert({'int': 1, 'char': 'a'})
    table2.insert({'int': 1, 'char': 'b'})

    assert len(table1.search(where('int') == 1)) == 2
    assert len(table2.search(where('int') == 1)) == 2
Example #30
0
def test_database_parameter_with_species_that_is_not_a_stoichiometric_formula():
    """Species names used in parameters do not have to be stoichiometric formulas"""

    # names are taken from the Thermo-Calc documentation set, Database Manager Guide, SPECIES

    tdb_string = """
     ELEMENT /-   ELECTRON_GAS              0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT VA   VACUUM                    0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT O    1/2_MOLE_O2(G)            0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT SI   HCP_A3                    0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT NA   HCP_A3                    0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT SB   RHOMBOHEDRAL_A7           0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT H    1/2_MOLE_H2(G)            0.0000E+00  0.0000E+00  0.0000E+00!

     SPECIES SILICA                      SI1O2 !  $ tests for arbitrary names
     SPECIES NASB_6OH                    NA1SB1O6H6 !  $ tests for underscores
     SPECIES SB-3                        SB/-3 !  $ tests for charge
     SPECIES ALCL2OH.3WATER                        AL1O1H1CL2H6O3 !  $ tests for charge


     PHASE LIQUID:L %  1  1.0  !

     CONSTITUENT LIQUID:L : O, SI, NA, SB, H, SILICA, NASB_6OH, SB-3, ALCL2OH.3WATER  :  !
     PARAMETER G(LIQUID,SILICA;0)      298.15  10;      3000 N !
     PARAMETER G(LIQUID,NASB_6OH;0)    298.15  100;      3000 N !
     PARAMETER G(LIQUID,ALCL2OH.3WATER;0)    298.15  1000;      3000 N !
     PARAMETER G(LIQUID,SB-3;0)        298.15  10000;      3000 N !

     """

    dbf = Database.from_string(tdb_string, fmt='tdb')

    species_dict = {sp.name: sp for sp in dbf.species}
    species_names = list(species_dict.keys())

    # check that the species are found
    assert 'SILICA' in species_names
    assert 'NASB_6OH' in species_names
    assert 'ALCL2OH.3WATER' in species_names
    assert 'SB-3' in species_names

    import tinydb
    silica = dbf._parameters.search(tinydb.where('constituent_array') == ((species_dict['SILICA'],),))
    assert len(silica) == 1
    assert silica[0]['parameter'].args[0][0] == 10

    nasb_6oh = dbf._parameters.search(tinydb.where('constituent_array') == ((species_dict['NASB_6OH'],),))
    assert len(nasb_6oh) == 1
    assert nasb_6oh[0]['parameter'].args[0][0] == 100

    alcl2oh_3water = dbf._parameters.search(tinydb.where('constituent_array') == ((species_dict['ALCL2OH.3WATER'],),))
    assert len(alcl2oh_3water) == 1
    assert alcl2oh_3water[0]['parameter'].args[0][0] == 1000

    sbminus3 = dbf._parameters.search(tinydb.where('constituent_array') == ((species_dict['SB-3'],),))
    assert len(sbminus3) == 1
    assert sbminus3[0]['parameter'].args[0][0] == 10000
Example #31
0
def test_update_returns_ids(db: TinyDB):
    db.drop_tables()
    assert db.insert({'int': 1, 'char': 'a'}) == 1
    assert db.insert({'int': 1, 'char': 'a'}) == 2

    assert db.update({'char': 'b'}, where('int') == 1) == [1, 2]
Example #32
0
def isPlayerInQueue(player: Union[Member, str]) -> bool:
    if (isinstance(player, Member)):
        return currQueue.contains(where(BallChaserKey.ID) == player.id)
    elif (isinstance(player, str)):
        return currQueue.contains(
            where(BallChaserKey.ID) == currQueue.get(doc_id=int(player))["id"])
Example #33
0
def ag_call_with_rc(func,
                    *args,
                    expected_rc=None,
                    new_only=True,
                    headers=None,
                    no_cache=False,
                    **kwargs):
    """
    Wrap AGitHub calls with basic error detection and caching in TingDB

    Not smart, and hides any error information from caller.
    But very convenient. :)
    """
    if not headers:
        headers = {}
    add_media_types(headers)
    last = {}
    url = func.keywords["url"]
    doc = {"url": url}
    if new_only and last_table is not None:
        try:
            last = last_table.search(tinydb.where("url") == url)[0]["when"]
        except IndexError:
            pass
        # prefer last modified, as more readable, but neither guaranteed
        # https://developer.github.com/v3/#conditional-requests
        if "last-modified" in last:
            headers["If-Modified-Since"] = last["last-modified"]
        elif "etag" in last:
            headers["If-None-Match"] = last["etag"]
    # Insert our (possibly modified) headers
    real_headers = kwargs.setdefault("headers", {})
    real_headers.update(headers)

    if expected_rc is None:
        expected_rc = [200, 304]
    rc, body = retry_call(func, *args, **kwargs)
    # If we have new information, we want to use it (and store it unless
    # no_cache is true)
    # If we are told our existing info is ok, or there's an error, use the
    # stored info
    if rc == 200:
        doc["rc"] = rc
        doc["body"] = body
    elif rc in (202, 204, 304):
        logger.debug("can't handle {} for {}, using older data".format(
            rc, url))
        body = doc.get("body", [])
    # Handle repo rename/removal corner cases
    elif rc == 301:
        logger.error("Permanent Redirect for '{}'".format(url))
        # TODO: do something better, like switch to using id's
        # for now, act like nothing is there
        body = doc.get("body", [])
    elif rc == 404 and rc not in expected_rc:
        logger.debug("No longer available or access denied: {}".format(url))
        # TODO: Figure out what to do here. Maybe it's just that message, but
        # maybe need to delete from DB before next run
        body = doc.get("body", [])
        # don't throw on this one
        expected_rc.append(404)
    logger.debug("{} for {}".format(rc, url))
    if (not no_cache) and new_only and last_table is not None:
        h = {k.lower(): v for k, v in gh.getheaders()}
        for x in "etag", "last-modified":
            if x in h:
                last[x] = h[x]
        doc.update({"body": body, "rc": rc, "when": last})
        last_table.upsert(doc, tinydb.where("url") == url)

    # Ignore 204s here -- they come up for many "legit" reasons, such as
    # repositories with no code.
    if rc not in expected_rc + [204]:
        if DEBUG:
            import pudb

            pudb.set_trace()  # noqa: E702
        else:
            logger.error("{} for {}".format(rc, url))
            raise AG_Exception
    return rc, body
Example #34
0
 def update_router_db_from_tinydb(self, prams):
     self.router_db.update({'item': prams},
                           where('name') == self.router_name)
Example #35
0
def test_remove_multiple(db: TinyDB):
    db.remove(where('int') == 1)

    assert len(db) == 0
Example #36
0
def test_count(db: TinyDB):
    assert db.count(where('int') == 1) == 3
    assert db.count(where('char') == 'd') == 0
Example #37
0
def validateBluePick(player: Member) -> bool:
    player = currQueue.get(doc_id=player.id)
    if (player is not None):
        return (currQueue.count(where(BallChaserKey.TEAM) == Team.BLUE) == 1
                and player[BallChaserKey.IS_CAP]
                and player[BallChaserKey.TEAM] == Team.BLUE)
Example #38
0
def test_contains(db: TinyDB):
    assert db.contains(where('int') == 1)
    assert not db.contains(where('int') == 0)
Example #39
0
def getTeamList() -> Tuple[List[BallChaser], List[BallChaser]]:
    orangeTeam = currQueue.search(where(BallChaserKey.TEAM) == Team.ORANGE)
    blueTeam = currQueue.search(where(BallChaserKey.TEAM) == Team.BLUE)
    return [BallChaser.fromDocument(p) for p in blueTeam
            ], [BallChaser.fromDocument(p) for p in orangeTeam]
Example #40
0
def test_get_idempotent(db: TinyDB):
    u = db.get(where('int') == 1)
    z = db.get(where('int') == 1)
    assert u == z
Example #41
0
 def updatenormDB(self, user, address):
     db = TinyDB('UserDB.json')
     db.remove(where('user') == user)
     db.insert({'user': user, 'permission': address})
Example #42
0
 def __delitem__(self,key):
     if key in self:
         self._data.remove(tinydb.where(self._key) == key)
         self._length -= 1
Example #43
0
def test_update_all(db: TinyDB):
    assert db.count(where('int') == 1) == 3

    db.update({'newField': True})

    assert db.count(where('newField') == True) == 3  # noqa
Example #44
0
def test_remove_returns_ids(db: TinyDB):
    assert db.remove(where('char') == 'b') == [2]
Example #45
0
def test_get(db: TinyDB):
    item = db.get(where('char') == 'b')
    assert item['char'] == 'b'
Example #46
0
def test_remove(db: TinyDB):
    db.remove(where('char') == 'b')

    assert len(db) == 2
    assert db.count(where('int') == 1) == 2
Example #47
0
 def __contains__(self,key):
     with_key = self._data.search(tinydb.where(self._key) == key)
     return len(with_key) > 0
Example #48
0
def formatted_parameter(dbf, symbol, unique=True):
    """
    Get the deconstructed pretty parts of the parameter/term a symbol belongs to in a Database.

    Parameters
    ----------
    dbf : pycalphad.Database
    symbol : string or symengine.Symbol
        Symbol in the Database to get the parameter for.
    unique : bool
        If True, will raise if more than one parameter containing the symbol is found.


    Returns
    -------
    FormattedParameter
        A named tuple with the following attributes:
        ``phase_name``, ``interaction``, ``symbol``, ``term``, ``parameter_type``
        or ``term_symbol`` (which is just the Symbol * temperature term)
    """
    FormattedParameter = namedtuple('FormattedParameter', [
        'phase_name', 'interaction', 'symbol', 'term', 'parameter_type',
        'term_symbol'
    ])

    if not isinstance(symbol, Symbol):
        symbol = Symbol(symbol)
    search_res = dbf._parameters.search(
        where('parameter').test(lambda x: symbol in x.free_symbols))

    if len(search_res) == 0:
        raise ValueError(
            'Symbol {} not found in any parameters.'.format(symbol))
    elif (len(search_res) > 1) and unique:
        raise ValueError(
            'Parameters found containing Symbol {} are not unique. Found {}.'.
            format(symbol, search_res))

    formatted_parameters = []
    for result in search_res:
        const_array = formatted_constituent_array(result['constituent_array'])
        # format the paramter type to G or L0, L1, ...
        parameter_type = '{}{}'.format(result['parameter_type'],
                                       result['parameter_order'])
        # override non-interacting to G if there's no interaction
        has_interaction = ',' in const_array
        if not has_interaction:
            if (result['parameter_type'] == 'G') or (result['parameter_type']
                                                     == 'L'):
                parameter_type = 'G'

        term = parameter_term(result['parameter'], symbol)
        formatted_param = FormattedParameter(result['phase_name'], const_array,
                                             symbol, term, parameter_type,
                                             term * symbol)
        formatted_parameters.append(formatted_param)

    if unique:
        return formatted_parameters[0]
    else:
        return formatted_parameters
Example #49
0
def getQueueLength() -> int:
    return currQueue.count(where(BallChaserKey.ID).exists())
Example #50
0
def test_search(db: TinyDB):
    assert not db._query_cache
    assert len(db.search(where('int') == 1)) == 3

    assert len(db._query_cache) == 1
    assert len(db.search(where('int') == 1)) == 3  # Query result from cache
Example #51
0
def test_update_ids(db: TinyDB):
    db.update({'int': 2}, doc_ids=[1, 2])

    assert db.count(where('int') == 2) == 2
Example #52
0
def test_search_no_results_cache(db: TinyDB):
    assert len(db.search(where('missing'))) == 0
    assert len(db.search(where('missing'))) == 0
Example #53
0
def getAvailablePicks() -> List[BallChaser]:
    availablePicks = []
    for player in currQueue.search(where(BallChaserKey.TEAM) == None):
        availablePicks.append(BallChaser.fromDocument(player))
    return availablePicks
Example #54
0
    def connected_devices_arp(self, run_test):
        """
        Method counts the number of active devices on the network.

        """

        if not run_test:
            return

        ts = int(time.time())

        route_cmd = "ip r | grep /24 | awk '{print $1;}'"
        subnet = Popen(route_cmd, shell=True,
                       stdout=PIPE).stdout.read().decode('utf-8')

        nmap_cmd = f'nmap -sn {subnet}'
        Popen(nmap_cmd, shell=True, stdout=PIPE)

        arp_cmd = ("/usr/sbin/arp -i eth0 -n | grep : |"
                   "grep -v '_gateway' | tr -s ' ' | "
                   "cut -f3 -d' ' | sort | uniq")

        arp_res = Popen(arp_cmd, shell=True,
                        stdout=PIPE).stdout.read().decode('utf-8')

        devices = set(arp_res.strip().split("\n"))
        active_devices = [[dev, ts, 1] for dev in devices]

        for device in active_devices:
            if self.dev_db.contains(where('mac_addr') == device[0]):
                self.dev_db.update(increment("n"),
                                   where('mac_addr') == device[0])
                self.dev_db.update(tdb_set('last_seen', device[1]),
                                   where('mac_addr') == device[0])
            else:
                self.dev_db.insert({'mac_addr': device[0],
                                    'last_seen': device[1],
                                    'n': device[2]})

        print(self.dev_db.all())
        ndev_past_day = len(self.dev_db.search(
            where('last_seen') > (ts - 86400)))
        ndev_past_week = len(self.dev_db.search(
            where('last_seen') > (ts - 86400*7)))

        print(ndev_past_day)
        self.results["devices_active"] = len(active_devices)
        self.results["devices_total"] = self.dev_db.count(where('n') >= 1)
        self.results["devices_1day"] = ndev_past_day
        self.results["devices_1week"] = ndev_past_week

        if not self.quiet:
            print('\n --- Number of Devices ---')
            print(f'Number of active devices: '
                  f'{self.results["devices_active"]}')
            print(f'Number of total devices: '
                  f'{self.results["devices_total"]}')
            print(f'Number of devices in last 1 day:'
                  f' {self.results["devices_1day"]}')
            print(f'Number of devices in last week:'
                  f' {self.results["devices_1week"]}')
Example #55
0
def queueAlreadyPopped() -> bool:
    return currQueue.contains(where(BallChaserKey.IS_CAP) == True)
Example #56
0
def test_update_returns_ids(db):
    db.purge()
    assert db.insert({'int': 1, 'char': 'a'}) == 1
    assert db.insert({'int': 1, 'char': 'a'}) == 2

    assert db.update({'char': 'b'}, where('int') == 1) == [1, 2]
Example #57
0
def test_database_parameter_with_species_that_is_not_a_stoichiometric_formula(
):
    """Species names used in parameters do not have to be stoichiometric formulas"""

    # names are taken from the Thermo-Calc documentation set, Database Manager Guide, SPECIES

    tdb_string = """
     ELEMENT /-   ELECTRON_GAS              0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT VA   VACUUM                    0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT O    1/2_MOLE_O2(G)            0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT SI   HCP_A3                    0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT NA   HCP_A3                    0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT SB   RHOMBOHEDRAL_A7           0.0000E+00  0.0000E+00  0.0000E+00!
     ELEMENT H    1/2_MOLE_H2(G)            0.0000E+00  0.0000E+00  0.0000E+00!

     SPECIES SILICA                      SI1O2 !  $ tests for arbitrary names
     SPECIES NASB_6OH                    NA1SB1O6H6 !  $ tests for underscores
     SPECIES SB-3                        SB/-3 !  $ tests for charge
     SPECIES ALCL2OH.3WATER                        AL1O1H1CL2H6O3 !  $ tests for charge


     PHASE LIQUID:L %  1  1.0  !

     CONSTITUENT LIQUID:L : O, SI, NA, SB, H, SILICA, NASB_6OH, SB-3, ALCL2OH.3WATER  :  !
     PARAMETER G(LIQUID,SILICA;0)      298.15  10;      3000 N !
     PARAMETER G(LIQUID,NASB_6OH;0)    298.15  100;      3000 N !
     PARAMETER G(LIQUID,ALCL2OH.3WATER;0)    298.15  1000;      3000 N !
     PARAMETER G(LIQUID,SB-3;0)        298.15  10000;      3000 N !

     """

    dbf = Database.from_string(tdb_string, fmt='tdb')

    species_dict = {sp.name: sp for sp in dbf.species}
    species_names = list(species_dict.keys())

    # check that the species are found
    assert 'SILICA' in species_names
    assert 'NASB_6OH' in species_names
    assert 'ALCL2OH.3WATER' in species_names
    assert 'SB-3' in species_names

    import tinydb
    silica = dbf._parameters.search(
        tinydb.where('constituent_array') == ((species_dict['SILICA'], ), ))
    assert len(silica) == 1
    assert silica[0]['parameter'].args[0] == float(10)

    nasb_6oh = dbf._parameters.search(
        tinydb.where('constituent_array') == ((species_dict['NASB_6OH'], ), ))
    assert len(nasb_6oh) == 1
    assert nasb_6oh[0]['parameter'].args[0] == float(100)

    alcl2oh_3water = dbf._parameters.search(
        tinydb.where('constituent_array') == ((
            species_dict['ALCL2OH.3WATER'], ), ))
    assert len(alcl2oh_3water) == 1
    assert alcl2oh_3water[0]['parameter'].args[0] == float(1000)

    sbminus3 = dbf._parameters.search(
        tinydb.where('constituent_array') == ((species_dict['SB-3'], ), ))
    assert len(sbminus3) == 1
    assert sbminus3[0]['parameter'].args[0] == float(10000)