示例#1
0
#!/usr/bin/python
import config, store, os
standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py')
c = config.Config("config.ini")
s = store.Store(c)
cursor = s.get_cursor()
cursor.execute(
    "lock table sshkeys in exclusive mode")  # to prevent simultaneous updates
cursor.execute(
    "select u.name,s.key from users u, sshkeys s where u.name=s.name")
lines = []
for name, key in cursor.fetchall():
    lines.append(
        'command="%s -r %s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s\n'
        % (standalone_py, name, key))
f = open('.ssh/authorized_keys', 'wb')
f.write(''.join(lines))
f.close()
s.rollback()
示例#2
0
# SENSEI BONUS: Update the product class to give each product a unique id.
#               Update the sell_product method to accept the unique id.

import store

store_165 = store.Store("Castle Rock")
store_165.show_products()
store_165.add_product("Shovel", 35.50, "Garden Supplies")
store_165.add_product("Rake", 15.50, "Garden Supplies")
store_165.add_product("Lawn Sprinkler", 25.50, "Garden Supplies")
store_165.show_products()
store_165.sell_product(1)
store_165.show_products()
store_165.inflation(.10)
store_165.show_products()
store_165.set_clearance("Garden Supplies", 0.10)
store_165.show_products()
示例#3
0
    if action == LOCK:
        if choice == 1:
            register1.lockOn()
        elif choice == 2:
            register2.lockOn()
            
    elif action == UNLOCK:
        if choice == 1:
            register1.lockOff()
        elif choice == 2:
            register2.lockOff()


###############################################################################
if __name__ == '__main__':
    store1 = store.Store() #create the store1 object
    store1.OpenShop() #set the store attribute to open
    
    print("The store is now open. Initializing the registers...")
    register1 = cashRegister.CashRegister() #create both register objects
    register2 = cashRegister.CashRegister()
    
    register1.lockOff() #unlock both registers
    register2.lockOff()
    
    #initialize lists, will be turned into list of the number of each bills, in 
    #order ones, fives, tens, twenties
    bills1 = [] 
    bills2 = []
    
    #user inputs initial values for each register, and method createList places 
示例#4
0
__author__ = 'Matt'

import store
import database

# create store and add customers to list
better_buy = store.Store()
menu = store.Menu()
# name = menu.sign_up()
# print (name)
# # name1 = raw_input("what is your name? ")
# # # customer1 = store.Customer(11, name1)
# matt = database.Customer(name=name[0], email=name[1], password=name[2])
# matt.save()

# for customer in database.Customer:
#     print customer.name, customer.email
# customer2 = store.Customer(22, 'Ashley')
# better_buy.list_of_customers.append(customer1)
# menu.sign_up()
# print menu.customer
menu.show_customers()
menu.login()

# create list of inventory
laptop = store.InventoryItem(111, 'Laptop', 699.99)
tv = store.InventoryItem(222, 'TV', 1499.99)
xbox = store.InventoryItem(333, 'Xbox One', 349.99)
better_buy.available_inventory = [laptop, tv, xbox]
print(better_buy.available_inventory)
示例#5
0
import store
import product

my_supermarket = store.Store("My Handpicked Store")
my_supermarket.add_product(product.Product("Gala Apple", 4.99, "Fresh Fruits"))
my_supermarket.add_product(product.Product("Hot pickels", 3.65, "Canned"))
my_supermarket.add_product(
    product.Product("Theo's patties", 7.18, "Ground meat"))
my_supermarket.add_product(product.Product("French Bread", 1.05, "Breads"))

for item in my_supermarket.products:
    item.print_info()
示例#6
0
 def initialize(self):
     self.store = store.Store("hub/live")
示例#7
0
 def setUp(self):
     store.StoreDatabase.load()
     self.store = store.Store()
     self.store.id = 3
     self.store.name = "Walmart Grocery"
     self.store.available_items = [40, 43, 45, 47]
示例#8
0
 def __init__(self, app):
     self.ui = food_edit_dlg_ui.FoodEditDlgUI()
     self.ui.dialog.connect('response', self.on_response)
     self.app = app
     self.store = store.Store()
示例#9
0
 def setUp(self):
     self.store = store.Store()
示例#10
0
import store
import product


if __name__ == "__main__":
    item1 = product.Product(10,"cat toy",5,"Fisher", 5)
    item2 = product.Product(20,"leash",2,"doge", 2)
    item2.return_item("like new")
    item2.displayInfo()
    print item1.add_tax(0.18)

    target = store.Store([item1, item2],"Mountain View", "Mr. T")
    target.inventory()

  

   # print target
    # exercise for tomorrow -- if we sell an item from the store, we should have the product "sold" and remove from the store's inventory
    
示例#11
0
import product
import store

if __name__ == "__main__":
    shoe = product.Product("tennis shoe", 30, 5, "Nike")
    walmart = store.Store([shoe],"Chicago","Chris Poche")
    walmart.inventory()
    ## product.shoe2.display() -- doesn't work because of namespace check
示例#12
0
        def ping(self):
            raise MySQLdb.OperationalError

    conn = DummyDB()

    # Shut down the server so it can restart afresh next time.
    globalAppServer.running = 0

lucenepath = globalAppServer.serverSidePath('Lucene')
db = metadb.DB(conn, os.path.isdir(lucenepath) and lucenepath or None)
coll = Collection(db)

users = store.Store(
    conn, *'''user name opening_facet_terms
    opening_facet_columns opening_term_columns remember facets attrs
    facet_column_width item_column_width endgame_item_col_width
    endgame_facet_col_width sortby caps display_opening_option
    display_middle_option display_end_option managegame_opening
    showpreviews password email completed_tasks available_tasks'''.split())
user_histories = store.Store(
    conn, *'''user_history id userid item
    itemidx timestamp favorites groupid user'''.split())
user_history_groups = store.Store(
    conn, *'''
    user_history_groups id groupname userid timestamp user'''.split())
user_history_searches = store.Store(
    conn, *'''user_history_searches
    searchname id userid timestamp query facetgroup sort user'''.split())

tasks = store.Store(conn, 'tasks', 'id', 'description')
tasks_questions = store.Store(
示例#13
0
import select
import socket
import datetime
import argparse
import store
import json

from command import Command

# Global key-value store
STORE = store.Store()


class Server(object):
    """
    TCP server for handling client connections
    """
    def __init__(self):
        # Line ending which is appended to the message when response to client
        self.le = "\n"
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setblocking(0)
        # Sockets from which we expect to read
        self.inputs = [self.server]

    def send_msg(self, connection, msg):
        """
        Send JSON encoded message to client connection

        :param connection: Client socket
        :param msg: Data to send
示例#14
0

product1 = product.Product(1500.00, "BigScreen TV", 55, "LG", 1200.00, 'new')
product2 = product.Product(700.00, "iPhone6S", 1, "Apple", 400.00, 'new')
product3 = product.Product(400.00, "iPhone5", 1, "Apple", 200.00, 'used')
product4 = product.Product(450.00, "XBox", 35, "MS", 35, 'new')
product5 = product.Product(250.00, "wii", 15, "EA", 50, "like new")
product6 = product.Product(350.00, "PlayStation", 22, "Sony", 20, "defective")

product1.displayinfo()
#product2.displayinfo()
#product3.displayinfo()

prods1 = (product1, product2)

Store1 = store.Store("Best Buy", "Best Guy")
Store1.add_product(prods1)
Store1.inventory()
Store1.remove_product(prods1)
Store1.inventory()

prods2 = (product4, product5)
Store2 = store.Store("Phil's Electronic Stuff", "Phil Filbert")
Store2.add_product("product4")
Store2.add_product("product5")
Store2.add_product("product6")
Store2.inventory()
Store2.remove_product(product4)
Store2.inventory()

#product1.sell()
示例#15
0
 def store(self, guid=None, entryid=None):
     """Return :class:`store <Store>` with given GUID."""
     if _unicode(guid).split('@')[0] == 'public':
         return self._pubstore(guid)
     else:
         return _store.Store(guid=guid, entryid=entryid, server=self)
import product
import store

zapatos = product.Product("Nike Shoes", 300, "shoes")
zapatos2 = product.Product("Sandals", 50, "shoes")
shirt = product.Product("Shirt", 50, "clothing")

zapatos.update_price(10, False)
print(zapatos.prod_id)
print(zapatos2.prod_id)
print(shirt.prod_id)

my_store = store.Store("MegaShoes")
my_store.add_product(zapatos, 3)
my_store.add_product(shirt, 1)
my_store.add_product(zapatos2, 5)

my_store.update_product(1, 3)
my_store.sell_product(1, 7)

my_store.inflation(10)
my_store.set_clearance("shoes", 50)
示例#17
0
#!/usr/bin/python
import sys, os, urllib

root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root)
# Work around http://sourceforge.net/p/docutils/bugs/214/
import docutils.utils
import admin, store, config

cfg = config.Config(root+'/config.ini')
st = store.Store(cfg)

# Demo data starts here

# an admin
otk = st.store_user('fred', 'fredpw', '*****@*****.**')
st.delete_otk(otk)
st.add_role('fred', 'Admin', None)
# an owner
otk = st.store_user('barney', 'barneypw', '*****@*****.**')
st.delete_otk(otk)

# package spam
st.set_user('barney', '127.0.0.1', True)
for version in ('0.8', '0.9', '1.0'):
    st.store_package('spam', version, {
            'author':'Barney Geroellheimer',
            'author_email':'*****@*****.**',
            'homepage':'http://spam.python.test/',
            'license':'GPL',
            'summary':'The spam package',
示例#18
0
import store

zuh_shop = store.Store("Zuhayr's Odds and Ends")

print("")
print("Testing add product")

zuh_shop.add_product("table", 200, "furniture")
zuh_shop.add_product("chair", 50, "furniture")
zuh_shop.add_product("lamp", 25, "lights")
zuh_shop.add_product("flashlight", 5, "lights")
zuh_shop.add_product("apple", 1, "food")
zuh_shop.add_product("golden apple", 100, "food")

print("")

zuh_shop.list_products()

print("")
print("Testing sell product")
print("")

zuh_shop.sell_product("lamp")
zuh_shop.sell_product("flashlight")
zuh_shop.sell_product("pineapple")

print("")

zuh_shop.list_products()
zuh_shop.add_product("lamp", 25, "lights").add_product("flashlight", 5,
                                                       "lights")
示例#19
0
            elif path.endswith('.tar.gz'):
                z = gzip.GzipFile(path)
                t = tarfile.TarFile(fileobj=z)
                for i in t.getmembers():
                    if not i.name.endswith('.py'): continue
                    f = t.extractfile(i.name)
                    if 'def print_lol' in f.read():
                        hits[name] = summary
    for name in hits:
        store.remove_package(name)
        print '%s: %s' % (name, hits[name])
    print 'removed %d packages' % len(hits)

if __name__ == '__main__':
    config = config.Config('/data/pypi/config.ini')
    st = store.Store(config)
    st.open()
    command = sys.argv[1]
    args = (st, ) + tuple(sys.argv[2:])
    try:
        if command == 'password':
            set_password(*args)
        elif command == 'rmpackage':
            remove_package(*args)
        elif command == 'addclass':
            add_classifier(*args)
            print 'done'
        elif command == 'addowner':
            add_owner(*args)
        elif command == 'delowner':
            delete_owner(*args)
示例#20
0
if __name__ == "__main__":
    op = OptionParser()

    op.add_option("-p", "--port", action="store", type=int, default=8080)
    op.add_option(
        "-s",
        "--store",
        action="store",
    )
    op.add_option("-l", "--log", action="store", default=None)
    (opts, args) = op.parse_args()
    logging.basicConfig(filename=opts.log,
                        level=logging.INFO,
                        format='[%(asctime)s] %(levelname).1s %(message)s',
                        datefmt='%Y.%m.%d %H:%M:%S')

    store_addr, store_port = opts.store.split(':')
    MainHTTPHandler.store = store.Store(store_addr, store_port)

    server = HTTPServer(("localhost", opts.port), MainHTTPHandler)

    logging.info("Starting server at %s" % opts.port)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    except Exception as e:
        logging.exception("Server is shutting down, error: {}".format(e))
    server.server_close()
示例#21
0
import store
import product

s = store.Store("test store")

p1 = product.Product("T-shirt", 2.5, "Appraisal")
p2 = product.Product("Jeans", 5.6, "Appraisal")
p3 = product.Product("Bread", 0.95, "Food")

s.add_product(p1).add_product(p2).add_product(p3)

s.sell_product(p1.get_id())
s.inflation(.2)
s.set_clearance("Appraisal", .3)
示例#22
0
        queue = rq.Queue(connection=queue_redis)
    else:
        queue = None

    s3conn = boto.s3.connect_to_region(
        "us-west-2",
        aws_access_key_id=config.database_aws_access_key_id,
        aws_secret_access_key=config.database_aws_secret_access_key,
    )

    package_bucket = s3conn.get_bucket(
        config.database_files_bucket,
        validate=False,
    )

    st = store.Store(config, queue=queue, package_bucket=package_bucket)
    st.open()
    command = sys.argv[1]
    args = (st, ) + tuple(sys.argv[2:])
    try:
        if command == 'password':
            set_password(*args)
        elif command == 'rmpackage':
            remove_package(*args)
        elif command == 'rmspam':
            remove_spam(*args)
        elif command == 'rmspammer':
            remove_spammer(*args)
        elif command == 'addclass':
            add_classifier(*args)
            print 'done'
示例#23
0
import requests

import config
import store
from pkg_resources import safe_name

CONFIG_FILE = os.environ.get("PYPI_CONFIG", os.path.join(prefix, 'config.ini'))

conf = config.Config(CONFIG_FILE)

if conf.database_releases_index_name is None or conf.database_releases_index_url is None:
    sys.exit()

new_index = "%s-%s" % (conf.database_releases_index_name, int(time.time()))
print("creating new index %s" % (new_index, ))
store = store.Store(conf)
store.open()

cursor = store._conn.cursor(cursor_factory=RealDictCursor)

cursor.execute(
    "BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE")
cursor.execute("SET statement_timeout = '600s'")
cursor.execute(
    "SELECT DISTINCT ON (name, _pypi_hidden) name, version, _pypi_ordering, _pypi_hidden, author, author_email, maintainer, maintainer_email, home_page, license, summary, description, keywords, platform, download_url FROM releases ORDER BY name, _pypi_hidden, _pypi_ordering DESC"
)
while True:
    releases = cursor.fetchmany(10000)
    if len(releases) == 0:
        break
    operations = []
 def __init__(self, app):
     self.app = app
     self.db = database.Database()
     self.store = store.Store()
     self.ui = recipe_srch_res_dlg_ui.RecipeSrchResDlgUI()
     self.connect_signals()
示例#25
0
import store
import product

costco = store.Store("Costco")
tp = product.Product("toilet paper", 10, "essentials")
flour = product.Product("flour", 15, "essentials")
beer = product.Product("beer", 30, "essentials")

costco.addProducts(tp).addProducts(flour).addProducts(beer)

costco.sellProduct(tp.id)
costco.sellProduct(5)

beer.inflation(.2)
print(beer.printInfo())

costco.setClearance("essentials", .5)
示例#26
0
import store
import products

our_store = store.Store()
cloths = products.Products('cloths', 10, 0, 12)
home = products.Products('home', 20, 1, 8)
shoes = products.Products('shoes', 50, 2, 9)

our_store.add_product(cloths)
our_store.add_product(home)
our_store.add_product(shoes)

our_store.list_products()
示例#27
0
 def __init__(self, desk):
     super(OrientLayout, self).__init__(desk)
     self.store = store.Store()
     self.proportion = 0.5
示例#28
0
 def admin_store(self):
     if not self._admin_store:
         self._admin_store = _store.Store(mapiobj=self.mapistore, server=self)
     return self._admin_store
示例#29
0
    def __init__(self, options, create=True, existing=None):

        self.provider = ida.IDA()

        if create:
            # create the DB
            print "[*] db.py: Creating a new DB file"

            db = store.sqlite3.connect(options['full_file_name'])
            #db.isolation_level =
            self.db_obj = db

            store.driver.sqlite.Deploy(db).create()

            # mutes the pesky sqlite messages
            tmp = sys.stderr 
            sys.stderr = StringIO()
            session = store.driver.sqlite.Session(db,0)
            my_store = store.Store(session)
            sys.stderr = tmp

            all_funcs = database.functions()
            opt = {}
            opt['database'] = my_store

            self.store = my_store

            proc = self.provider.getArch()

            if proc == "pc":
                # XXX: hackish way to fix a crap ton of stuff...
                start = self.provider.segByBase(self.provider.segByName(".text"))
                end = self.provider.segEnd(self.provider.segByBase(self.provider.segByName(".text")))

                succeeded = 0
                for instr in self.provider.iterInstructions(start, end):
                    disasm = self.provider.getDisasm(instr)
                    tokens = disasm.split(" ")

                    res = []
                    for t in tokens:
                        if len(t) != 0:
                            res.append(t)

                    prologues = [['mov', 'edi,', 'edi'], ['push', 'ebp'], ['push', 'rbp']]

                    if res in prologues and instr not in all_funcs:
                        try:
                            prev_ea = self.provider.prevItem(instr, instr-0x20)
                            if prev_ea not in all_funcs:
                                if options['verbosity'] > 2:
                                    print "[!] Attempting to create a function at 0x%08x" % instr
                                ret = self.provider.makeFunc(instr)
                            else:
                                continue

                            if ret:
                                if options['verbosity'] > 2:
                                    print "[*] Successfully made new function at 0x%08x" % instr
                                succeeded += 1

                        except Exception as detail:
                            print detail
                            pass

                    elif "dup(90h)" in disasm:
                        if options['verbosity'] > 2:
                            print "Found dup at 0x%08x" % instr
                        try:
                            next_ea = self.provider.nextItem(instr, instr+0x20)

                            if next_ea not in all_funcs:
                                ret = self.provider.nextItem(next_ea, 0xFFFFFFFF)
                            else:
                                continue

                            if not ret and (next_ea in database.functions()) :
                                if options['verbosity'] > 2:
                                    print "[*] Successfully made new function at 0x%08x" % next_ea
                                succeeded += 1
                        except:
                            pass
                   
                if succeeded != 0:
                    print "[*] Successfully created %d new functions" % succeeded

            print "[*] There are %d funtions to process" % len(all_funcs)

            failed = 0
            succeeded = 0

            for i in xrange(0, len(all_funcs)):
    
                i_actual = i+1
                ea = all_funcs[i]
                if ((i_actual % 250 == 0) or (i == len(all_funcs)-1)):
                    print "[*] db.py: Processing 0x%08x (%d of %d)" % (ea, i_actual, len(all_funcs))

                analyza = analyze_xrefs(opt)
                collecta = collector(analyza, opt)

                try:
                    collecta.go(ea)
                    succeeded += 1
                
                except ValueError as detail:
                    failed += 1
                    if options['verbosity'] > 2:
                        print "0x%08x - failed to process node, %s" % (ea, detail)
                    
                opt['database'].commit()
            
            print "[*] Failed to process %d functions" % failed
            print "[*] Successfully processed %d functions" % succeeded

            # now loop imports
            segs = list(self.provider.getSegments())

            if proc in ["arm", "ppc", "mips"]:
                idata = "extern"
            elif proc == "pc":
                idata = ".idata"

            for s in segs:
                if self.provider.segName(s) == idata:
                    start = s
                    end = self.provider.segEnd(s)

                    for head in self.provider.iterData(start, end):
                        opt['database'].address(head)['name'] = self.provider.getName(head)

                        xrefs_to = database.cxup(head)

                        for x in xrefs_to:
                            try:
                                xref_top = function.top(x)
                            except ValueError: 
                                continue
                            context = opt['database'].c(xref_top)
                            context.address(x).edge((head, head))
            self.commit()


        else:
            db = store.sqlite3.connect(options['full_file_name'])
            self.db_obj = db

            # mutes the pesky sqlite messages
            tmp = sys.stderr
            sys.stderr = StringIO()
            session = store.driver.sqlite.Session(db,0)
            sys.stderr = tmp

            my_store = store.Store(session)
            self.store = my_store
示例#30
0
    config = config.Config(CONFIG_FILE)

    if config.queue_redis_url:
        queue_redis = redis.Redis.from_url(config.queue_redis_url)
        queue = rq.Queue(connection=queue_redis)
    else:
        queue = None

    package_fs = fs.multifs.MultiFS()
    package_fs.addfs(
        "local",
        fs.osfs.OSFS(config.database_files_dir),
        write=True,
    )

    st = store.Store(config, queue=queue, package_fs=package_fs)
    st.open()
    command = sys.argv[1]
    args = (st, ) + tuple(sys.argv[2:])
    try:
        if command == 'password':
            set_password(*args)
        elif command == 'rmpackage':
            remove_package(*args)
        elif command == 'rmspam':
            remove_spam(*args)
        elif command == 'rmspammer':
            remove_spammer(*args)
        elif command == 'addclass':
            add_classifier(*args)
            print 'done'