function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def a_function():
return | PyBossa/pybossa | [
716,
269,
716,
21,
1321773782
] |
def setUp(self):
sentinel = Sentinel(settings_test.REDIS_SENTINEL)
db = getattr(settings_test, 'REDIS_DB', 0)
self.connection = sentinel.master_for('mymaster', db=db)
self.connection.flushall()
self.scheduler = Scheduler('test_queue', connection=self.connection) | PyBossa/pybossa | [
716,
269,
716,
21,
1321773782
] |
def test_adds_several_jobs_(self):
schedule_job(a_job, self.scheduler)
schedule_job(another_job, self.scheduler)
sched_jobs = self.scheduler.get_jobs()
job_func_names = [job.func_name for job in sched_jobs]
module_name = 'test_jobs.test_schedule_jobs'
assert len(sched_jo... | PyBossa/pybossa | [
716,
269,
716,
21,
1321773782
] |
def test_returns_log_messages(self):
success_message = schedule_job(a_job, self.scheduler)
failure_message = schedule_job(a_job, self.scheduler)
assert success_message == 'Scheduled a_function([], {}) to run every 1 seconds'
assert failure_message == 'WARNING: Job a_function([], {}) is ... | PyBossa/pybossa | [
716,
269,
716,
21,
1321773782
] |
def utcNow( cls ):
"""Return the current UTC time as a FILETIME value.
Output: An unsigned long integer representing the current time in
FILETIME format.
Notes: Yeah...the few nanoseconds it will take to run this code
means that by the time the result is actually returned it
... | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def SMB_Pad8( msglen=0 ):
"""Return the number of padding octets needed for 8-octet alignment.
Input: msglen - The length of the bytestream that may need to be
padded. It is assumed that this bytestream starts
on an 8-octet boundary (otherwise, the results are
... | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def test_roster_generation(self,
config_override,
extra_module_engagement_metric_ranges,
extra_module_engagement_rows):
self._validate_roster_generation(config_override,
extra_mo... | edx/edx-analytics-pipeline | [
91,
120,
91,
29,
1407959837
] |
def _validate_roster_generation(self,
config_override,
extra_module_engagement_metric_ranges,
extra_module_engagement_rows):
"""Validates the module engagement roster data generated by ModuleEngagementWor... | edx/edx-analytics-pipeline | [
91,
120,
91,
29,
1407959837
] |
def __init__(self, user_id, post_id):
# Call the BaseAlert __init__ method
super(PostingAlert, self).__init__(user_id)
self.post_id = post_id | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def verify(self):
"""Overwrites the verify() of BaseAlert to check the post exists
"""
return m.db.users.find_one({'_id': self.user_id}, {}) and \
m.db.posts.find_one({'_id': self.post_id}, {}) | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def prettify(self, for_uid=None):
return '<a href="{0}">{1}</a> tagged you in a <a href="{2}">post</a>' \
.format(url_for('users.profile',
username=self.user.get('username')),
do_capitalize(self.user.get('username')), self.url()) | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def prettify(self, for_uid=None):
# Let's try and work out why this user is being notified of a comment
reason = subscription_reason(for_uid, self.post_id)
if reason == SubscriptionReasons.POSTER:
sr = 'posted'
elif reason == SubscriptionReasons.COMMENTER:
sr = '... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def populate_followers_feeds(user_id, post_id, timestamp):
"""Fan out a post_id to all the users followers.
This can be run on a worker to speed the process up.
"""
# Get a list of ALL users who are following a user
followers = r.zrange(k.USER_FOLLOWERS.format(user_id), 0, -1)
# This is not tr... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def populate_approved_followers_feeds(user_id, post_id, timestamp):
"""Fan out a post_id to all the users approved followers."""
# Get a list of ALL users who are following a user
followers = r.zrange(k.USER_APPROVED.format(user_id), 0, -1)
# This is not transactional as to not hold Redis up.
for fo... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def back_feed(who_id, whom_id):
"""Takes 5 lastest posts from user with ``who_id`` places them in user
with ``whom_id`` feed.
The reason behind this is that new users may follow someone but still have
and empty feed, which makes them sad :( so we'll give them some. If the
posts are to old for a non... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def get_post(post_id):
"""Returns a post. Simple helper function
"""
post = m.db.posts.find_one({'_id': post_id})
# Attach in the e-mail (will be removed with image uploads)
if post is not None:
user = m.db.users.find_one({'_id': post.get('user_id')},
{'a... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def get_posts(user_id, page=1, per_page=None, perm=0):
"""Returns a users posts as a pagination object."""
if per_page is None:
per_page = app.config.get('FEED_ITEMS_PER_PAGE')
# Get the user object we need the email for Gravatar.
user = m.db.users.find_one({'_id': user_id},
... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def get_hashtagged_posts(hashtag, page=1, per_page=None):
"""Returns all posts with `hashtag` in date order."""
if per_page is None:
per_page = app.config.get('FEED_ITEMS_PER_PAGE')
total = m.db.posts.find({
'hashtags.hashtag': hashtag,
'reply_to': {'$exists': False}}).count()
c... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def vote_post(user_id, post_id, amount=1, ts=None):
"""Handles voting on posts
:param user_id: User who is voting
:type user_id: str
:param post_id: ID of the post the user is voting on
:type post_id: int
:param amount: The way to vote (-1 or 1)
:type amount: int
:param ts: Timestamp to... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def delete_post_replies(post_id):
"""Delete ALL comments on post with pid.
This can't be done in one single call to Mongo because we need to remove
the votes from Redis!
"""
# Get a cursor for all the posts comments
cur = m.db.posts.find({'reply_to': post_id})
# Iterate over the cursor an... | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def unsubscribe(user_id, post_id):
"""Unsubscribe a user from a post.
"""
# Actually remove the uid from the subscribers list
return bool(r.zrem(k.POST_SUBSCRIBERS.format(post_id), user_id)) | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def unflag_post(post_id):
"""Resets the flag count on a post to 0.
.. note: This is an OP user only action from the dashboard.
"""
return m.db.posts.update({'_id': post_id}, {'$set': {'flags': 0}}) | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def is_subscribed(user_id, post_id):
"""Returns a boolean to denote if a user is subscribed or not
"""
return r.zrank(k.POST_SUBSCRIBERS.format(post_id), user_id) is not None | pjuu/pjuu | [
57,
7,
57,
27,
1374656999
] |
def setUpClass(cls):
super().setUpClass()
cls.res_users_model = cls.env["res.users"]
cls.move_model = cls.env["account.move"]
cls.journal_model = cls.env["account.journal"]
cls.payment_mode_model = cls.env["account.payment.mode"]
cls.partner_bank_model = cls.env["res.par... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_create_partner(self):
customer = (
self.env["res.partner"]
.with_company(self.company.id)
.create(
{
"name": "Test customer",
"customer_payment_mode_id": self.customer_payment_mode,
}
... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_out_invoice_onchange(self):
# Test the onchange methods in invoice
invoice = self.move_model.new(
{
"partner_id": self.customer.id,
"move_type": "out_invoice",
"company_id": self.company.id,
}
)
self.assertE... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_invoice_create_in_invoice(self):
invoice = self._create_invoice(
default_move_type="in_invoice", partner=self.supplier
)
invoice.action_post()
aml = invoice.line_ids.filtered(
lambda l: l.account_id.user_type_id == self.acct_type_payable
)
... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_invoice_create_out_refund(self):
self.manual_out.bank_account_required = False
invoice = self._create_invoice(
default_move_type="out_refund", partner=self.customer
)
invoice.action_post()
self.assertEqual(
invoice.payment_mode_id,
sel... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_invoice_constrains(self):
with self.assertRaises(UserError):
self.move_model.create(
{
"partner_id": self.supplier.id,
"move_type": "in_invoice",
"invoice_date": fields.Date.today(),
"company_id"... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_payment_mode_constrains_02(self):
self.move_model.create(
{
"date": fields.Date.today(),
"journal_id": self.journal_sale.id,
"name": "/",
"ref": "reference",
"state": "draft",
"invoice_line_ids":... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_invoice_out_refund(self):
invoice = self._create_invoice(
default_move_type="out_invoice", partner=self.customer
)
invoice.partner_bank_id = False
invoice.action_post()
# Lets create a refund invoice for invoice_1.
# I refund the invoice Using Refund ... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_partner_onchange(self):
customer_invoice = self.move_model.create(
{"partner_id": self.customer.id, "move_type": "out_invoice"}
)
self.assertEqual(customer_invoice.payment_mode_id, self.customer_payment_mode)
self.assertEqual(self.supplier_invoice.partner_bank_id, s... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def test_print_report(self):
self.supplier_invoice.partner_bank_id = self.supplier_bank.id
report = self.env.ref("account.account_invoices")
res = str(report._render_qweb_html(self.supplier_invoice.ids)[0])
self.assertIn(self.supplier_bank.acc_number, res)
payment_mode = self.sup... | OCA/bank-payment | [
152,
470,
152,
36,
1402917389
] |
def setUp(self):
self.curl = pycurl.Curl() | p/pycurl-archived | [
2,
6,
2,
5,
1361076307
] |
def tearDown(self):
self.curl.close() | p/pycurl-archived | [
2,
6,
2,
5,
1361076307
] |
def __init__(self):
""" Empty Ctor """
pass | xalt/xalt | [
36,
10,
36,
1,
1410559911
] |
def execute(self):
""" Specify command line arguments and parse the command line"""
parser = argparse.ArgumentParser()
parser.add_argument("--dbname", dest='dbname', action="store", default = "xalt", help="xalt")
args = parser.parse_args()
return args | xalt/xalt | [
36,
10,
36,
1,
1410559911
] |
def __init__(self):
""" Empty Ctor """
pass | xalt/xalt | [
36,
10,
36,
1,
1410559911
] |
def execute(self):
""" Specify command line arguments and parse the command line"""
parser = argparse.ArgumentParser()
parser.add_argument("--confFn", dest='confFn', action="store", help="python config file")
parser.add_argument("--xalt_cfg", dest='xaltCFG', action="store", help="XALT std... | xalt/xalt | [
36,
10,
36,
1,
1410559911
] |
def convert_template(pattern, replaceA ,inputFn, outputFn):
try:
f = open(inputFn,"r")
except IOError as e:
print("Unable to open \"%s\", aborting!" % (inputFn))
sys.exit(-1) | xalt/xalt | [
36,
10,
36,
1,
1410559911
] |
def main():
my_replacement = "python_pkg_patterns"
args = CmdLineOptions().execute()
namespace = {}
exec(open(args.confFn).read(), namespace)
replaceA = namespace.get(my_replacement, [])
namespace = {}
exec(open(args.xaltCFG).read(), namespace)
replaceA.extend(namespace.get(my_replacement, []))
c... | xalt/xalt | [
36,
10,
36,
1,
1410559911
] |
def start_agent():
result = False
try:
process = subprocess.Popen(start_command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
raw_output, error_output = process.communicate()
if raw_output == '' and error_output == '':
logger.log('Ag... | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def load_agent():
try:
process = subprocess.Popen(load_command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
raw_output, error_output = process.communicate()
if raw_output == '' and error_output == '':
logger.log('Agent loaded.')
... | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def agent_running_stats():
ps_info = []
running = False
loaded = False
process = subprocess.Popen(list_command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
raw_output, error_output = process.communicate()
for line in raw_output.splitlines():
pid, r... | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def setUp(self, *args, **kwargs):
ctx = zmq.Context()
ctx = zmq.Context()
# two beacon frames
self.transmit1 = struct.pack('cccb16sH', b'Z', b'R', b'E',
1, uuid.uuid4().bytes,
socket.htons(9999))
self.transmit2 = struct.pack('... | zeromq/pyre | [
116,
50,
116,
20,
1382777149
] |
def tearDown(self):
self.node1.destroy()
self.node2.destroy() | zeromq/pyre | [
116,
50,
116,
20,
1382777149
] |
def test_node1(self):
self.node1.send_unicode("PUBLISH", zmq.SNDMORE)
self.node1.send(self.transmit1) | zeromq/pyre | [
116,
50,
116,
20,
1382777149
] |
def test_recv_beacon1(self):
self.node1.send_unicode("PUBLISH", zmq.SNDMORE)
self.node1.send(self.transmit1)
self.node2.send_unicode("PUBLISH", zmq.SNDMORE)
self.node2.send(self.transmit2)
req = self.node1.recv_multipart()
self.assertEqual(self.transmit2, req[1]) | zeromq/pyre | [
116,
50,
116,
20,
1382777149
] |
def generate_color_handler(cls, stream=sys.stdout):
handler = logging.StreamHandler(stream)
handler.setFormatter(cls.FORMATTER_COLOR)
return handler | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def get_script_name(cls):
script_name = os.path.basename(sys.argv[0])
script_name, _ = os.path.splitext(script_name)
return script_name | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def generate_simple_rotating_file_handler(cls, path_log_file=None, when='midnight', files_count=7):
if path_log_file is None:
path_dir = os.path.dirname(sys.argv[0])
path_log_file = cls.suggest_script_log_name(path_dir)
handler = logging.handlers.TimedRotatingFileHandler(path_lo... | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def suggest_script_log_name(cls, path_dir):
return os.path.join(path_dir, cls.get_script_name() + '.log') | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def timestamp(with_ms=False, time=None):
if time is None:
time = datetime.datetime.now()
if with_ms:
return time.strftime('%Y%m%d_%H%M%S.%f')[:-3]
else:
return time.strftime('%Y%m%d_%H%M%S') | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def __init__(self, *, n_samples=1000, units_suffix='', units_format='.2f', name=None):
super().__init__()
self.name: str = name
self.queue_samples = deque(maxlen=n_samples)
self.total = 0
self.last = 0
self.units_str = units_suffix
self.units_format = units_forma... | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def n_samples(self):
return len(self.queue_samples) | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def last_str(self):
str_name = f'[{self.name}] ' if self.name else ''
return f'{str_name}{self.last:{self.units_format}} {self.units_str}' | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def average(self):
if self.n_samples == 0:
return None
return self.total / self.n_samples | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def __init__(self, n_samples=1000, units_format='.1f', **kwargs) -> None:
super().__init__(n_samples=n_samples, units_suffix='sec', units_format=units_format, **kwargs)
self.time_last_start = 0 | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def __exit__(self, t, value, tb):
self.end() | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def end(self):
self.submit_sample(self.peek()) | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def __init__(self, stream=None):
if not stream:
stream = io.StringIO()
self.stream = stream | wolf1986/log_utils | [
3,
2,
3,
1,
1497855595
] |
def PutAsync( entities, **kwargs ):
"""
Asynchronously store one or more entities in the data store.
This function is identical to :func:`server.db.Put`, except that it
returns an asynchronous object. Call ``get_result()`` on the return value to
block on the call and get the results.
"""
if isinstance( enti... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def GetAsync( keys, **kwargs ):
"""
Asynchronously retrieves one or more entities from the data store.
This function is identical to :func:`server.db.Get`, except that it
returns an asynchronous object. Call ``get_result()`` on the return value to
block on the call and get the results.
"""
class AsyncResult... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def GetOrInsert( key, kindName=None, parent=None, **kwargs ):
"""
Either creates a new entity with the given key, or returns the existing one.
Its guaranteed that there is no race-condition here; it will never overwrite an
previously created entity. Extra keyword arguments passed to this function will be
used... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def Delete(keys, **kwargs):
"""
Deletes one or more entities from the data store.
:warning: Permanently deletes entities, use with care!
Deletes the given entity or entities from the data store. You can only delete
entities from your app. If there is an error, the function raises a
subclass of :exc:`datast... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def __init__(self, kind, srcSkelClass=None, *args, **kwargs ):
super( Query, self ).__init__( )
self.datastoreQuery = datastore.Query( kind, *args, **kwargs )
self.srcSkel = srcSkelClass
self.amount = 30
self._filterHook = None
self._orderHook = None
self._origCursor = None
self._customMultiQueryMerge =... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def setOrderHook(self, hook):
"""
Installs *hook* as a callback function for new orderings.
*hook* will be called each time a :func:`db.Query.order` is called on this query.
:param hook: The function to register as callback. \
A value of None removes the currently active hook.
:type hook: callable
... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def filter(self, filter, value=__undefinedC__ ):
"""
Adds a filter to this query. #fixme: Better description required here...
The following examples are equivalent: ``filter( "name", "John" )``
and ``filter( {"name": "John"} )``.
See also :func:`server.db.Query.mergeExternalFilter` for a safer filter im... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def ancestor(self, ancestor):
"""
Sets an ancestor for this query.
This restricts the query to only return result entities that are descended
from a given entity. In other words, all of the results will have the
ancestor as their parent, or parent's parent, and so on.
Raises BadArgumentError or BadKe... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def limit( self, amount ):
"""
Sets the query limit to *amount* entities in the result.
Specifying an amount of 0 disables the limit (use with care!).
:param amount: The maximum number of entities.
:type amount: int
:returns: Returns the query itself for chaining.
:rtype: server.db.Query
"""
... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def getQueryOptions(self):
"""
Returns a datastore_query.QueryOptions for the current instance.
:rtype: datastore_query.QueryOptions
"""
return( self.datastoreQuery.GetQueryOptions() ) | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def getOrder(self):
"""
Gets a datastore_query.Order for the current instance.
:returns: The sort orders set on the current query, or None.
:rtype: datastore_query.Order or None
"""
if self.datastoreQuery is None:
return( None )
return( self.datastoreQuery.GetOrder() ) | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def getOrders(self):
"""
Returns a list of orders applied to this query.
Every element in the list returned (if any), is a tuple of (property,direction).
Property is the name of the property used to sort, direction a bool
(false => ascending, True => descending).
:returns: list of orderings, in tupl... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def getKind(self):
"""
Returns the kind of this query.
:rtype: str
"""
if self.datastoreQuery is None:
return( None )
return( self.datastoreQuery.__kind ) | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def getAncestor(self):
"""
Returns the ancestor of this query (if any).
:rtype: str | None
"""
return( self.datastoreQuery.ancestor ) | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def fetch(self, limit=-1, **kwargs ):
"""
Run this query and fetch results as :class:`server.skeleton.SkelList`.
This function is similar to :func:`server.db.Query.run`, but returns a
:class:`server.skeleton.SkelList` instance instead of Entities.
:warning: The query must be limited!
If queried data... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def get( self ):
"""
Returns only the first entity of the current query.
:returns: dict on success, or None if the result-set is empty.
:rtype: dict
"""
try:
res = list( self.run( limit=1 ) )[0]
return( res )
except IndexError: #Empty result-set
return( None )
except TypeError: #Also Empty ... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def count( self, limit=1000, **kwargs ):
"""
Returns the number of entities that this query matches.
:param limit: Limits the query to the defined maximum entities count.\
If there are more results than this limit, stop short and just return this number.\
Providing this argument makes the count operation... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def _fixUnindexedProperties( self ):
"""
Ensures that no property with strlen > 500 makes it into the index.
"""
unindexed = list( self.getUnindexedProperties() )
for k,v in self.items():
if isinstance( v, basestring ) and len( v )>=500 and not k in unindexed:
logging.warning("Your property %s cant be... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def entityGroup(self):
"""
Returns this entity's entity group as a Key.
Note that the returned Key will be incomplete if this is a a root entity
and its key is incomplete.
"""
return( self.entity_group() ) | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def setUnindexedProperties(self, unindexed_properties):
"""
Sets the list of unindexed properties.
Properties listed here are *not* saved in an index;
its impossible to use them in a query filter / sort.
But it saves one db-write op per property listed here.
"""
self.set_unindexed_properties( uninde... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def set(self, key, value, indexed=True):
"""
Sets a property.
:param key: key of the property to set.
:type key: str
:param value: Any value to set tot the property.
:param indexed: Defines if the value is indexed.
:type indexed: bool
:raises: :exc:`BadPropertyError` if the property name is th... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def FromDatastoreEntity( entity ):
"""
Converts a datastore.Entity into a :class:`db.server.Entity`.
Required, as ``datastore.Get()`` always returns a datastore.Entity
(and it seems that currently there is no valid way to change that).
"""
res = Entity( entity.kind(), parent=entity.key().parent(), _app=... | viur-framework/server | [
12,
5,
12,
31,
1496136499
] |
def doit(channel):
cpu_pc = psutil.cpu_percent()
mem_avail_mb = psutil.virtual_memory().percent
try:
response = channel.update({1: cpu_pc, 2: mem_avail})
print(cpu_pc)
print(mem_avail_mb)
print(strftime("%a, %d %b %Y %H:%M:%S", localtime()))
print(response)
exce... | mchwalisz/thingspeak | [
32,
14,
32,
9,
1454869765
] |
def testCombinationPairs(self):
inputs = ["A", "B", "C"]
expected_combination = [("A", "B"), ("A", "C"), ("B", "C")]
actual_combination = paraphrase_ms_coco.create_combination(inputs)
self.assertEqual(actual_combination, expected_combination) | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def testBidirectionalTrue(self, data, bidirectional):
paraphrase_problem = paraphrase_ms_coco.ParaphraseGenerationProblem()
paraphrase_problem.bidirectional = True
expected_generated_data = [{"inputs": "sentence1", "targets": "sentence2"},
{"inputs": "sentence2", "targets": "... | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def testBidirectionalFalse(self, data, bidirectional):
paraphrase_problem = paraphrase_ms_coco.ParaphraseGenerationProblem()
paraphrase_problem.bidirectional = False
expected_generated_data = [{"inputs": "sentence1", "targets": "sentence2"}]
actual_generated_data = list(paraphrase_problem
... | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def __init__(self, *args, **kwargs):
kwargs.setdefault('directConnection', True)
kwargs.setdefault('serverSelectionTimeoutMS', 1)
# Set client application name for MongoDB 3.4+ servers
kwargs['appName'] = f'''mlaunch v{__version__}'''
Connection.__init__(self, *args, **kwargs) | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def shutdown_host(port, username=None, password=None, authdb=None):
"""
Send the shutdown command to a mongod or mongos on given port.
This function can be called as a separate thread.
"""
host = 'localhost:%i' % port
try:
if username and password and authdb:
if authdb != "a... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def check_mongo_server_output(binary, argument):
"""Call mongo[d|s] with arguments such as --help or --version.
This is used only to check the server's output. We expect the server to
exit immediately.
"""
try:
proc = subprocess.Popen(['%s' % binary, argument],
... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def __init__(self, test=False):
BaseCmdLineTool.__init__(self)
# arguments
self.args = None
# startup parameters for each port
self.startup_info = {}
# data structures for the discovery feature
self.cluster_tree = {}
self.cluster_tags = defaultdict(list... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def is_file(arg):
if not os.path.exists(os.path.expanduser(arg)):
init_parser.error("The file [%s] does not exist" % arg)
return arg | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def init(self):
"""
Sub-command init.
Branches out to sharded, replicaset or single node methods.
"""
# check for existing environment. Only allow subsequent
# 'mlaunch init' if they are identical.
if self._load_parameters():
if self.loaded_args != se... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def getMongoDVersion(self):
binary = "mongod"
if self.args and self.args.get('binarypath'):
binary = os.path.join(self.args['binarypath'], binary)
try:
out = check_mongo_server_output(binary, '--version')
except Exception:
return "0.0"
buf = ... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def stop(self):
"""
Sub-command stop.
Parse the list of tags and stop the matching nodes. Each tag has a set
of nodes associated with it, and only the nodes matching all tags
(intersection) will be shut down.
Currently this is an alias for kill()
"""
sel... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def list(self):
"""
Sub-command list.
Takes no further parameters. Will discover the current configuration
and print a table of all the nodes with status and port.
"""
self.discover()
print_docs = []
# mongos
for node in sorted(self.get_tagged(['... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def restart(self):
# get all running processes
processes = self._get_processes()
procs = [processes[k] for k in list(processes.keys())]
# stop nodes via stop command
self.stop()
# wait until all processes terminate
psutil.wait_procs(procs)
# start node... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def discover(self):
"""
Fetch state for each processes.
Build the self.cluster_tree, self.cluster_tags, self.cluster_running
data structures, needed for sub-commands start, stop, list.
"""
# need self.args['command'] so fail if it's not available
if (not self.arg... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def get_tagged(self, tags):
"""
Tag format.
The format for the tags list is tuples for tags: mongos, config, shard,
secondary tags of the form (tag, number), e.g. ('mongos', 2) which
references the second mongos in the list. For all other tags, it is
simply the string, e... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
def wait_for(self, ports, interval=1.0, timeout=30, to_start=True):
"""
Spawn threads to ping host using a list of ports.
Returns when all hosts are running (if to_start=True) / shut down (if
to_start=False).
"""
threads = []
queue = Queue.Queue()
for po... | rueckstiess/mtools | [
1782,
375,
1782,
74,
1347607696
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.