Пример #1
0
 def create_on_device(self):
     params = self.want.api_params()
     import q
     q.q(params)
     self.client.api.tm.cm.add_to_trust.exec_cmd('run',
                                                 name='Root',
                                                 **params)
Пример #2
0
 def __init__(self, *args, **kwargs):
     self._values = defaultdict(lambda: None)
     self._values['__warnings'] = []
     params = kwargs.get('params', None)
     q.q(params)
     if params:
         self.update(params)
Пример #3
0
 def create_on_device(self):
     params = self.want.api_params()
     import q
     q.q(params)
     resource = self.client.api.tm.ltm.rules.rule
     resource.create(name=self.want.name,
                     partition=self.want.partition,
                     **params)
Пример #4
0
 def _device_is_rebooting(self):
     command = dict(command="tmsh run /util bash -c 'runlevel'")
     result = run_commands(self.module, command)
     import q
     q.q(result)
     if any(x for x in result if '6' in x):
         return True
     return False
Пример #5
0
 def _is_mprov_running_on_device(self):
     command = dict(
         command="tmsh run /util bash -c 'ps aux | grep \'[m]prov\''")
     result = run_commands(self.module, command)
     import q
     q.q(result)
     if any(x for x in result if len(x) > 1):
         return True
     return False
Пример #6
0
def setup(bot):
    bot.config.define_section('defcon', DefconSection)
    try:
        fn = os.path.join(bot.config.core.homedir, 'defcon_nowarn_users.cfg')
        with open(fn, 'r') as f:
            bot.config.defcon.nowarn_users = set(f.read())
            import q; q.q(bot.config.defcon.nowarn_users)
    except FileNotFoundError:
        bot.config.defcon.nowarn_users = set()
Пример #7
0
    def v2_runner_on_ok(self, result):
        templar = Templar(loader=self.playbook.get_loader(),
                          shared_loader_obj=SharedPluginLoaderObj(),
                          variables=self._all_vars(host=result._host,
                                                   task=result._task))

        import q
        result._task.squash()
        foo = templar.template(result._task._attributes['environment'])
        q.q(foo)
Пример #8
0
 def cb(cb_f):
     e = cb_f.exception()
     if e:
         exc_callback(e)
     if ENABLE_LOG:
         now = time.time()
         t = _queueLog[queue_name][func]
         _queueLog[queue_name][func] = (t[0], t[1], "done", time.time(), e,
                                        "elapsed", now - t[1])
         q.q(qstatsf())
Пример #9
0
 def compare_to_active(self, other, differences):
     for k in self.__dict__:
         if k in ('advertise_addr', 'listen_addr', 'rotate_worker_token', 'rotate_manager_token', 'spec'):
             continue
         if self.__dict__[k] is None:
             continue
         if self.__dict__[k] != other.__dict__[k]:
             differences.add(k, parameter=self.__dict__[k], active=other.__dict__[k])
             import q
             q.q(k, self.__dict__[k], other.__dict__[k])
     return differences
Пример #10
0
	def test_q_Basic(self):
		import q

		@q.t
		def test(arg):
			return 'RetVal'

		q.q('Test message')
		self.assertEqual('RetVal', test('foo'))
		self.assertTrue(os.path.exists('/tmp/q'))
		self.assertIn('Test message', open('/tmp/q', 'r').read())
		self.assertIn('foo', open('/tmp/q', 'r').read())
		self.assertIn('RetVal', open('/tmp/q', 'r').read())
Пример #11
0
def acmd(ip):
    ip = ip.strip(' ')
    if ip == 'exit' or ip == 'quit' or ip == 'q':
        q.q()
        return 'ok'
    elif ip == 'c' or ip == 'clear':
        c.c()
        return 'ok'
    elif ip == '':
        return 'ok'
    elif ip.startswith('os') == True:
        command.runCmd(ip)
        return 'ok'

    else:
        return 'err_0001'
Пример #12
0
def bdt_int2(x, snr_per_bit, M):
    E = 1
    Eb = E / np.log2(M)
    sgma = Eb * np.sqrt(np.log2(M) / (2 * snr_per_bit))

    return (1 - 2 * q(x / sgma))**(M / 2 - 1) * (
        1 / (np.sqrt(2 * np.pi) * sgma)) * np.exp(-(x - E)**2 / (2 * sgma**2))
Пример #13
0
def p_e_hd_a(gamma_db_l, gamma_db_h, k, n, d_min):  # 10,16,11,15,3
    gamma_db = np.arange(gamma_db_l,
                         gamma_db_h + (gamma_db_h - gamma_db_l) / 40,
                         (gamma_db_h - gamma_db_l) / 20)
    gamma_b = 10**(gamma_db / 10)
    R_c = k / n
    p_b = q(np.sqrt(2**R_c * gamma_b))
    p_err = (2**k - 1) * (4 * p_b * (1 - p_b))**(d_min / 2)
    return p_err, gamma_db
Пример #14
0
def p_e_sd_o(gamma_db_l, gamma_db_h, k, n, d_min):
    gamma_db = np.arange(gamma_db_l,
                         gamma_db_h + (gamma_db_h - gamma_db_l) / 40,
                         (gamma_db_h - gamma_db_l) / 20)
    gamma_b = 10**(gamma_db / 10)
    R_c = k / n

    p_err = (2**k - 1) * q(np.sqrt(d_min * R_c * gamma_b / 2))
    return p_err, gamma_db
Пример #15
0
def verifyCode(code, account):
    qconn = q.q(host=config.Q_HOST, port=config.Q_PORT, user=config.Q_USER)
    sql = 'verifyCode[`%s;"%s"]' % (code, account)
    try:
        res = bool(qconn.k(str(sql)))
    except:
        res = False
        logger.error(traceback.format_exc())
        logger.error(sql)
    qconn.close()
    return res
Пример #16
0
def genCode(account):
    qconn = q.q(host=config.Q_HOST, port=config.Q_PORT, user=config.Q_USER)
    sql = 'genCode["%s"]' % (account)
    try:
        res = qconn.k(str(sql))
    except:
        res = None
        logger.error(traceback.format_exc())
        logger.error(sql)
    qconn.close()
    return res
Пример #17
0
def submit(func, exc_callback, queue_name="DEFAULT"):
    def cb(cb_f):
        e = cb_f.exception()
        if e:
            exc_callback(e)
        if ENABLE_LOG:
            now = time.time()
            t = _queueLog[queue_name][func]
            _queueLog[queue_name][func] = (t[0], t[1], "done", time.time(), e,
                                           "elapsed", now - t[1])
            q.q(qstatsf())

    if ShutdownEvent.is_set():
        log.debug("ignoring async.submit due to impending shutdown.")
        return None
    f = _queues[queue_name].submit(func)
    if ENABLE_LOG:
        _queueLog[queue_name][func] = ("added", time.time(), None, None, None)
        q.q(qstatsf())
    f.add_done_callback(cb)
    return f
Пример #18
0
def get_ex_rate():
    qconn = q.q(host=config.Q_HOST, port=config.Q_PORT, user=config.Q_USER)
    sql = '(usdt;eth;eos;btc)'
    try:
        res = qconn.k(str(sql))
        res = {'usdt': res[0], 'eth': res[1], 'eos': res[2], 'btc': res[3]}
    except:
        res = []
        logger.error(traceback.format_exc())
        logger.error(sql)
    qconn.close()
    return res
    def uuid(self):
        """Returns UUID of a given name

        Will search for a given name and return the first one returned to us. If no name,
        and therefore no ID, is found, will return the string "none". The string "none"
        is returned because if we were to return the None value, it would cause the
        license loading code to append a None string to the URI; essentially asking the
        remote device for its collection (which we dont want and which would cause the SDK
        to return an False error.

        :return:
        """
        collection = self.client.api.cm.device.licensing.pool.regkey.licenses_s.get_collection(
        )
        resource = next(
            (x for x in collection if x.name == self._values['name']), None)
        import q
        q.q(resource)
        if resource:
            return resource.id
        else:
            return "none"
Пример #20
0
 def __init__(self, target):
     # self.qscript = ba_config.qscript
     cmd = 'nohup /home/sunqi/q/l32/q /home/sunqi/mysrc/kdbSync.qpy/src/qscript/contest.q -p %d -u /home/sunqi/qtest/pass > /dev/null 2>&1 &' % (
         ba_config.port)
     logger.info(cmd)
     os.system(
         'nohup /home/sunqi/q/l32/q /home/sunqi/mysrc/kdbSync.qpy/src/qscript/contest.q -p %d -u /home/sunqi/qtest/pass > /dev/null 2>&1 &'
         % (ba_config.port))
     time.sleep(3)
     self.qcon = q.q(host='localhost',
                     port=ba_config.port,
                     user=ba_config.user)
     zip_filter = u'bitsharzmq-accbalance'
     self.context = zmq.Context()
     self.socket = self.context.socket(zmq.SUB)
     self.socket.connect(target)
     self.socket.setsockopt_string(zmq.SUBSCRIBE, zip_filter)
     self.filter_assets = []
Пример #21
0
def get_portfolio_account(account, slot):  # sloc is minute
    if slot < 1:
        return ['error: slot must >0, please change your slot!']
    qconn = q.q(host=config.Q_HOST, port=config.Q_PORT, user=config.Q_USER)
    sql = 'getPortfolio["%s";%d]' % (account, slot)
    try:
        res = qconn.k(str(sql))
    except:
        res = []
        logger.error(traceback.format_exc())
        logger.error(sql)
    qconn.close()
    return map(
        lambda x: {
            'time': x[0],
            'usdt': x[1],
            'eth': x[2],
            'eos': x[3],
            'cap': x[4]
        }, list(res))
Пример #22
0
def portfolio_ranking(algo, limit):
    # rates = get_ex_rate() # usdt, eth, eos
    qconn = q.q(host=config.Q_HOST, port=config.Q_PORT, user=config.Q_USER)
    if algo not in (
            'COMP', 'RV', 'SHARP'
    ):  # COMP::select account,cap, score: (rv_score*0.6)+(sharp_score*0.35)+ (to_ind*0.05), rv_score ,sharp_score, turnover from ej[`account;ej[`account;RV;SHARP];to_ind]
        return []
    if limit > 50:
        return []
    sql = 'get_ranking[%d;%s]' % (limit, algo)
    # logger.info(sql)
    try:
        res = qconn.k(str(sql))
    except:
        res = []
        logger.error(traceback.format_exc())
        logger.error(sql)
    qconn.close()
    # return map(lambda x:{'account':x[0], 'value':x[1], 'cap':x[2]  } , list(res))
    if algo == 'COMP':
        # return map(lambda x:{'account':x[0], 'cap':x[1], 'score':x[2], 'rv_score':x[3], 'sharp_score':x[4], 'turnover':x[5] } , list(res))
        # return map(lambda x:{'account':x[0], 'rv':x[3], 'sharp':x[4], 'cap':x[1], 'score':x[2], 'turnover':x[5] } , list(res))
        return map(
            lambda x: {
                'account': x[0],
                'rv': x[3],
                'sharp': x[4],
                'cap': x[1],
                'turnover': x[5]
            }, list(res))
    else:
        # return map(lambda x:{'account':x[0], 'rv':x[1], 'sharp':x[2], 'cap':x[3] ,'score':x[4], 'turnover':x[6] } , list(res))
        return map(
            lambda x: {
                'account': x[0],
                'rv': x[1],
                'sharp': x[2],
                'cap': x[3],
                'turnover': x[6]
            }, list(res))
Пример #23
0
import numpy as np
from q import q
from entropy2 import entropy2
import matplotlib.pyplot as plt
# gamma_db=[-20:0.1:20];
gamma_db = np.arange(-20, 20 + 0.01, 0.1)  # (401,)

# gamma=10.^(gamma_db./10);
gamma = 10**(gamma_db / 10)  # (401,)

# p_error=q(sqrt(2.*gamma));
p_error = q(np.sqrt(2 * gamma))

capacity = 1 - entropy2(p_error)

fig = plt.figure(21, figsize=(13, 8), dpi=98)

fig.add_subplot(211,
                xlabel='SNR/bit',
                ylabel='Error Prob.',
                title='Error probability versus SNR/bit')
plt.semilogx(gamma, p_error)
plt.grid()

fig.add_subplot(212,
                xlabel='SNR/bit',
                ylabel='Channel capacity',
                title='Channel capacity versus SNR/bit')
plt.semilogx(gamma, capacity)
plt.grid()
plt.subplots_adjust(wspace=1, hspace=1)
Пример #24
0
	def test_q_Disable(self):
		import q
		q.use_syslog()

		q.q('Test message')
		self.assertFalse(os.path.exists('/tmp/q'))
Пример #25
0
def q_debug(value):
    q.q(value)
Пример #26
0
 def List(self, xs) -> Q:
     return q([getattr(x, "val", x) for x in xs])
Пример #27
0
 def Dict(self, ks, vs) -> Q:
     return q({
         getattr(k, "val", k): getattr(v, "val", v)
         for k, v in zip(ks, vs)
     })
Пример #28
0
            p2.show()
            p2.y += 1
            p2.x += delta_p2
            delta_p1 = float(c.x - b.x) / (c.y - b.y)


screen = 800, 600
center = 400, 300

img = Image.new("RGB", (screen[0] + 1, screen[1] + 1), "black")
canvas = img.load()

with open("face.obj", "r") as source:
    lines = source.read().split("\n")

points = []
for line in lines:
    match = RE_TYPE.match(line)
    if match:
        if match.group() == "v":
            etype, x, y, z = RE_OBJ_ENTRY.split(line)
            x = (float(x) + 1) * center[0]
            y = screen[1] - (float(y) + 1) * center[1]
            canvas[x, y] = (255, 255, 255)
            points.append(Point(x, y))
        elif match.group() == "f":
            entry = RE_OBJ_ENTRY.split(line)
            q.q([points[int(el.split("/")[0]) - 1] for el in entry[1:]])

img.show()
Пример #29
0
snr_in_dB = np.arange(initial_snr, final_snr + 0.1 * snr_step, snr_step)

# 初始化
n = len(snr_in_dB)
Pe_2 = np.zeros(n)
Pe_4 = np.zeros(n)
Pe_8 = np.zeros(n)
Pe_16 = np.zeros(n)
Pe_32 = np.zeros(n)

for i in range(n):
    # snr=10^(snr_in_dB(i)/10);
    snr = 10**(snr_in_dB[i] / 10)

    Pe_2[i] = q(np.sqrt(snr))
    """           
    由于函数return回的结果有两个,其实是一个元祖,python语法中元祖不能直接乘以非int类型,因此前面系数
    在后面输出
    Pe_4[i], error = (2/3) *integrate.quad(bdt_int2, minus_inf, plus_inf,
                                    epsabs=tolerance, args=(snr, 4))"""
    Pe_4[i], error = integrate.quad(bdt_int2, 0, plus_inf, \
                                    epsabs=tolerance, args=(snr, 4))
    Pe_8[i], error = integrate.quad(bdt_int2,
                                    0,
                                    plus_inf,
                                    epsabs=tolerance,
                                    args=(snr, 8))

    Pe_16[i], error = integrate.quad(bdt_int2,
                                     0,
Пример #30
0
 def Set(self, xs) -> Q:
     return q(set(getattr(x, "val", x) for x in xs))
Пример #31
0
        self.var_names = set()
        self.name = name
        self.q = q

    def build_code(self):
        m = Module()
        d = m.symbol("d")
        q = self.q
        with m.def_(self.name, d):
            env = {}
            for name in self.var_names:
                env[name] = m.let(name,
                                  d.get(name))  # TODO: required/unrequired
            m.return_(q)
        return m


# from q import QJSBuilder
# from functools import partial
# q = partial(q, builder=QJSBuilder())

print(q("x"), q("x").And("y"), q("x").Lt(q("y").Not()))
print(q("x").startswith("y"), q("x").foo.bar(q("z"), "xx").boo())
print(q("x").IsNot("y"), q("x").In(q("y")))
print(q("x").Add("y").neg().add(q("int")(True)))
print(q("ob").x.Mult(q("ob").y))

b = Builder(q("name").startswith("o"))
b.var_names.add("name")
print(b.build_code())
Пример #32
0
 def test_q_log_message(self):
     import q
     q.q('Test message')
     self.assertInQLog('Test message')
Пример #33
0
import os
import sys

import q

# If there is a global installation of poetry, prefer that.
poetry_python_lib = os.path.expanduser('~/.poetry/lib')
sys.path.append(os.path.realpath(poetry_python_lib))

try:
    from poetry.core.masonry.builders.sdist import SdistBuilder
    from poetry.factory import Factory
except (ImportError, ModuleNotFoundError) as ee:
    raise ImportError('install poetry by doing pip install poetry to use '
                      f'this script: {ee}')


# Generate a Poetry object that knows about the metadata in pyproject.toml
factory = Factory()
poetry = factory.create_poetry(os.path.dirname(__file__))

# Use the SdistBuilder to genrate a blob for setup.py
sdist_builder = SdistBuilder(poetry, None, None)
setuppy_blob = sdist_builder.build_setup()

q.q(setuppy_blob)

with open('setup.py', 'wb') as unit:
    unit.write(setuppy_blob)
    unit.write(b'\n# This setup.py was autogenerated using poetry.\n')
Пример #34
0
            p2.show()
            p2.y += 1
            p2.x += delta_p2
            delta_p1 = float(c.x - b.x) / (c.y - b.y)


screen = 800, 600
center = 400, 300

img = Image.new("RGB", (screen[0] + 1, screen[1] + 1), "black")
canvas = img.load()

with open("face.obj", "r") as source:
    lines = source.read().split("\n")

points = []
for line in lines:
    match = RE_TYPE.match(line)
    if match:
        if match.group() == "v":
            etype, x, y, z = RE_OBJ_ENTRY.split(line)
            x = (float(x) + 1) * center[0]
            y = screen[1] - (float(y) + 1) * center[1]
            canvas[x, y] = (255, 255, 255)
            points.append(Point(x, y))
        elif match.group() == "f":
            entry = RE_OBJ_ENTRY.split(line)
            q.q([points[int(el.split("/")[0])-1] for el in entry[1:]])

img.show()