function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def settings(request, event_url_name):
event = get_object_or_404(Event, url_name=event_url_name)
# check permission
if not has_access(request.user, event, ACCESS_BADGES_EDIT):
return nopermission(request)
# check if badge system is active
if not event.badges:
return notactive(request)
# roles
roles = event.badge_settings.badgerole_set.all()
# designs
designs = event.badge_settings.badgedesign_set.all()
# forms for defaults
defaults_form = BadgeDefaultsForm(request.POST or None,
instance=event.badge_settings.defaults,
settings=event.badge_settings,
prefix='event')
job_defaults_form = BadgeJobDefaultsForm(request.POST or None, event=event,
prefix='jobs')
if defaults_form.is_valid() and job_defaults_form.is_valid():
defaults_form.save()
job_defaults_form.save()
return redirect('badges:settings', event_url_name=event.url_name)
context = {'event': event,
'roles': roles,
'designs': designs,
'defaults_form': defaults_form,
'job_defaults_form': job_defaults_form}
return render(request, 'badges/settings.html', context) | helfertool/helfertool | [
43,
19,
43,
42,
1482499089
] |
def settings_advanced(request, event_url_name):
event = get_object_or_404(Event, url_name=event_url_name)
# check permission
if not has_access(request.user, event, ACCESS_BADGES_EDIT):
return nopermission(request)
# check if badge system is active
if not event.badges:
return notactive(request)
# form for settings
form = BadgeSettingsForm(request.POST or None, request.FILES or None,
instance=event.badge_settings)
# for for permissions
permissions = event.badge_settings.badgepermission_set.all()
if form.is_valid():
form.save()
return redirect('badges:settings_advanced', event_url_name=event.url_name)
# render
context = {'event': event,
'form': form,
'permissions': permissions}
return render(request, 'badges/settings_advanced.html',
context) | helfertool/helfertool | [
43,
19,
43,
42,
1482499089
] |
def default_template(request, event_url_name):
event = get_object_or_404(Event, url_name=event_url_name)
# check permission
if not has_access(request.user, event, ACCESS_BADGES_EDIT):
return nopermission(request)
# check if badge system is active
if not event.badges:
return notactive(request)
# output
response = HttpResponse(content_type='application/x-tex')
response['Content-Disposition'] = 'attachment; filename="template.tex"'
# send file
with open(django_settings.BADGE_DEFAULT_TEMPLATE, 'rb') as f:
response.write(f.read())
return response | helfertool/helfertool | [
43,
19,
43,
42,
1482499089
] |
def test_gmap_mapper():
'It test the gmap mapper'
mappers_dir = join(TEST_DATA_DIR, 'mappers')
gmap_dir = join(TEST_DATA_DIR, 'mappers', 'gmap')
work_dir = NamedTemporaryDir()
temp_genome = join(work_dir.name, 'genome.fa')
os.symlink(join(mappers_dir, 'genome.fa'), temp_genome)
reads_fpath = join(gmap_dir, 'lb_lib1.pl_sanger.sm_sam1.fa')
out_bam_fhand = NamedTemporaryFile(suffix='.bam')
parameters = {'threads':None, 'kmer':13}
map_reads_with_gmap(temp_genome, reads_fpath, out_bam_fhand.name,
parameters)
sam_fhand = NamedTemporaryFile(suffix='.sam')
bam2sam(out_bam_fhand.name, sam_fhand.name, header=True)
result = open(sam_fhand.name).read()
assert exists(out_bam_fhand.name)
assert '36M2I204M' in result
assert 'SN:SL2.30ch00' in result
assert 'seq9_rev_MOD' in result
work_dir.close()
out_bam_fhand.close()
sam_fhand.close()
work_dir = NamedTemporaryDir()
temp_genome = join(work_dir.name, 'genome.fa')
os.symlink(join(mappers_dir, 'genome.fa'), temp_genome)
reads_fpath = join(gmap_dir, 'lb_lib1.pl_sanger.sm_sam1.sfastq')
out_bam_fhand = NamedTemporaryFile(suffix='.bam')
unmapped_fhand = StringIO.StringIO()
parameters = {'threads':None, 'kmer':13,
'unmapped_fhand':unmapped_fhand}
map_reads_with_gmap(temp_genome, reads_fpath, out_bam_fhand.name,
parameters)
sam_fhand = NamedTemporaryFile(suffix='.sam')
bam2sam(out_bam_fhand.name, sam_fhand.name, header=True)
result = open(sam_fhand.name).read()
assert exists(out_bam_fhand.name)
assert '36M2I204M' in result
assert 'SN:SL2.30ch00' in result
assert 'seq9_rev_MOD' in result
assert '?????????????????' in result
work_dir.close()
out_bam_fhand.close()
sam_fhand.close() | JoseBlanca/franklin | [
23,
3,
23,
25,
1272293875
] |
def test_gmap_without_mapping_output():
'''It test that the gmap doesn't map anything'''
mappers_dir = join(TEST_DATA_DIR, 'mappers')
cmap_dir = join(TEST_DATA_DIR, 'mappers', 'gmap')
work_dir = NamedTemporaryDir()
temp_genome = join(work_dir.name, 'genome.fa')
os.symlink(join(mappers_dir, 'genome.fa'), temp_genome)
reads_fhand = NamedTemporaryFile()
reads_fhand.write('>seq\natgtgatagat\n')
reads_fhand.flush()
out_bam_fhand = NamedTemporaryFile()
out_bam_fpath = out_bam_fhand.name
out_bam_fhand.close()
parameters = {'threads':None, 'kmer':13}
map_reads_with_gmap(temp_genome, reads_fhand.name, out_bam_fpath,
parameters)
reads_fhand.close()
temp_sam_fhand = NamedTemporaryFile(suffix='.sam')
bam2sam(out_bam_fpath, temp_sam_fhand.name, True)
result = open(temp_sam_fhand.name).read()
assert 'seq\t4\t*\t0\t0' in result | JoseBlanca/franklin | [
23,
3,
23,
25,
1272293875
] |
def test_bwa_mapping():
'''It test that the gmap doesn't map anything'''
reference = join(TEST_DATA_DIR, 'blast/arabidopsis_genes')
work_dir = NamedTemporaryDir()
reference_fpath = join(work_dir.name, 'arabidopsis_genes')
os.symlink(reference, reference_fpath)
reads_fhand = NamedTemporaryFile(suffix='.sfastq')
reads_fhand.write(SOLEXA)
reads_fhand.flush()
out_bam_fhand = NamedTemporaryFile()
out_bam_fpath = out_bam_fhand.name
out_bam_fhand.close()
parameters = {'colorspace': False, 'reads_length':'short',
'threads':None, 'java_conf':None}
map_reads_with_bwa(reference_fpath, reads_fhand.name, out_bam_fpath,
parameters)
test_sam_fhand = NamedTemporaryFile(suffix='sam')
bam2sam(out_bam_fpath, test_sam_fhand.name)
result = open(test_sam_fhand.name).read()
assert 'seq17' in result
unmapped_fhand = StringIO.StringIO()
parameters = {'colorspace': False, 'reads_length':'short',
'threads':None, 'java_conf':None,
'unmapped_fhand':unmapped_fhand}
map_reads_with_bwa(reference_fpath, reads_fhand.name, out_bam_fpath,
parameters)
assert 'seq17' in unmapped_fhand.getvalue()
test_sam_fhand = NamedTemporaryFile(suffix='sam')
bam2sam(out_bam_fpath, test_sam_fhand.name)
result = open(test_sam_fhand.name).read()
assert 'seq17' not in result | JoseBlanca/franklin | [
23,
3,
23,
25,
1272293875
] |
def forwards(self, orm):
for user in orm['auth.user'].objects.all():
notification = orm.Notification()
notification.user = user
notification.save() | fgaudin/aemanager | [
38,
20,
38,
17,
1292269932
] |
def test_getgenesfromfusion():
AB_EXAMPLE = ('A', 'B')
assert getgenesfromfusion('A-B') == AB_EXAMPLE
assert getgenesfromfusion('A-B ') == AB_EXAMPLE
assert getgenesfromfusion('a-b') == ('a', 'b')
assert getgenesfromfusion('A') == ('A', 'A')
assert getgenesfromfusion('A1-1B') == ('A1', '1B')
# Test fusion case insensitive
assert getgenesfromfusion('A-B fusion') == AB_EXAMPLE
assert getgenesfromfusion('A-B Fusion') == AB_EXAMPLE
# Test unnecessary characters will be trimmed off after fusion
assert getgenesfromfusion('A-B fusion archer') == AB_EXAMPLE
assert getgenesfromfusion('A-B fusion Archer') == AB_EXAMPLE
assert getgenesfromfusion('A-B fusion -Archer') == AB_EXAMPLE
assert getgenesfromfusion('A-B fusion -archer') == AB_EXAMPLE
assert getgenesfromfusion('A-B fusion - archer') == AB_EXAMPLE
assert getgenesfromfusion('A-B fusion - archer ') == AB_EXAMPLE
assert getgenesfromfusion('A-B fusion test') == AB_EXAMPLE
assert getgenesfromfusion('fusion A-B fusion') == AB_EXAMPLE
# Test intragenic
assert getgenesfromfusion('MLL2-intragenic') == ('MLL2', 'MLL2') | oncokb/oncokb-annotator | [
101,
52,
101,
9,
1489518732
] |
def test_replace_all():
# Test replace_all for case insensitivity
assert replace_all('tyr') == 'Y'
assert replace_all('tYr') == 'Y'
assert replace_all('Tyr') == 'Y'
assert replace_all('tyR') == 'Y'
assert replace_all('TyR') == 'Y'
assert replace_all('TYR') == 'Y'
assert replace_all('tYR') == 'Y'
assert replace_all('sEr') == 'S'
# Test replace_all only targets the dict() keys
assert replace_all('bubblegum juice cup dairy hot pot Tyr melon') == 'bubblegum juice cup dairy hot pot Y melon'
assert replace_all('Ly Lys Pr Pro Gln Glad Ph PH Phe') == 'Ly K Pr P Q Glad Ph PH F'
assert replace_all(
'nOt can fat Tan Rat cat dog man Men FAn rot taR car fAr map TAP Zip poP') == 'nOt can fat Tan Rat cat dog man Men FAn rot taR car fAr map TAP Zip poP'
# Test replace_all is not affected by numbers
assert replace_all('Tyr600E Cys56734342342454562456') == 'Y600E C56734342342454562456'
assert replace_all(
'60 045 434 345 4 26 567 254 245 34 67567 8 56 8 364 56 6 345 7567 3455 6 8 99 89 7 3') == '60 045 434 345 4 26 567 254 245 34 67567 8 56 8 364 56 6 345 7567 3455 6 8 99 89 7 3'
# Test replace_all is not affected by empty string and whitespaces
assert replace_all('') == ''
assert replace_all(' ') == ' '
assert replace_all('Tyr Asn As n Ile Il e') == 'Y N As n I Il e' | oncokb/oncokb-annotator | [
101,
52,
101,
9,
1489518732
] |
def save(self, *args, **kwargs):
"""
Only one image should be marked as is_primary for an object.
""" | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def add_arguments(self, parser):
parser.add_argument('args', nargs='*') | macarthur-lab/xbrowse | [
139,
77,
139,
77,
1389113017
] |
def get_accounting_data():
empty_accounting = {
'val_0': 0,
'empty': '',
'causal': 0, # ??? Causale cont. industr.
# Fatt vendita = 001
# Fatt acquisto = 002
'account': 0, # ??? Conto cont. Industriale
# 1 = sistemi
# 2 = Noleggi
# 3 = domotica
'account_proceeds': 0, # ??? Voce di spesa / ricavo (uguale ai conti di ricavo contabilità generale ma con uno 0 in più)
# 58100501
# 58100502
# 58100503
'sign': '', # ??? Segno ( D o A )
'total_ammount': 0, # Importo movimento o costo complessivo
}
accounting_data = ''
for k in range(0, 20):
accounting_data += industrial_accounting_template.format(**empty_accounting)
return accounting_data | iw3hxn/LibrERP | [
29,
16,
29,
1,
1402418161
] |
def __init__(self, client, batch_size):
super(ElasticBatch, self).__init__(client, batch_size)
self.client = client
self.actions = [] | c2corg/v6_api | [
21,
18,
21,
89,
1439983299
] |
def should_flush(self):
return len(self.actions) > self.batch_size | c2corg/v6_api | [
21,
18,
21,
89,
1439983299
] |
def test_unicode(self):
"""Unicode generation."""
self.assertIsNotNone(str(self.survey)) | Pierre-Sassoulas/django-survey | [
191,
133,
191,
35,
1489572975
] |
def test_absolute_url(self):
"""Absoulte url is not None and do not raise error."""
self.assertIsNotNone(self.survey.get_absolute_url()) | Pierre-Sassoulas/django-survey | [
191,
133,
191,
35,
1489572975
] |
def test_publish_date(self):
"""the pblish date must be None or datetime date instance."""
self.assertIsInstance(self.survey.publish_date, date) | Pierre-Sassoulas/django-survey | [
191,
133,
191,
35,
1489572975
] |
def test_expiration_date_is_in_future(self):
"""by default the expiration should be a week in the future"""
self.assertGreater(self.survey.expire_date, now()) | Pierre-Sassoulas/django-survey | [
191,
133,
191,
35,
1489572975
] |
def test_level_from_name(name, level_name, level_no):
level = level_from_name(name)
assert level.name == level_name
assert level.no == level_no | LibreTime/libretime | [
662,
191,
662,
147,
1487513246
] |
def upgrade():
op.create_table(
'jobpost_admin',
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('jobpost_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['jobpost_id'], ['jobpost.id']),
sa.ForeignKeyConstraint(['user_id'], ['user.id']),
sa.PrimaryKeyConstraint('user_id', 'jobpost_id'),
) | hasgeek/hasjob | [
233,
79,
233,
149,
1303378189
] |
def parseMsg( cls, msgBlob=None, dialect=SMB2_DIALECT_MIN ):
"""Decompose wire data and return an _SMB2_Header object.
Input:
cls - This class.
msgBlob - An array of at least 64 bytes, representing an SMB2+
message in wire format.
dialect - The minimum dialect under which to parse the header.
Output:
An <_SMB2_Header> object.
Errors:
AssertionError - Thrown if:
+ The length of <msgBlob> is less than the
minimum of 64 bytes.
+ The command code parsed from the message is
not a valid command code.
+ The given dialect is not known.
ValueError - Thrown if the packet cannot possibly contain a
valid SMB2+ message header. This exception is
raised if either the ProtocolId field doesn't
contain the correct string, or if the
StructureSize value is incorrect.
Notes:
- This function does not parse SMB3 Transform Headers. An SMB3
Transform header will be rejected with a ValueError.
- Beyond the basics of verifying that ProtocolId and StructureSize
are correct, this function does _no_ validation of the input.
"""
# Fundamental sanity check.
assert( SMB2_HDR_SIZE <= len( msgBlob ) ), "Incomplete message header."
# Parse it. Use the simple sync response format.
tup = cls._format_SMB2_StatTreeId.unpack( msgBlob[:SMB2_HDR_SIZE] )
# Look for trouble.
if( SMB2_MSG_PROTOCOL != tup[0] ):
raise ValueError( "Malformed SMB2 ProtocolId: [%s]." % repr( tup[0] ) )
elif( SMB2_HDR_SIZE != tup[1] ):
s = "The SMB2 Header StructureSize must be 64, not %d." % tup[1]
raise ValueError( s )
# Create and populate a header record instance.
hdr = cls( tup[4], dialect )
hdr._creditCharge = tup[2]
# 3: Status/ChannelSeq/Reserved1; see below
hdr.command = tup[4]
hdr._creditReqResp = tup[5]
hdr._flags = tup[6]
hdr._nextCommand = tup[7]
hdr._messageId = tup[8]
# 9, 10: Reserved2/TreeId/AsyncId; see below
hdr._sessionId = tup[11]
hdr._signature = tup[12]
# Handle the overloaded fields.
if( hdr.flagReply or (dialect < SMB2_DIALECT_300) ):
hdr._status = tup[3]
else:
hdr._channelSeq, hdr._reserved1 = cls._format_2H.unpack( msgBlob[8:12] )
if( hdr.flagAsync ):
hdr._asyncId = cls._format_Q.unpack( msgBlob[32:40] )
else:
hdr._reserved2 = tup[9]
hdr._treeId = tup[10]
# All done.
return( hdr ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def commandName( self, CmdId=0xFF ):
"""Given an SMB2 command code, return the name of the command.
Input:
CmdId - An SMB2/3 command code.
Output: A string.
If <CmdId> is a known SMB2/3 command code, the string
will be the command name. Otherwise, the empty string
is returned.
"""
if( CmdId in self._cmd_LookupDict ):
return( self._cmd_LookupDict[CmdId] )
return( '' ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def creditCharge( self ):
"""Get/set the SMB2_Header.CreditCharge field value (USHORT).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to an <int>) is either negative or greater
than 0xFFFF.
- Thrown if the assigned value is non-zero and
the current dialect is SMBv2.0.2.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into an <int>.
Notes:
It is out of character to throw an exception based on the given
dialect level. This layer does minimal enforcement of
per-dialect syntax rules, generally allowing the caller to make
their own mess. You can, of course, still bypass the assertion
by setting <instance>._creditCharge directly.
"""
return( self._creditCharge ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def creditCharge( self, cc ):
cc = int( cc )
assert( 0 <= cc <= _USHORT_MAX ), "Assigned value (%d) out of range." % cc
assert( (cc == 0) or (self._dialect > SMB2_DIALECT_202) ), \
"Reserved; Value must be zero in SMBv2.0.2."
self._creditCharge = cc | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def status( self ):
"""Get/set the SMB2_Header.status field (ULONG).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to a <long>) is either negative or greater
than 0xFFFFFFFF.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into a <long>.
Notes:
This field should only be set in response messages, and should
be considered "reserved; must be zero" in all requests.
Starting with SMBv3.0.0, this field is superceeded in request
messages by the 16-bit ChannelSequence field (plus an additional
16-bit Reserved field).
It is probably easiest to think of it this way:
- There is no <Status> field in request messages; it only exists
in response messages.
- If the dialect is less than 0x0300, then there is a 32-bit
"Reserved Must Be Zero" field where the <Status> field might
otherwise exist.
- If the dialect is 0x0300 or greater, then there is a 16-bit
<ChannelSequence> field followed by a 16-bit "Reserved Must Be
Zero" field where the <Status> might otherwise exist.
"""
return( self._status ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def status( self, st ):
st = 0L if( not st ) else long( st )
assert( 0 <= st <= _ULONG_MAX ), \
"Assigned value (0x%08X) out of range." % st
self._status = st | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def channelSeq( self ):
"""Get/set the Channel Sequence value (USHORT).
AssertionError - Thrown if the assigned value (after conversion
to an <int>) is either negative or greater
than 0xFFFF.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into an <int>.
Notes:
The ChannelSequence value is only recognized in request messages,
and only if the dialect is 0x0300 or greater. That is, this
field does not not exist in SMB2.x, only in SMB3.x. In all
responses, and in dialcts prior to 0x0300, the bytes of this
field are always seen as part of the Status field.
"""
return( self._channelSeq ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def channelSeq( self, cs ):
cs = int( cs )
assert( 0 <= cs <= _USHORT_MAX ), "Assigned value (%d) out of range." % cs
self._channelSeq = cs | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def command( self ):
"""Get/set the SMB2_Header.Command (UCHAR).
Errors: [ AssertionError, TypeError, ValueError ]
Thrown if the assigned value cannot be converted into a valid
SMB2 command code.
"""
return( self._command ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def command( self, cmd ):
cmd = int( cmd )
assert( 0 <= cmd <= 0x12 ), "Unknown command code: 0x%04X." % cmd
self._command = cmd | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def creditReqResp( self ):
"""Get/set the Credit Request / Credit Response value (USHORT).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to an <int>) is either negative or greater
than 0xFFFF.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into an <int>.
ToDo: Document how and when this is used; references.
The credit management subsystem needs study.
"""
return( self._creditReqResp ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def creditReqResp( self, crr ):
crr = int( crr )
assert( 0 <= crr <= _USHORT_MAX ), \
"Assigned value (%d) out of range." % crr
self._creditReqResp = crr | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flags( self ):
"""Get/set the Flags field (ULONG).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to a <long>) has bits that are set which do not
represent a known SMB2+ flag.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into a <long>.
"""
return( self._flags ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flags( self, flags ):
flgs = long( flags )
assert( flgs == (flgs & SMB2_FLAGS_MASK) ), "Unrecognized flag bit(s)."
self._flags = flgs | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def nextCommand( self ):
"""Get/set the Next Command offset value (ULONG).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to a <long>) is either negative, or greater
than (2^32)-1.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into a <long>.
"""
return( self._nextCommand ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def nextCommand( self, nextOffset ):
nc = long( nextOffset )
assert( 0 <= nc <= _ULONG_MAX ), \
"Invalid Related Command Offset: %d." % nc
self._nextCommand = nc | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def messageId( self ):
"""Get/set the Message ID value (UINT64).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to a <long>) is either negative, or greater
than (2^64)-1.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into a <long>.
"""
return( self._messageId ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def messageId( self, messageId ):
mi = long( messageId )
assert( 0 <= mi <= _UINT64_MAX ), \
"Assigned value (%d) out of range." % mi
self._messageId = mi | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def treeId( self ):
"""Get/set the Tree Connect ID (ULONG).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to a <long>) is either negative or greater
than 0xFFFFFFFF.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into a <long>.
"""
return( self._treeId ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def treeId( self, treeId ):
tid = long( treeId )
assert( 0 <= tid <= _ULONG_MAX ), \
"Assigned value (%d) out of range." % tid
self._treeId = tid | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def asyncId( self ):
"""Get/set the Async Id (UINT64).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to a <long>) is either negative or greater
than (2^64)-1.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into a <long>.
"""
return( self._asyncId ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def asyncId( selfd, asyncId ):
ai = long( asyncId )
assert( 0 <= ai <= _UINT64_MAX ), \
"Assigned value (%d) out of range." % ai
self._asyncId = ai | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def sessionId( self ):
"""Get/set the Session Id (UINT64).
Errors:
AssertionError - Thrown if the assigned value (after conversion
to a <long>) is either negative or greater
than (2^64)-1.
[ TypeError, - Either of these may be thrown if the assigned
ValueError ] value cannot be converted into a <long>.
"""
return( self._sessionId ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def sessionId( self, sessionId ):
si = long( sessionId )
assert( 0 <= si <= _UINT64_MAX ), \
"Assigned value (%d) out of range." % si
self._sessionId = si | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def signature( self ):
"""Get/set the packet signature.
Errors:
AssertionError - Thrown if the string representation of the
assigned value is not exactly 16 bytes.
SyntaxError - Thrown if the assigned value is not of type
<str> and cannot be converted to type <str>.
"""
return( self._signature ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def signature( self, signature ):
sig = str( signature )
assert( 16 == len( sig ) ), "Exactly 16 bytes required."
self._signature = sig | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def _flagGet( self, flag ):
return( bool( flag & self._flags ) ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagReply( self ):
"""Get/set the SMB2_FLAGS_SERVER_TO_REDIR (Reply) bit.
The assigned value is evaluated as a boolean:
True = set the bit; False = clear it.
"""
return( self._flagGet( SMB2_FLAGS_SERVER_TO_REDIR ) ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagReply( self, bitState ):
self._flagSet( SMB2_FLAGS_SERVER_TO_REDIR, bitState ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagAsync( self ):
"""Get/set the SMB2_FLAGS_ASYNC_COMMAND (Async) bit.
The assigned value is evaluated as a boolean:
True = set the bit; False = clear it.
"""
return( self._flagGet( SMB2_FLAGS_ASYNC_COMMAND ) ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagAsync( self, bitState ):
self._flagSet( SMB2_FLAGS_ASYNC_COMMAND, bitState ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagNext( self ):
"""Get/set the SMB2_FLAGS_RELATED_OPERATIONS (Next) bit.
The assigned value is evaluated as a boolean:
True = set the bit; False = clear it.
"""
return( self._flagGet( SMB2_FLAGS_RELATED_OPERATIONS ) ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagNext( self, bitState ):
self._flagSet( SMB2_FLAGS_RELATED_OPERATIONS, bitState ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagSigned( self ):
"""Get/set the SMB2_FLAGS_SIGNED (Signed) bit.
The assigned value is evaluated as a boolean:
True = set the bit; False = clear it.
"""
return( self._flagGet( SMB2_FLAGS_SIGNED ) ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagSigned( self, bitState ):
self._flagSet( SMB2_FLAGS_SIGNED, bitState ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagDFS( self ):
"""Get/set the SMB2_FLAGS_DFS_OPERATIONS (DFS) bit.
The assigned value is evaluated as a boolean:
True = set the bit; False = clear it.
"""
return( self._flagGet( SMB2_FLAGS_DFS_OPERATIONS ) ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagDFS( self, bitState ):
self._flagSet( SMB2_FLAGS_DFS_OPERATIONS, bitState ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagReplay( self ):
"""Get/set the SMB2_FLAGS_REPLAY_OPERATION (Replay) bit.
The assigned value is evaluated as a boolean:
True = set the bit; False = clear it.
"""
return( self._flagGet( SMB2_FLAGS_REPLAY_OPERATION ) ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagReplay( self, bitState ):
self._flagSet( SMB2_FLAGS_REPLAY_OPERATION, bitState ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagPriority( self ):
"""Get/set the SMBv3.1.1+ Priority subfield.
This value is actually a 3-bit integer (in the range 0..7).
Errors:
ValueError - Thrown if the assigned value is outside of the
valid range.
"""
return( (self._flags & SMB2_FLAGS_PRIORITY_MASK) >> 4 ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def flagPriority( self, prioVal ):
if( prioVal not in range( 8 ) ):
raise ValueError( "Assigned value (%d) out of range." % prioVal )
self._flags &= ~SMB2_FLAGS_PRIORITY_MASK
self._flags |= (prioVal << 4) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def compose( self ):
# Marshall the SMB2 header fields into a stream of bytes.
#
# Output: A string of bytes; the wire format of the SMB2 header.
#
# Notes: It's probably okay if the dialect version isn't
# specified. The default values of <channelSeq> and
# <reserved1> are zero, so the encoded format would be
# zero for either interpretation.
#
if( self.flagReply or (self._dialect < 0x0300) ):
# Bytes 8..11 are <status>
if( self.flagAsync ):
# Bytes 32..39 are <async>
msg = self._format_SMB2_StatAsync.pack( self._protocolId,
self._headerSize,
self._creditCharge,
self._status,
self._command,
self._creditReqResp,
self._flags,
self._nextCommand,
self._messageId,
self._asyncId,
self._sessionId,
self._signature )
else:
# Bytes 32..39 are <reserved2>/<treeId>
msg = self._format_SMB2_StatTreeId.pack( self._protocolId,
self._headerSize,
self._creditCharge,
self._status,
self._command,
self._creditReqResp,
self._flags,
self._nextCommand,
self._messageId,
self._reserved2,
self._treeId,
self._sessionId,
self._signature )
else:
# Bytes 8..11 are <channelSeq>/<reserved1>
if( self.flagAsync ):
# Bytes 32..39 are <async>
msg = self._format_SMB2_cSeqAsync.pack( self._protocolId,
self._headerSize,
self._creditCharge,
self._channelSeq,
self._reserved1,
self._command,
self._creditReqResp,
self._flags,
self._nextCommand,
self._messageId,
self._asyncId,
self._sessionId,
self._signature )
else:
# Bytes 32..39 are <reserved2>/<treeId>
msg = self._format_SMB2_cSeqTreeId.pack( self._protocolId,
self._headerSize,
self._creditCharge,
self._channelSeq,
self._reserved1,
self._command,
self._creditReqResp,
self._flags,
self._nextCommand,
self._messageId,
self._reserved2,
self._treeId,
self._sessionId,
self._signature )
return( msg ) | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def _unit_test():
# Module unit tests.
#
"""
Doctest:
>>> _unit_test()
Success
"""
if( __debug__ ):
# 1.Baseline test.
# Just verify that we can store and retrieve the basic attributes
# of an _SMB2_Header object.
#
hdr = _SMB2_Header( SMB2_COM_LOGOFF, SMB2_DIALECT_302 )
hdr.creditCharge = 213
hdr.channelSeq = 42607
hdr.creditReqResp = 42
hdr.flagReply = False
hdr.flagAsync = False
hdr.flagNext = False
hdr.flagSigned = False
hdr.flagPriority = 5
hdr.flagDFS = True
hdr.flagReplay = False
hdr.nextCommand = 0x87654321
hdr.messageId = _SMB2_Header._format_Q.unpack( "Fooberry" )[0]
hdr.treeId = 0xBEADED
hdr.sessionId = _SMB2_Header._format_Q.unpack( "Icecream" )[0]
hdr.signature = "Reginald".center( 16 )
# Create a header dump, compose a message, then parse the message.
dmp0 = hdr.dump()
msg = hdr.compose()
hdr = _SMB2_Header.parseMsg( msg, SMB2_DIALECT_302 )
# Dump the newly reparsed header, and compare against the original.
dmp1 = hdr.dump()
if( dmp0 != dmp1 ):
print "Failure: Reparsing a composed header resulted in differences."
print "As composed:\n", dmp0
print "As parsed:\n", dmp1
return
# 2.Add additional tests hereafter.
# Bottom line.
print "Success" | ubiqx-org/Carnaval | [
11,
5,
11,
1,
1396561525
] |
def install():
install_salt_support()
update_machine_state('machine_states/dependencies.yaml')
update_machine_state('machine_states/installed.yaml') | Ubuntu-Solutions-Engineering/glance-simplestreams-sync-charm | [
3,
1,
3,
2,
1400611874
] |
def install_salt_support(from_ppa=True):
"""Installs the salt-minion helper for machine state.
By default the salt-minion package is installed from
the saltstack PPA. If from_ppa is False you must ensure
that the salt-minion package is available in the apt cache.
"""
if from_ppa:
subprocess.check_call([
'/usr/bin/add-apt-repository',
'--yes',
'ppa:saltstack/salt',
])
subprocess.check_call(['/usr/bin/apt-get', 'update'])
# We install salt-common as salt-minion would run the salt-minion
# daemon.
charmhelpers.fetch.apt_install('salt-common') | Ubuntu-Solutions-Engineering/glance-simplestreams-sync-charm | [
3,
1,
3,
2,
1400611874
] |
def patch_psycopg():
"""Configure Psycopg to be used with gevent in non-blocking way."""
if not hasattr(extensions, 'set_wait_callback'):
raise ImportError(
"support for coroutines not available in this Psycopg version (%s)"
% psycopg2.__version__)
extensions.set_wait_callback(gevent_wait_callback) | funkring/fdoo | [
1,
5,
1,
8,
1400249085
] |
def __init__(self, dsn, max_con=10, max_idle=3,
connection_factory=RealDictConnection):
self.dsn = dsn
self.max_con = max_con
self.max_idle = max_idle
self.connection_factory = connection_factory
self._sem = Semaphore(max_con)
self._free = []
self._local = gevent_local() | funkring/fdoo | [
1,
5,
1,
8,
1400249085
] |
def __exit__(self, exc_type, exc_value, traceback):
try:
if self._local.con is None:
raise RuntimeError("Exit connection pool with no connection?")
if exc_type is not None:
self.rollback()
else:
self.commit()
if len(self._free) < self.max_idle:
self._free.append(self._local.con)
self._local.con = None
finally:
self._sem.release() | funkring/fdoo | [
1,
5,
1,
8,
1400249085
] |
def main():
memberships = Membership.objects.language("en").all()
for membership in memberships:
if not membership.organization:
if membership.post:
if membership.post.organization:
membership.organization = membership.post.organization
membership.save() | Sinar/popit_ng | [
21,
4,
21,
91,
1443407491
] |
def session_started(self):
self.stream.send(Presence()) | Jajcus/pyxmpp | [
27,
9,
27,
6,
1304423454
] |
def post_disconnect(self):
print "Disconnected"
raise Disconnected | Jajcus/pyxmpp | [
27,
9,
27,
6,
1304423454
] |
def __init__(self, **kwargs):
Handler.__init__(self, **kwargs) | DinoTools/ArduRPC-python | [
2,
1,
2,
1,
1392998168
] |
def getHeight(self):
"""
Get the display height as number of characters.
:return: Height
:rtype: Integer
"""
return self._call(0x02) | DinoTools/ArduRPC-python | [
2,
1,
2,
1,
1392998168
] |
def home(self):
"""
Set the cursor position to the upper-left corner.
"""
return self._call(0x12) | DinoTools/ArduRPC-python | [
2,
1,
2,
1,
1392998168
] |
def write(self, c):
"""
Print a single character to the LCD.
"""
c = c.encode('ASCII')
return self._call(0x21, '>B', c[0]) | DinoTools/ArduRPC-python | [
2,
1,
2,
1,
1392998168
] |
def __init__(self, name, experiment, description=''):
super(Vaunix, self).__init__(name, experiment, description)
self.frequency = FloatProp('Frequency', experiment, 'Frequency (MHz)', '0')
self.power = FloatProp('Power', experiment, 'Power (dBm)', '0')
self.pulsewidth = FloatProp('PulseWidth', experiment, 'Pulse Width (us)', '0')
self.pulserep = FloatProp('PulseRep', experiment, 'Pulse Rep Time (us)', '0')
self.startfreq = FloatProp('StartFreq', experiment, 'Start Frequency (MHz)', '0')
self.endfreq = FloatProp('EndFreq', experiment, 'End Frequency (MHz)', '0')
self.sweeptime = IntProp('SweepTime', experiment, 'Sweep Time (ms)', '0')
self.properties += ['ID', 'model', 'serial', 'frequency','power','pulsewidth','pulserep','pulseenable','startfreq','endfreq','sweeptime',
'sweepmode', 'sweeptype', 'sweepdir', 'sweepenable', 'internalref', 'useexternalmod', 'rfonoff', 'maxPower'] | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def initialize(self,va):
self.va = va
errcode = self.va.fnLMS_InitDevice(self.ID)
if (errcode !=0):
errcodereset = self.va.fnLMS_CloseDevice(self.ID)
if (errcodereset != 0): #if device fails to initialize, it may be because it was not closed previously. Try closing and reinitializing it.
logger.error("Failed to initialize Vaunix device {}. Error code {}.".format(self.ID,errcode))
raise PauseError
errcode = self.va.fnLMS_InitDevice(self.ID)
if (errcode != 0):
logger.error("Failed to initialize Vaunix device {}. Error code {}.".format(self.ID,errcode))
raise PauseError
self.maxPower = int(self.va.fnLMS_GetMaxPwr(self.ID)/4)
self.minPower = int(self.va.fnLMS_GetMinPwr(self.ID)/4)
self.minFreq = int(self.va.fnLMS_GetMinFreq(self.ID))
self.maxFreq = int(self.va.fnLMS_GetMaxFreq(self.ID)) | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def freq_unit(self,val):
return int(val*100000) | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def power_unit(self,value):
return int((self.maxPower - value)*4) | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def power_sanity_check(self,value):
if (value < self.minPower or value > self.maxPower):
logger.error("Vaunix device {} power ({} dBm) outside min/max range: {} dBm, {} dBm.".format(self.ID,value,self.minPower,self.maxPower))
raise PauseError
return | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def freq_sanity_check(self,value):
if (value < self.minFreq or value > self.maxFreq):
logger.error("Vaunix device {} frequency ({} x10 Hz) outside min/max range: {} x10 Hz, {} x10 Hz.".format(self.ID,value,self.minFreq,self.maxFreq))
raise PauseError
return | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def update(self):
if (self.rfonoff):
self.freq_sanity_check(self.freq_unit(self.frequency.value))
self.va.fnLMS_SetFrequency(self.ID, self.freq_unit(self.frequency.value)) | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def getparams(self):
logger.info("Parameters for Vaunix # {}".format(self.ID))
logger.info("Frequency: {} MHz".format(
self.va.fnLMS_GetFrequency(self.ID)/100000))
logger.info("Power Level: {} dBm".format(
self.va.fnLMS_GetPowerLevel(self.ID)/4)) | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def __init__(self, name, experiment, description=''):
super(Vaunixs, self).__init__(name, experiment, description)
self.motors = ListProp('motors', experiment, 'A list of individual Vaunix signal generators', listElementType=Vaunix,
listElementName='Vaunix')
self.properties += ['version', 'motors']
num = self.initialize()
self.motors.length = num
self.motors.refreshGUI() | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def initialize(self):
num = 0
if self.enable:
CDLL_file = "./vaunix/VNX_fmsynth.dll"
self.va = CDLL(CDLL_file)
if (self.testMode):
logger.warning("Warning: Vaunix in test mode. Set testMode=False in vaunix.py to turn off test mode.")
self.va.fnLMS_SetTestMode(self.testMode) #Test mode... this needs to be set False for actual run. Do not remove this command (default setting is True).
self.isInitialized = True
num = self.detect_generators()
return num | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def preExperiment(self, hdf5):
if self.enable:
if (not self.isInitialized):
self.initialize()
for i in self.motors:
#initialize serial connection to each power supply
i.initialize(self.va) | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def preIteration(self, iterationresults, hdf5):
"""
Every iteration, send the motors updated positions.
"""
if self.enable:
msg = ''
try:
for i in self.motors:
i.update()
except Exception as e:
logger.error('Problem updating Vaunix:\n{}\n{}\n'.format(msg, e))
self.isInitialized = False
raise PauseError | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def postMeasurement(self, measurementresults, iterationresults, hdf5):
return | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def postIteration(self, iterationresults, hdf5):
return | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def postExperiment(self, hdf5):
return | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def finalize(self,hdf5):
return | QuantumQuadrate/CsPyController | [
3,
2,
3,
24,
1492572590
] |
def __init__(self, parent = None):
super().__init__(parent)
self._component = None
self._context = None
self._view = None
self._qml_url = "WorkspaceDialog.qml"
self._lock = threading.Lock()
self._default_strategy = None
self._result = {"machine": self._default_strategy,
"quality_changes": self._default_strategy,
"definition_changes": self._default_strategy,
"material": self._default_strategy}
self._override_machine = None
self._visible = False
self.showDialogSignal.connect(self.__show)
self._has_quality_changes_conflict = False
self._has_definition_changes_conflict = False
self._has_machine_conflict = False
self._has_material_conflict = False
self._has_visible_settings_field = False
self._num_visible_settings = 0
self._num_user_settings = 0
self._active_mode = ""
self._quality_name = ""
self._num_settings_overridden_by_quality_changes = 0
self._quality_type = ""
self._intent_name = ""
self._machine_name = ""
self._machine_type = ""
self._variant_type = ""
self._material_labels = []
self._extruders = []
self._objects_on_plate = False
self._is_printer_group = False
self._updatable_machines_model = UpdatableMachinesModel(self) | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def isPrinterGroup(self) -> bool:
return self._is_printer_group | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def variantType(self) -> str:
return self._variant_type | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def machineType(self) -> str:
return self._machine_type | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def setNumUserSettings(self, num_user_settings: int) -> None:
if self._num_user_settings != num_user_settings:
self._num_user_settings = num_user_settings
self.numVisibleSettingsChanged.emit() | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def numUserSettings(self) -> int:
return self._num_user_settings | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def hasObjectsOnPlate(self) -> bool:
return self._objects_on_plate | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def materialLabels(self) -> List[str]:
return self._material_labels | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
def extruders(self):
return self._extruders | Ultimaker/Cura | [
4656,
1806,
4656,
2468,
1402923331
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.