repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.limit
def limit(self, limit): """ Apply a LIMIT to the query and return the newly resulting Query. """ query = self._copy() query._limit = limit return query
python
def limit(self, limit): """ Apply a LIMIT to the query and return the newly resulting Query. """ query = self._copy() query._limit = limit return query
[ "def", "limit", "(", "self", ",", "limit", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "_limit", "=", "limit", "return", "query" ]
Apply a LIMIT to the query and return the newly resulting Query.
[ "Apply", "a", "LIMIT", "to", "the", "query", "and", "return", "the", "newly", "resulting", "Query", "." ]
180ac969c427b1292439a0371866aa5f169ffa6b
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L437-L443
train
37,000
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.offset
def offset(self, offset): """ Apply an OFFSET to the query and return the newly resulting Query. """ query = self._copy() query._offset = offset return query
python
def offset(self, offset): """ Apply an OFFSET to the query and return the newly resulting Query. """ query = self._copy() query._offset = offset return query
[ "def", "offset", "(", "self", ",", "offset", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "_offset", "=", "offset", "return", "query" ]
Apply an OFFSET to the query and return the newly resulting Query.
[ "Apply", "an", "OFFSET", "to", "the", "query", "and", "return", "the", "newly", "resulting", "Query", "." ]
180ac969c427b1292439a0371866aa5f169ffa6b
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L445-L451
train
37,001
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.one
def one(self): """ Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found. """ results = self.rpc_model.search_read( self.domain, 2, None, self._order_by, self.fields, context=self.context ) if not results: raise fulfil_client.exc.NoResultFound if len(results) > 1: raise fulfil_client.exc.MultipleResultsFound return results[0]
python
def one(self): """ Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found. """ results = self.rpc_model.search_read( self.domain, 2, None, self._order_by, self.fields, context=self.context ) if not results: raise fulfil_client.exc.NoResultFound if len(results) > 1: raise fulfil_client.exc.MultipleResultsFound return results[0]
[ "def", "one", "(", "self", ")", ":", "results", "=", "self", ".", "rpc_model", ".", "search_read", "(", "self", ".", "domain", ",", "2", ",", "None", ",", "self", ".", "_order_by", ",", "self", ".", "fields", ",", "context", "=", "self", ".", "cont...
Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found.
[ "Return", "exactly", "one", "result", "or", "raise", "an", "exception", "." ]
180ac969c427b1292439a0371866aa5f169ffa6b
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L454-L470
train
37,002
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.order_by
def order_by(self, *criterion): """ apply one or more ORDER BY criterion to the query and return the newly resulting Query All existing ORDER BY settings can be suppressed by passing None - this will suppress any ORDER BY configured on mappers as well. """ query = self._copy() query._order_by = criterion return query
python
def order_by(self, *criterion): """ apply one or more ORDER BY criterion to the query and return the newly resulting Query All existing ORDER BY settings can be suppressed by passing None - this will suppress any ORDER BY configured on mappers as well. """ query = self._copy() query._order_by = criterion return query
[ "def", "order_by", "(", "self", ",", "*", "criterion", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "_order_by", "=", "criterion", "return", "query" ]
apply one or more ORDER BY criterion to the query and return the newly resulting Query All existing ORDER BY settings can be suppressed by passing None - this will suppress any ORDER BY configured on mappers as well.
[ "apply", "one", "or", "more", "ORDER", "BY", "criterion", "to", "the", "query", "and", "return", "the", "newly", "resulting", "Query" ]
180ac969c427b1292439a0371866aa5f169ffa6b
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L472-L482
train
37,003
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.delete
def delete(self): """ Delete all records matching the query. Warning: This is a desctructive operation. Not every model allows deletion of records and several models even restrict based on status. For example, deleting products that have been transacted is restricted. Another example is sales orders which can be deleted only when they are draft. If deletion fails, a server error is thrown. """ ids = self.rpc_model.search(self.domain, context=self.context) if ids: self.rpc_model.delete(ids)
python
def delete(self): """ Delete all records matching the query. Warning: This is a desctructive operation. Not every model allows deletion of records and several models even restrict based on status. For example, deleting products that have been transacted is restricted. Another example is sales orders which can be deleted only when they are draft. If deletion fails, a server error is thrown. """ ids = self.rpc_model.search(self.domain, context=self.context) if ids: self.rpc_model.delete(ids)
[ "def", "delete", "(", "self", ")", ":", "ids", "=", "self", ".", "rpc_model", ".", "search", "(", "self", ".", "domain", ",", "context", "=", "self", ".", "context", ")", "if", "ids", ":", "self", ".", "rpc_model", ".", "delete", "(", "ids", ")" ]
Delete all records matching the query. Warning: This is a desctructive operation. Not every model allows deletion of records and several models even restrict based on status. For example, deleting products that have been transacted is restricted. Another example is sales orders which can be deleted only when they are draft. If deletion fails, a server error is thrown.
[ "Delete", "all", "records", "matching", "the", "query", "." ]
180ac969c427b1292439a0371866aa5f169ffa6b
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L484-L499
train
37,004
317070/python-twitch-stream
twitchstream/chat.py
TwitchChatStream._logged_in_successful
def _logged_in_successful(data): """ Test the login status from the returned communication of the server. :param data: bytes received from server during login :type data: list of bytes :return boolean, True when you are logged in. """ if re.match(r'^:(testserver\.local|tmi\.twitch\.tv)' r' NOTICE \* :' r'(Login unsuccessful|Error logging in)*$', data.strip()): return False else: return True
python
def _logged_in_successful(data): """ Test the login status from the returned communication of the server. :param data: bytes received from server during login :type data: list of bytes :return boolean, True when you are logged in. """ if re.match(r'^:(testserver\.local|tmi\.twitch\.tv)' r' NOTICE \* :' r'(Login unsuccessful|Error logging in)*$', data.strip()): return False else: return True
[ "def", "_logged_in_successful", "(", "data", ")", ":", "if", "re", ".", "match", "(", "r'^:(testserver\\.local|tmi\\.twitch\\.tv)'", "r' NOTICE \\* :'", "r'(Login unsuccessful|Error logging in)*$'", ",", "data", ".", "strip", "(", ")", ")", ":", "return", "False", "el...
Test the login status from the returned communication of the server. :param data: bytes received from server during login :type data: list of bytes :return boolean, True when you are logged in.
[ "Test", "the", "login", "status", "from", "the", "returned", "communication", "of", "the", "server", "." ]
83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6
https://github.com/317070/python-twitch-stream/blob/83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6/twitchstream/chat.py#L51-L67
train
37,005
317070/python-twitch-stream
twitchstream/chat.py
TwitchChatStream.connect
def connect(self): """ Connect to Twitch """ # Do not use non-blocking stream, they are not reliably # non-blocking # s.setblocking(False) # s.settimeout(1.0) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect_host = "irc.twitch.tv" connect_port = 6667 try: s.connect((connect_host, connect_port)) except (Exception, IOError): print("Unable to create a socket to %s:%s" % ( connect_host, connect_port)) raise # unexpected, because it is a blocking socket # Connected to twitch # Sending our details to twitch... s.send(('PASS %s\r\n' % self.oauth).encode('utf-8')) s.send(('NICK %s\r\n' % self.username).encode('utf-8')) if self.verbose: print('PASS %s\r\n' % self.oauth) print('NICK %s\r\n' % self.username) received = s.recv(1024).decode() if self.verbose: print(received) if not TwitchChatStream._logged_in_successful(received): # ... and they didn't accept our details raise IOError("Twitch did not accept the username-oauth " "combination") else: # ... and they accepted our details # Connected to twitch.tv! # now make this socket non-blocking on the OS-level fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK) if self.s is not None: self.s.close() # close the previous socket self.s = s # store the new socket self.join_channel(self.username) # Wait until we have switched channels while self.current_channel != self.username: self.twitch_receive_messages()
python
def connect(self): """ Connect to Twitch """ # Do not use non-blocking stream, they are not reliably # non-blocking # s.setblocking(False) # s.settimeout(1.0) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect_host = "irc.twitch.tv" connect_port = 6667 try: s.connect((connect_host, connect_port)) except (Exception, IOError): print("Unable to create a socket to %s:%s" % ( connect_host, connect_port)) raise # unexpected, because it is a blocking socket # Connected to twitch # Sending our details to twitch... s.send(('PASS %s\r\n' % self.oauth).encode('utf-8')) s.send(('NICK %s\r\n' % self.username).encode('utf-8')) if self.verbose: print('PASS %s\r\n' % self.oauth) print('NICK %s\r\n' % self.username) received = s.recv(1024).decode() if self.verbose: print(received) if not TwitchChatStream._logged_in_successful(received): # ... and they didn't accept our details raise IOError("Twitch did not accept the username-oauth " "combination") else: # ... and they accepted our details # Connected to twitch.tv! # now make this socket non-blocking on the OS-level fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK) if self.s is not None: self.s.close() # close the previous socket self.s = s # store the new socket self.join_channel(self.username) # Wait until we have switched channels while self.current_channel != self.username: self.twitch_receive_messages()
[ "def", "connect", "(", "self", ")", ":", "# Do not use non-blocking stream, they are not reliably", "# non-blocking", "# s.setblocking(False)", "# s.settimeout(1.0)", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")...
Connect to Twitch
[ "Connect", "to", "Twitch" ]
83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6
https://github.com/317070/python-twitch-stream/blob/83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6/twitchstream/chat.py#L109-L157
train
37,006
317070/python-twitch-stream
twitchstream/chat.py
TwitchChatStream._push_from_buffer
def _push_from_buffer(self): """ Push a message on the stack to the IRC stream. This is necessary to avoid Twitch overflow control. """ if len(self.buffer) > 0: if time.time() - self.last_sent_time > 5: try: message = self.buffer.pop(0) self.s.send(message.encode('utf-8')) if self.verbose: print(message) finally: self.last_sent_time = time.time()
python
def _push_from_buffer(self): """ Push a message on the stack to the IRC stream. This is necessary to avoid Twitch overflow control. """ if len(self.buffer) > 0: if time.time() - self.last_sent_time > 5: try: message = self.buffer.pop(0) self.s.send(message.encode('utf-8')) if self.verbose: print(message) finally: self.last_sent_time = time.time()
[ "def", "_push_from_buffer", "(", "self", ")", ":", "if", "len", "(", "self", ".", "buffer", ")", ">", "0", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "last_sent_time", ">", "5", ":", "try", ":", "message", "=", "self", ".", "buff...
Push a message on the stack to the IRC stream. This is necessary to avoid Twitch overflow control.
[ "Push", "a", "message", "on", "the", "stack", "to", "the", "IRC", "stream", ".", "This", "is", "necessary", "to", "avoid", "Twitch", "overflow", "control", "." ]
83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6
https://github.com/317070/python-twitch-stream/blob/83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6/twitchstream/chat.py#L159-L172
train
37,007
317070/python-twitch-stream
twitchstream/chat.py
TwitchChatStream.join_channel
def join_channel(self, channel): """ Join a different chat channel on Twitch. Note, this function returns immediately, but the switch might take a moment :param channel: name of the channel (without #) """ self.s.send(('JOIN #%s\r\n' % channel).encode('utf-8')) if self.verbose: print('JOIN #%s\r\n' % channel)
python
def join_channel(self, channel): """ Join a different chat channel on Twitch. Note, this function returns immediately, but the switch might take a moment :param channel: name of the channel (without #) """ self.s.send(('JOIN #%s\r\n' % channel).encode('utf-8')) if self.verbose: print('JOIN #%s\r\n' % channel)
[ "def", "join_channel", "(", "self", ",", "channel", ")", ":", "self", ".", "s", ".", "send", "(", "(", "'JOIN #%s\\r\\n'", "%", "channel", ")", ".", "encode", "(", "'utf-8'", ")", ")", "if", "self", ".", "verbose", ":", "print", "(", "'JOIN #%s\\r\\n'"...
Join a different chat channel on Twitch. Note, this function returns immediately, but the switch might take a moment :param channel: name of the channel (without #)
[ "Join", "a", "different", "chat", "channel", "on", "Twitch", ".", "Note", "this", "function", "returns", "immediately", "but", "the", "switch", "might", "take", "a", "moment" ]
83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6
https://github.com/317070/python-twitch-stream/blob/83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6/twitchstream/chat.py#L190-L200
train
37,008
317070/python-twitch-stream
twitchstream/chat.py
TwitchChatStream._parse_message
def _parse_message(self, data): """ Parse the bytes received from the socket. :param data: the bytes received from the socket :return: """ if TwitchChatStream._check_has_ping(data): self._send_pong() if TwitchChatStream._check_has_channel(data): self.current_channel = \ TwitchChatStream._check_has_channel(data)[0] if TwitchChatStream._check_has_message(data): return { 'channel': re.findall(r'^:.+![a-zA-Z0-9_]+' r'@[a-zA-Z0-9_]+' r'.+ ' r'PRIVMSG (.*?) :', data)[0], 'username': re.findall(r'^:([a-zA-Z0-9_]+)!', data)[0], 'message': re.findall(r'PRIVMSG #[a-zA-Z0-9_]+ :(.+)', data)[0].decode('utf8') } else: return None
python
def _parse_message(self, data): """ Parse the bytes received from the socket. :param data: the bytes received from the socket :return: """ if TwitchChatStream._check_has_ping(data): self._send_pong() if TwitchChatStream._check_has_channel(data): self.current_channel = \ TwitchChatStream._check_has_channel(data)[0] if TwitchChatStream._check_has_message(data): return { 'channel': re.findall(r'^:.+![a-zA-Z0-9_]+' r'@[a-zA-Z0-9_]+' r'.+ ' r'PRIVMSG (.*?) :', data)[0], 'username': re.findall(r'^:([a-zA-Z0-9_]+)!', data)[0], 'message': re.findall(r'PRIVMSG #[a-zA-Z0-9_]+ :(.+)', data)[0].decode('utf8') } else: return None
[ "def", "_parse_message", "(", "self", ",", "data", ")", ":", "if", "TwitchChatStream", ".", "_check_has_ping", "(", "data", ")", ":", "self", ".", "_send_pong", "(", ")", "if", "TwitchChatStream", ".", "_check_has_channel", "(", "data", ")", ":", "self", "...
Parse the bytes received from the socket. :param data: the bytes received from the socket :return:
[ "Parse", "the", "bytes", "received", "from", "the", "socket", "." ]
83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6
https://github.com/317070/python-twitch-stream/blob/83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6/twitchstream/chat.py#L210-L235
train
37,009
317070/python-twitch-stream
twitchstream/outputvideo.py
TwitchOutputStream.reset
def reset(self): """ Reset the videostream by restarting ffmpeg """ if self.ffmpeg_process is not None: # Close the previous stream try: self.ffmpeg_process.send_signal(signal.SIGINT) except OSError: pass command = [] command.extend([ self.ffmpeg_binary, '-loglevel', 'verbose', '-y', # overwrite previous file/stream # '-re', # native frame-rate '-analyzeduration', '1', '-f', 'rawvideo', '-r', '%d' % self.fps, # set a fixed frame rate '-vcodec', 'rawvideo', # size of one frame '-s', '%dx%d' % (self.width, self.height), '-pix_fmt', 'rgb24', # The input are raw bytes '-thread_queue_size', '1024', '-i', '/tmp/videopipe', # The input comes from a pipe # Twitch needs to receive sound in their streams! # '-an', # Tells FFMPEG not to expect any audio ]) if self.audio_enabled: command.extend([ '-ar', '%d' % AUDIORATE, '-ac', '2', '-f', 's16le', '-thread_queue_size', '1024', '-i', '/tmp/audiopipe' ]) else: command.extend([ '-ar', '8000', '-ac', '1', '-f', 's16le', '-i', '/dev/zero', # silence alternative, works forever # '-i','http://stream1.radiostyle.ru:8001/tunguska', # '-filter_complex', # '[0:1][1:0]amix=inputs=2:duration=first[all_audio]' ]) command.extend([ # VIDEO CODEC PARAMETERS '-vcodec', 'libx264', '-r', '%d' % self.fps, '-b:v', '3000k', '-s', '%dx%d' % (self.width, self.height), '-preset', 'faster', '-tune', 'zerolatency', '-crf', '23', '-pix_fmt', 'yuv420p', # '-force_key_frames', r'expr:gte(t,n_forced*2)', '-minrate', '3000k', '-maxrate', '3000k', '-bufsize', '12000k', '-g', '60', # key frame distance '-keyint_min', '1', # '-filter:v "setpts=0.25*PTS"' # '-vsync','passthrough', # AUDIO CODEC PARAMETERS '-acodec', 'libmp3lame', '-ar', '44100', '-b:a', '160k', # '-bufsize', '8192k', '-ac', '1', # '-acodec', 'aac', '-strict', 'experimental', # '-ab', '128k', '-ar', '44100', '-ac', '1', # '-async','44100', # '-filter_complex', 'asplit', #for audio sync? # STORE THE VIDEO PARAMETERS # '-vcodec', 'libx264', '-s', '%dx%d'%(width, height), # '-preset', 'libx264-fast', # 'my_output_videofile2.avi' # MAP THE STREAMS # use only video from first input and only audio from second '-map', '0:v', '-map', '1:a', # NUMBER OF THREADS '-threads', '2', # STREAM TO TWITCH '-f', 'flv', 'rtmp://live-ams.twitch.tv/app/%s' % self.twitch_stream_key ]) devnullpipe = open("/dev/null", "w") # Throw away stream if self.verbose: devnullpipe = None self.ffmpeg_process = subprocess.Popen( command, stdin=subprocess.PIPE, stderr=devnullpipe, stdout=devnullpipe)
python
def reset(self): """ Reset the videostream by restarting ffmpeg """ if self.ffmpeg_process is not None: # Close the previous stream try: self.ffmpeg_process.send_signal(signal.SIGINT) except OSError: pass command = [] command.extend([ self.ffmpeg_binary, '-loglevel', 'verbose', '-y', # overwrite previous file/stream # '-re', # native frame-rate '-analyzeduration', '1', '-f', 'rawvideo', '-r', '%d' % self.fps, # set a fixed frame rate '-vcodec', 'rawvideo', # size of one frame '-s', '%dx%d' % (self.width, self.height), '-pix_fmt', 'rgb24', # The input are raw bytes '-thread_queue_size', '1024', '-i', '/tmp/videopipe', # The input comes from a pipe # Twitch needs to receive sound in their streams! # '-an', # Tells FFMPEG not to expect any audio ]) if self.audio_enabled: command.extend([ '-ar', '%d' % AUDIORATE, '-ac', '2', '-f', 's16le', '-thread_queue_size', '1024', '-i', '/tmp/audiopipe' ]) else: command.extend([ '-ar', '8000', '-ac', '1', '-f', 's16le', '-i', '/dev/zero', # silence alternative, works forever # '-i','http://stream1.radiostyle.ru:8001/tunguska', # '-filter_complex', # '[0:1][1:0]amix=inputs=2:duration=first[all_audio]' ]) command.extend([ # VIDEO CODEC PARAMETERS '-vcodec', 'libx264', '-r', '%d' % self.fps, '-b:v', '3000k', '-s', '%dx%d' % (self.width, self.height), '-preset', 'faster', '-tune', 'zerolatency', '-crf', '23', '-pix_fmt', 'yuv420p', # '-force_key_frames', r'expr:gte(t,n_forced*2)', '-minrate', '3000k', '-maxrate', '3000k', '-bufsize', '12000k', '-g', '60', # key frame distance '-keyint_min', '1', # '-filter:v "setpts=0.25*PTS"' # '-vsync','passthrough', # AUDIO CODEC PARAMETERS '-acodec', 'libmp3lame', '-ar', '44100', '-b:a', '160k', # '-bufsize', '8192k', '-ac', '1', # '-acodec', 'aac', '-strict', 'experimental', # '-ab', '128k', '-ar', '44100', '-ac', '1', # '-async','44100', # '-filter_complex', 'asplit', #for audio sync? # STORE THE VIDEO PARAMETERS # '-vcodec', 'libx264', '-s', '%dx%d'%(width, height), # '-preset', 'libx264-fast', # 'my_output_videofile2.avi' # MAP THE STREAMS # use only video from first input and only audio from second '-map', '0:v', '-map', '1:a', # NUMBER OF THREADS '-threads', '2', # STREAM TO TWITCH '-f', 'flv', 'rtmp://live-ams.twitch.tv/app/%s' % self.twitch_stream_key ]) devnullpipe = open("/dev/null", "w") # Throw away stream if self.verbose: devnullpipe = None self.ffmpeg_process = subprocess.Popen( command, stdin=subprocess.PIPE, stderr=devnullpipe, stdout=devnullpipe)
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "ffmpeg_process", "is", "not", "None", ":", "# Close the previous stream", "try", ":", "self", ".", "ffmpeg_process", ".", "send_signal", "(", "signal", ".", "SIGINT", ")", "except", "OSError", ":", ...
Reset the videostream by restarting ffmpeg
[ "Reset", "the", "videostream", "by", "restarting", "ffmpeg" ]
83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6
https://github.com/317070/python-twitch-stream/blob/83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6/twitchstream/outputvideo.py#L75-L174
train
37,010
317070/python-twitch-stream
twitchstream/outputvideo.py
TwitchOutputStream.send_audio
def send_audio(self, left_channel, right_channel): """Add the audio samples to the stream. The left and the right channel should have the same shape. Raises an OSError when the stream is closed. :param left_channel: array containing the audio signal. :type left_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. k can be any integer :param right_channel: array containing the audio signal. :type right_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. k can be any integer """ if self.audio_pipe is None: if not os.path.exists('/tmp/audiopipe'): os.mkfifo('/tmp/audiopipe') self.audio_pipe = os.open('/tmp/audiopipe', os.O_WRONLY) assert len(left_channel.shape) == 1 assert left_channel.shape == right_channel.shape frame = np.column_stack((left_channel, right_channel)).flatten() frame = np.clip(32767*frame, -32767, 32767).astype('int16') try: os.write(self.audio_pipe, frame.tostring()) except OSError: # The pipe has been closed. Reraise and handle it further # downstream raise
python
def send_audio(self, left_channel, right_channel): """Add the audio samples to the stream. The left and the right channel should have the same shape. Raises an OSError when the stream is closed. :param left_channel: array containing the audio signal. :type left_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. k can be any integer :param right_channel: array containing the audio signal. :type right_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. k can be any integer """ if self.audio_pipe is None: if not os.path.exists('/tmp/audiopipe'): os.mkfifo('/tmp/audiopipe') self.audio_pipe = os.open('/tmp/audiopipe', os.O_WRONLY) assert len(left_channel.shape) == 1 assert left_channel.shape == right_channel.shape frame = np.column_stack((left_channel, right_channel)).flatten() frame = np.clip(32767*frame, -32767, 32767).astype('int16') try: os.write(self.audio_pipe, frame.tostring()) except OSError: # The pipe has been closed. Reraise and handle it further # downstream raise
[ "def", "send_audio", "(", "self", ",", "left_channel", ",", "right_channel", ")", ":", "if", "self", ".", "audio_pipe", "is", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "'/tmp/audiopipe'", ")", ":", "os", ".", "mkfifo", "(", "'/tm...
Add the audio samples to the stream. The left and the right channel should have the same shape. Raises an OSError when the stream is closed. :param left_channel: array containing the audio signal. :type left_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. k can be any integer :param right_channel: array containing the audio signal. :type right_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. k can be any integer
[ "Add", "the", "audio", "samples", "to", "the", "stream", ".", "The", "left", "and", "the", "right", "channel", "should", "have", "the", "same", "shape", ".", "Raises", "an", "OSError", "when", "the", "stream", "is", "closed", "." ]
83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6
https://github.com/317070/python-twitch-stream/blob/83b4c2a27ee368fc3316b59ab1d25fcf0b0bcda6/twitchstream/outputvideo.py#L209-L237
train
37,011
flashingpumpkin/django-socialregistration
socialregistration/mixins.py
CommonMixin.import_attribute
def import_attribute(self, path): """ Import an attribute from a module. """ module = '.'.join(path.split('.')[:-1]) function = path.split('.')[-1] module = importlib.import_module(module) return getattr(module, function)
python
def import_attribute(self, path): """ Import an attribute from a module. """ module = '.'.join(path.split('.')[:-1]) function = path.split('.')[-1] module = importlib.import_module(module) return getattr(module, function)
[ "def", "import_attribute", "(", "self", ",", "path", ")", ":", "module", "=", "'.'", ".", "join", "(", "path", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "function", "=", "path", ".", "split", "(", "'.'", ")", "[", "-", "1", ...
Import an attribute from a module.
[ "Import", "an", "attribute", "from", "a", "module", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/mixins.py#L21-L29
train
37,012
flashingpumpkin/django-socialregistration
socialregistration/mixins.py
CommonMixin.inactive_response
def inactive_response(self, request): """ Return an inactive message. """ inactive_url = getattr(settings, 'LOGIN_INACTIVE_REDIRECT_URL', '') if inactive_url: return HttpResponseRedirect(inactive_url) else: return self.error_to_response(request, {'error': _("This user account is marked as inactive.")})
python
def inactive_response(self, request): """ Return an inactive message. """ inactive_url = getattr(settings, 'LOGIN_INACTIVE_REDIRECT_URL', '') if inactive_url: return HttpResponseRedirect(inactive_url) else: return self.error_to_response(request, {'error': _("This user account is marked as inactive.")})
[ "def", "inactive_response", "(", "self", ",", "request", ")", ":", "inactive_url", "=", "getattr", "(", "settings", ",", "'LOGIN_INACTIVE_REDIRECT_URL'", ",", "''", ")", "if", "inactive_url", ":", "return", "HttpResponseRedirect", "(", "inactive_url", ")", "else",...
Return an inactive message.
[ "Return", "an", "inactive", "message", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/mixins.py#L64-L72
train
37,013
flashingpumpkin/django-socialregistration
socialregistration/mixins.py
ProfileMixin.create_profile
def create_profile(self, user, save=False, **kwargs): """ Create a profile model. :param user: A user object :param save: If this is set, the profile will be saved to DB straight away :type save: bool """ profile = self.get_model()(user=user, **kwargs) if save: profile.save() return profile
python
def create_profile(self, user, save=False, **kwargs): """ Create a profile model. :param user: A user object :param save: If this is set, the profile will be saved to DB straight away :type save: bool """ profile = self.get_model()(user=user, **kwargs) if save: profile.save() return profile
[ "def", "create_profile", "(", "self", ",", "user", ",", "save", "=", "False", ",", "*", "*", "kwargs", ")", ":", "profile", "=", "self", ".", "get_model", "(", ")", "(", "user", "=", "user", ",", "*", "*", "kwargs", ")", "if", "save", ":", "profi...
Create a profile model. :param user: A user object :param save: If this is set, the profile will be saved to DB straight away :type save: bool
[ "Create", "a", "profile", "model", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/mixins.py#L128-L142
train
37,014
flashingpumpkin/django-socialregistration
socialregistration/mixins.py
ProfileMixin.get_or_create_profile
def get_or_create_profile(self, user, save=False, **kwargs): """ Return a profile from DB or if there is none, create a new one. :param user: A user object :param save: If set, a new profile will be saved. :type save: bool """ try: profile = self.get_model().objects.get(user=user, **kwargs) return profile, False except self.get_model().DoesNotExist: profile = self.create_profile(user, save=save, **kwargs) return profile, True
python
def get_or_create_profile(self, user, save=False, **kwargs): """ Return a profile from DB or if there is none, create a new one. :param user: A user object :param save: If set, a new profile will be saved. :type save: bool """ try: profile = self.get_model().objects.get(user=user, **kwargs) return profile, False except self.get_model().DoesNotExist: profile = self.create_profile(user, save=save, **kwargs) return profile, True
[ "def", "get_or_create_profile", "(", "self", ",", "user", ",", "save", "=", "False", ",", "*", "*", "kwargs", ")", ":", "try", ":", "profile", "=", "self", ".", "get_model", "(", ")", ".", "objects", ".", "get", "(", "user", "=", "user", ",", "*", ...
Return a profile from DB or if there is none, create a new one. :param user: A user object :param save: If set, a new profile will be saved. :type save: bool
[ "Return", "a", "profile", "from", "DB", "or", "if", "there", "is", "none", "create", "a", "new", "one", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/mixins.py#L150-L163
train
37,015
flashingpumpkin/django-socialregistration
socialregistration/contrib/foursquare/client.py
Foursquare.request_access_token
def request_access_token(self, params): """ Foursquare does not accept POST requests to retrieve an access token, so we'll be doing a GET request instead. """ return self.request(self.access_token_url, method="GET", params=params)
python
def request_access_token(self, params): """ Foursquare does not accept POST requests to retrieve an access token, so we'll be doing a GET request instead. """ return self.request(self.access_token_url, method="GET", params=params)
[ "def", "request_access_token", "(", "self", ",", "params", ")", ":", "return", "self", ".", "request", "(", "self", ".", "access_token_url", ",", "method", "=", "\"GET\"", ",", "params", "=", "params", ")" ]
Foursquare does not accept POST requests to retrieve an access token, so we'll be doing a GET request instead.
[ "Foursquare", "does", "not", "accept", "POST", "requests", "to", "retrieve", "an", "access", "token", "so", "we", "ll", "be", "doing", "a", "GET", "request", "instead", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/contrib/foursquare/client.py#L32-L37
train
37,016
flashingpumpkin/django-socialregistration
socialregistration/views.py
Setup.get_initial_data
def get_initial_data(self, request, user, profile, client): """ Return initial data for the setup form. The function can be controlled with ``SOCIALREGISTRATION_INITIAL_DATA_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client """ if INITAL_DATA_FUNCTION: func = self.import_attribute(INITAL_DATA_FUNCTION) return func(request, user, profile, client) return {}
python
def get_initial_data(self, request, user, profile, client): """ Return initial data for the setup form. The function can be controlled with ``SOCIALREGISTRATION_INITIAL_DATA_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client """ if INITAL_DATA_FUNCTION: func = self.import_attribute(INITAL_DATA_FUNCTION) return func(request, user, profile, client) return {}
[ "def", "get_initial_data", "(", "self", ",", "request", ",", "user", ",", "profile", ",", "client", ")", ":", "if", "INITAL_DATA_FUNCTION", ":", "func", "=", "self", ".", "import_attribute", "(", "INITAL_DATA_FUNCTION", ")", "return", "func", "(", "request", ...
Return initial data for the setup form. The function can be controlled with ``SOCIALREGISTRATION_INITIAL_DATA_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client
[ "Return", "initial", "data", "for", "the", "setup", "form", ".", "The", "function", "can", "be", "controlled", "with", "SOCIALREGISTRATION_INITIAL_DATA_FUNCTION", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L55-L68
train
37,017
flashingpumpkin/django-socialregistration
socialregistration/views.py
Setup.get_context
def get_context(self, request, user, profile, client): """ Return additional context for the setup view. The function can be controlled with ``SOCIALREGISTRATION_SETUP_CONTEXT_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client """ if CONTEXT_FUNCTION: func = self.import_attribute(CONTEXT_FUNCTION) return func(request, user, profile, client) return {}
python
def get_context(self, request, user, profile, client): """ Return additional context for the setup view. The function can be controlled with ``SOCIALREGISTRATION_SETUP_CONTEXT_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client """ if CONTEXT_FUNCTION: func = self.import_attribute(CONTEXT_FUNCTION) return func(request, user, profile, client) return {}
[ "def", "get_context", "(", "self", ",", "request", ",", "user", ",", "profile", ",", "client", ")", ":", "if", "CONTEXT_FUNCTION", ":", "func", "=", "self", ".", "import_attribute", "(", "CONTEXT_FUNCTION", ")", "return", "func", "(", "request", ",", "user...
Return additional context for the setup view. The function can be controlled with ``SOCIALREGISTRATION_SETUP_CONTEXT_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client
[ "Return", "additional", "context", "for", "the", "setup", "view", ".", "The", "function", "can", "be", "controlled", "with", "SOCIALREGISTRATION_SETUP_CONTEXT_FUNCTION", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L70-L83
train
37,018
flashingpumpkin/django-socialregistration
socialregistration/views.py
Setup.generate_username_and_redirect
def generate_username_and_redirect(self, request, user, profile, client): """ Generate a username and then redirect the user to the correct place. This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME`` is set. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client """ func = self.get_username_function() user.username = func(user, profile, client) user.set_unusable_password() user.save() profile.user = user profile.save() user = profile.authenticate() self.send_connect_signal(request, user, profile, client) self.login(request, user) self.send_login_signal(request, user, profile, client) self.delete_session_data(request) return HttpResponseRedirect(self.get_next(request))
python
def generate_username_and_redirect(self, request, user, profile, client): """ Generate a username and then redirect the user to the correct place. This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME`` is set. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client """ func = self.get_username_function() user.username = func(user, profile, client) user.set_unusable_password() user.save() profile.user = user profile.save() user = profile.authenticate() self.send_connect_signal(request, user, profile, client) self.login(request, user) self.send_login_signal(request, user, profile, client) self.delete_session_data(request) return HttpResponseRedirect(self.get_next(request))
[ "def", "generate_username_and_redirect", "(", "self", ",", "request", ",", "user", ",", "profile", ",", "client", ")", ":", "func", "=", "self", ".", "get_username_function", "(", ")", "user", ".", "username", "=", "func", "(", "user", ",", "profile", ",",...
Generate a username and then redirect the user to the correct place. This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME`` is set. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client
[ "Generate", "a", "username", "and", "then", "redirect", "the", "user", "to", "the", "correct", "place", ".", "This", "method", "is", "called", "when", "SOCIALREGISTRATION_GENERATE_USERNAME", "is", "set", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L85-L115
train
37,019
flashingpumpkin/django-socialregistration
socialregistration/views.py
Setup.get
def get(self, request): """ When signing a new user up - either display a setup form, or generate the username automatically. """ if request.user.is_authenticated(): return HttpResponseRedirect(self.get_next(request)) try: user, profile, client = self.get_session_data(request) except KeyError: return self.error_to_response(request, dict( error=_("Social profile is missing from your session."))) if GENERATE_USERNAME: return self.generate_username_and_redirect(request, user, profile, client) form = self.get_form()(initial=self.get_initial_data(request, user, profile, client)) additional_context = self.get_context(request, user, profile, client) return self.render_to_response(dict({'form': form}, **additional_context))
python
def get(self, request): """ When signing a new user up - either display a setup form, or generate the username automatically. """ if request.user.is_authenticated(): return HttpResponseRedirect(self.get_next(request)) try: user, profile, client = self.get_session_data(request) except KeyError: return self.error_to_response(request, dict( error=_("Social profile is missing from your session."))) if GENERATE_USERNAME: return self.generate_username_and_redirect(request, user, profile, client) form = self.get_form()(initial=self.get_initial_data(request, user, profile, client)) additional_context = self.get_context(request, user, profile, client) return self.render_to_response(dict({'form': form}, **additional_context))
[ "def", "get", "(", "self", ",", "request", ")", ":", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "return", "HttpResponseRedirect", "(", "self", ".", "get_next", "(", "request", ")", ")", "try", ":", "user", ",", "profile", ","...
When signing a new user up - either display a setup form, or generate the username automatically.
[ "When", "signing", "a", "new", "user", "up", "-", "either", "display", "a", "setup", "form", "or", "generate", "the", "username", "automatically", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L117-L138
train
37,020
flashingpumpkin/django-socialregistration
socialregistration/views.py
Setup.post
def post(self, request): """ Save the user and profile, login and send the right signals. """ if request.user.is_authenticated(): return self.error_to_response(request, dict( error=_("You are already logged in."))) try: user, profile, client = self.get_session_data(request) except KeyError: return self.error_to_response(request, dict( error=_("A social profile is missing from your session."))) form = self.get_form()(request.POST, request.FILES, initial=self.get_initial_data(request, user, profile, client)) if not form.is_valid(): additional_context = self.get_context(request, user, profile, client) return self.render_to_response(dict({'form': form}, **additional_context)) user, profile = form.save(request, user, profile, client) user = profile.authenticate() self.send_connect_signal(request, user, profile, client) self.login(request, user) self.send_login_signal(request, user, profile, client) self.delete_session_data(request) return HttpResponseRedirect(self.get_next(request))
python
def post(self, request): """ Save the user and profile, login and send the right signals. """ if request.user.is_authenticated(): return self.error_to_response(request, dict( error=_("You are already logged in."))) try: user, profile, client = self.get_session_data(request) except KeyError: return self.error_to_response(request, dict( error=_("A social profile is missing from your session."))) form = self.get_form()(request.POST, request.FILES, initial=self.get_initial_data(request, user, profile, client)) if not form.is_valid(): additional_context = self.get_context(request, user, profile, client) return self.render_to_response(dict({'form': form}, **additional_context)) user, profile = form.save(request, user, profile, client) user = profile.authenticate() self.send_connect_signal(request, user, profile, client) self.login(request, user) self.send_login_signal(request, user, profile, client) self.delete_session_data(request) return HttpResponseRedirect(self.get_next(request))
[ "def", "post", "(", "self", ",", "request", ")", ":", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "return", "self", ".", "error_to_response", "(", "request", ",", "dict", "(", "error", "=", "_", "(", "\"You are already logged in.\...
Save the user and profile, login and send the right signals.
[ "Save", "the", "user", "and", "profile", "login", "and", "send", "the", "right", "signals", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L140-L174
train
37,021
flashingpumpkin/django-socialregistration
socialregistration/views.py
OAuthRedirect.post
def post(self, request): """ Create a client, store it in the user's session and redirect the user to the API provider to authorize our app and permissions. """ request.session['next'] = self.get_next(request) client = self.get_client()() request.session[self.get_client().get_session_key()] = client url = client.get_redirect_url(request=request) logger.debug("Redirecting to %s", url) try: return HttpResponseRedirect(url) except OAuthError, error: return self.error_to_response(request, {'error': error}) except socket.timeout: return self.error_to_response(request, {'error': _('Could not connect to service (timed out)')})
python
def post(self, request): """ Create a client, store it in the user's session and redirect the user to the API provider to authorize our app and permissions. """ request.session['next'] = self.get_next(request) client = self.get_client()() request.session[self.get_client().get_session_key()] = client url = client.get_redirect_url(request=request) logger.debug("Redirecting to %s", url) try: return HttpResponseRedirect(url) except OAuthError, error: return self.error_to_response(request, {'error': error}) except socket.timeout: return self.error_to_response(request, {'error': _('Could not connect to service (timed out)')})
[ "def", "post", "(", "self", ",", "request", ")", ":", "request", ".", "session", "[", "'next'", "]", "=", "self", ".", "get_next", "(", "request", ")", "client", "=", "self", ".", "get_client", "(", ")", "(", ")", "request", ".", "session", "[", "s...
Create a client, store it in the user's session and redirect the user to the API provider to authorize our app and permissions.
[ "Create", "a", "client", "store", "it", "in", "the", "user", "s", "session", "and", "redirect", "the", "user", "to", "the", "API", "provider", "to", "authorize", "our", "app", "and", "permissions", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L202-L218
train
37,022
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth.client
def client(self, verifier=None): """ Return the correct client depending on which stage of the OAuth process we're in. """ # We're just starting out and don't have neither request nor access # token. Return the standard client if not self._request_token and not self._access_token: client = oauth.Client(self.consumer, timeout=TIMEOUT) # We're one step in, we've got the request token and can add that to # the client. if self._request_token and not self._access_token: if verifier is not None: self._request_token.set_verifier(verifier) client = oauth.Client(self.consumer, self._request_token, timeout=TIMEOUT) # Two steps in, we've got an access token and can now properly sign # our client requests with it. if self._access_token: client = oauth.Client(self.consumer, self._access_token, timeout=TIMEOUT) return client
python
def client(self, verifier=None): """ Return the correct client depending on which stage of the OAuth process we're in. """ # We're just starting out and don't have neither request nor access # token. Return the standard client if not self._request_token and not self._access_token: client = oauth.Client(self.consumer, timeout=TIMEOUT) # We're one step in, we've got the request token and can add that to # the client. if self._request_token and not self._access_token: if verifier is not None: self._request_token.set_verifier(verifier) client = oauth.Client(self.consumer, self._request_token, timeout=TIMEOUT) # Two steps in, we've got an access token and can now properly sign # our client requests with it. if self._access_token: client = oauth.Client(self.consumer, self._access_token, timeout=TIMEOUT) return client
[ "def", "client", "(", "self", ",", "verifier", "=", "None", ")", ":", "# We're just starting out and don't have neither request nor access", "# token. Return the standard client", "if", "not", "self", ".", "_request_token", "and", "not", "self", ".", "_access_token", ":",...
Return the correct client depending on which stage of the OAuth process we're in.
[ "Return", "the", "correct", "client", "depending", "on", "which", "stage", "of", "the", "OAuth", "process", "we", "re", "in", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L64-L86
train
37,023
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth._get_request_token
def _get_request_token(self): """ Fetch a request token from `self.request_token_url`. """ params = { 'oauth_callback': self.get_callback_url() } response, content = self.client().request(self.request_token_url, "POST", body=urllib.urlencode(params)) content = smart_unicode(content) if not response['status'] == '200': raise OAuthError(_( u"Invalid status code %s while obtaining request token from %s: %s") % ( response['status'], self.request_token_url, content)) token = dict(urlparse.parse_qsl(content)) return oauth.Token(token['oauth_token'], token['oauth_token_secret'])
python
def _get_request_token(self): """ Fetch a request token from `self.request_token_url`. """ params = { 'oauth_callback': self.get_callback_url() } response, content = self.client().request(self.request_token_url, "POST", body=urllib.urlencode(params)) content = smart_unicode(content) if not response['status'] == '200': raise OAuthError(_( u"Invalid status code %s while obtaining request token from %s: %s") % ( response['status'], self.request_token_url, content)) token = dict(urlparse.parse_qsl(content)) return oauth.Token(token['oauth_token'], token['oauth_token_secret'])
[ "def", "_get_request_token", "(", "self", ")", ":", "params", "=", "{", "'oauth_callback'", ":", "self", ".", "get_callback_url", "(", ")", "}", "response", ",", "content", "=", "self", ".", "client", "(", ")", ".", "request", "(", "self", ".", "request_...
Fetch a request token from `self.request_token_url`.
[ "Fetch", "a", "request", "token", "from", "self", ".", "request_token_url", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L88-L110
train
37,024
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth._get_access_token
def _get_access_token(self, verifier=None): """ Fetch an access token from `self.access_token_url`. """ response, content = self.client(verifier).request( self.access_token_url, "POST") content = smart_unicode(content) if not response['status'] == '200': raise OAuthError(_( u"Invalid status code %s while obtaining access token from %s: %s") % (response['status'], self.access_token_url, content)) token = dict(urlparse.parse_qsl(content)) return (oauth.Token(token['oauth_token'], token['oauth_token_secret']), token)
python
def _get_access_token(self, verifier=None): """ Fetch an access token from `self.access_token_url`. """ response, content = self.client(verifier).request( self.access_token_url, "POST") content = smart_unicode(content) if not response['status'] == '200': raise OAuthError(_( u"Invalid status code %s while obtaining access token from %s: %s") % (response['status'], self.access_token_url, content)) token = dict(urlparse.parse_qsl(content)) return (oauth.Token(token['oauth_token'], token['oauth_token_secret']), token)
[ "def", "_get_access_token", "(", "self", ",", "verifier", "=", "None", ")", ":", "response", ",", "content", "=", "self", ".", "client", "(", "verifier", ")", ".", "request", "(", "self", ".", "access_token_url", ",", "\"POST\"", ")", "content", "=", "sm...
Fetch an access token from `self.access_token_url`.
[ "Fetch", "an", "access", "token", "from", "self", ".", "access_token_url", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L112-L131
train
37,025
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth.get_request_token
def get_request_token(self): """ Return the request token for this API. If we've not fetched it yet, go out, request and memoize it. """ if self._request_token is None: self._request_token = self._get_request_token() return self._request_token
python
def get_request_token(self): """ Return the request token for this API. If we've not fetched it yet, go out, request and memoize it. """ if self._request_token is None: self._request_token = self._get_request_token() return self._request_token
[ "def", "get_request_token", "(", "self", ")", ":", "if", "self", ".", "_request_token", "is", "None", ":", "self", ".", "_request_token", "=", "self", ".", "_get_request_token", "(", ")", "return", "self", ".", "_request_token" ]
Return the request token for this API. If we've not fetched it yet, go out, request and memoize it.
[ "Return", "the", "request", "token", "for", "this", "API", ".", "If", "we", "ve", "not", "fetched", "it", "yet", "go", "out", "request", "and", "memoize", "it", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L133-L141
train
37,026
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth.get_access_token
def get_access_token(self, verifier=None): """ Return the access token for this API. If we've not fetched it yet, go out, request and memoize it. """ if self._access_token is None: self._access_token, self._access_token_dict = self._get_access_token(verifier) return self._access_token
python
def get_access_token(self, verifier=None): """ Return the access token for this API. If we've not fetched it yet, go out, request and memoize it. """ if self._access_token is None: self._access_token, self._access_token_dict = self._get_access_token(verifier) return self._access_token
[ "def", "get_access_token", "(", "self", ",", "verifier", "=", "None", ")", ":", "if", "self", ".", "_access_token", "is", "None", ":", "self", ".", "_access_token", ",", "self", ".", "_access_token_dict", "=", "self", ".", "_get_access_token", "(", "verifier...
Return the access token for this API. If we've not fetched it yet, go out, request and memoize it.
[ "Return", "the", "access", "token", "for", "this", "API", ".", "If", "we", "ve", "not", "fetched", "it", "yet", "go", "out", "request", "and", "memoize", "it", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L143-L151
train
37,027
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth.complete
def complete(self, GET): """ When redirect back to our application, try to complete the flow by requesting an access token. If the access token request fails, it'll throw an `OAuthError`. Tries to complete the flow by validating against the `GET` paramters received. """ token = self.get_access_token(verifier=GET.get('oauth_verifier', None)) return token
python
def complete(self, GET): """ When redirect back to our application, try to complete the flow by requesting an access token. If the access token request fails, it'll throw an `OAuthError`. Tries to complete the flow by validating against the `GET` paramters received. """ token = self.get_access_token(verifier=GET.get('oauth_verifier', None)) return token
[ "def", "complete", "(", "self", ",", "GET", ")", ":", "token", "=", "self", ".", "get_access_token", "(", "verifier", "=", "GET", ".", "get", "(", "'oauth_verifier'", ",", "None", ")", ")", "return", "token" ]
When redirect back to our application, try to complete the flow by requesting an access token. If the access token request fails, it'll throw an `OAuthError`. Tries to complete the flow by validating against the `GET` paramters received.
[ "When", "redirect", "back", "to", "our", "application", "try", "to", "complete", "the", "flow", "by", "requesting", "an", "access", "token", ".", "If", "the", "access", "token", "request", "fails", "it", "ll", "throw", "an", "OAuthError", ".", "Tries", "to...
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L164-L174
train
37,028
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth.request
def request(self, url, method="GET", params=None, headers=None): """ Make signed requests against `url`. """ params = params or {} headers = headers or {} logger.debug("URL: %s", url) logger.debug("Method: %s", method) logger.debug("Headers: %s", headers) logger.debug("Params: %s", params) response, content = self.client().request(url, method, headers=headers, body=urllib.urlencode(params)) content = smart_unicode(content) logger.debug("Status: %s", response['status']) logger.debug("Content: %s", content) if response['status'] != '200': raise OAuthError(_( u"Invalid status code %s while requesting %s: %s") % ( response['status'], url, content)) return content
python
def request(self, url, method="GET", params=None, headers=None): """ Make signed requests against `url`. """ params = params or {} headers = headers or {} logger.debug("URL: %s", url) logger.debug("Method: %s", method) logger.debug("Headers: %s", headers) logger.debug("Params: %s", params) response, content = self.client().request(url, method, headers=headers, body=urllib.urlencode(params)) content = smart_unicode(content) logger.debug("Status: %s", response['status']) logger.debug("Content: %s", content) if response['status'] != '200': raise OAuthError(_( u"Invalid status code %s while requesting %s: %s") % ( response['status'], url, content)) return content
[ "def", "request", "(", "self", ",", "url", ",", "method", "=", "\"GET\"", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "logger", ".", "debug",...
Make signed requests against `url`.
[ "Make", "signed", "requests", "against", "url", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L176-L201
train
37,029
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth2.get_redirect_url
def get_redirect_url(self, state='', **kwargs): """ Assemble the URL to where we'll be redirecting the user to to request permissions. """ params = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': self.get_callback_url(**kwargs), 'scope': self.scope or '', 'state': state, } return '%s?%s' % (self.auth_url, urllib.urlencode(params))
python
def get_redirect_url(self, state='', **kwargs): """ Assemble the URL to where we'll be redirecting the user to to request permissions. """ params = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': self.get_callback_url(**kwargs), 'scope': self.scope or '', 'state': state, } return '%s?%s' % (self.auth_url, urllib.urlencode(params))
[ "def", "get_redirect_url", "(", "self", ",", "state", "=", "''", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'response_type'", ":", "'code'", ",", "'client_id'", ":", "self", ".", "client_id", ",", "'redirect_uri'", ":", "self", ".", "get_cal...
Assemble the URL to where we'll be redirecting the user to to request permissions.
[ "Assemble", "the", "URL", "to", "where", "we", "ll", "be", "redirecting", "the", "user", "to", "to", "request", "permissions", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L241-L254
train
37,030
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth2.request_access_token
def request_access_token(self, params): """ Request the access token from `self.access_token_url`. The default behaviour is to use a `POST` request, but some services use `GET` requests. Individual clients can override this method to use the correct HTTP method. """ return self.request(self.access_token_url, method="POST", params=params, is_signed=False)
python
def request_access_token(self, params): """ Request the access token from `self.access_token_url`. The default behaviour is to use a `POST` request, but some services use `GET` requests. Individual clients can override this method to use the correct HTTP method. """ return self.request(self.access_token_url, method="POST", params=params, is_signed=False)
[ "def", "request_access_token", "(", "self", ",", "params", ")", ":", "return", "self", ".", "request", "(", "self", ".", "access_token_url", ",", "method", "=", "\"POST\"", ",", "params", "=", "params", ",", "is_signed", "=", "False", ")" ]
Request the access token from `self.access_token_url`. The default behaviour is to use a `POST` request, but some services use `GET` requests. Individual clients can override this method to use the correct HTTP method.
[ "Request", "the", "access", "token", "from", "self", ".", "access_token_url", ".", "The", "default", "behaviour", "is", "to", "use", "a", "POST", "request", "but", "some", "services", "use", "GET", "requests", ".", "Individual", "clients", "can", "override", ...
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L263-L271
train
37,031
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth2._get_access_token
def _get_access_token(self, code, **params): """ Fetch an access token with the provided `code`. """ params.update({ 'code': code, 'client_id': self.client_id, 'client_secret': self.secret, 'redirect_uri': self.get_callback_url(), }) logger.debug("Params: %s", params) resp, content = self.request_access_token(params=params) content = smart_unicode(content) logger.debug("Status: %s", resp['status']) logger.debug("Content: %s", content) content = self.parse_access_token(content) if 'error' in content: raise OAuthError(_( u"Received error while obtaining access token from %s: %s") % ( self.access_token_url, content['error'])) return content
python
def _get_access_token(self, code, **params): """ Fetch an access token with the provided `code`. """ params.update({ 'code': code, 'client_id': self.client_id, 'client_secret': self.secret, 'redirect_uri': self.get_callback_url(), }) logger.debug("Params: %s", params) resp, content = self.request_access_token(params=params) content = smart_unicode(content) logger.debug("Status: %s", resp['status']) logger.debug("Content: %s", content) content = self.parse_access_token(content) if 'error' in content: raise OAuthError(_( u"Received error while obtaining access token from %s: %s") % ( self.access_token_url, content['error'])) return content
[ "def", "_get_access_token", "(", "self", ",", "code", ",", "*", "*", "params", ")", ":", "params", ".", "update", "(", "{", "'code'", ":", "code", ",", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "secret", ",...
Fetch an access token with the provided `code`.
[ "Fetch", "an", "access", "token", "with", "the", "provided", "code", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L273-L300
train
37,032
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth2.get_access_token
def get_access_token(self, code=None, **params): """ Return the memoized access token or go out and fetch one. """ if self._access_token is None: if code is None: raise ValueError(_('Invalid code.')) self.access_token_dict = self._get_access_token(code, **params) try: self._access_token = self.access_token_dict['access_token'] except KeyError, e: raise OAuthError("Credentials could not be validated, the provider returned no access token.") return self._access_token
python
def get_access_token(self, code=None, **params): """ Return the memoized access token or go out and fetch one. """ if self._access_token is None: if code is None: raise ValueError(_('Invalid code.')) self.access_token_dict = self._get_access_token(code, **params) try: self._access_token = self.access_token_dict['access_token'] except KeyError, e: raise OAuthError("Credentials could not be validated, the provider returned no access token.") return self._access_token
[ "def", "get_access_token", "(", "self", ",", "code", "=", "None", ",", "*", "*", "params", ")", ":", "if", "self", ".", "_access_token", "is", "None", ":", "if", "code", "is", "None", ":", "raise", "ValueError", "(", "_", "(", "'Invalid code.'", ")", ...
Return the memoized access token or go out and fetch one.
[ "Return", "the", "memoized", "access", "token", "or", "go", "out", "and", "fetch", "one", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L302-L316
train
37,033
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth2.complete
def complete(self, GET): """ Complete the OAuth2 flow by fetching an access token with the provided code in the GET parameters. """ if 'error' in GET: raise OAuthError( _("Received error while obtaining access token from %s: %s") % ( self.access_token_url, GET['error'])) return self.get_access_token(code=GET.get('code'))
python
def complete(self, GET): """ Complete the OAuth2 flow by fetching an access token with the provided code in the GET parameters. """ if 'error' in GET: raise OAuthError( _("Received error while obtaining access token from %s: %s") % ( self.access_token_url, GET['error'])) return self.get_access_token(code=GET.get('code'))
[ "def", "complete", "(", "self", ",", "GET", ")", ":", "if", "'error'", "in", "GET", ":", "raise", "OAuthError", "(", "_", "(", "\"Received error while obtaining access token from %s: %s\"", ")", "%", "(", "self", ".", "access_token_url", ",", "GET", "[", "'err...
Complete the OAuth2 flow by fetching an access token with the provided code in the GET parameters.
[ "Complete", "the", "OAuth2", "flow", "by", "fetching", "an", "access", "token", "with", "the", "provided", "code", "in", "the", "GET", "parameters", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L318-L327
train
37,034
flashingpumpkin/django-socialregistration
socialregistration/clients/oauth.py
OAuth2.request
def request(self, url, method="GET", params=None, headers=None, is_signed=True): """ Make a request against ``url``. By default, the request is signed with an access token, but can be turned off by passing ``is_signed=False``. """ params = params or {} headers = headers or {} if is_signed: params.update(self.get_signing_params()) if method.upper() == "GET": url = '%s?%s' % (url, urllib.urlencode(params)) return self.client().request(url, method=method, headers=headers) return self.client().request(url, method, body=urllib.urlencode(params), headers=headers)
python
def request(self, url, method="GET", params=None, headers=None, is_signed=True): """ Make a request against ``url``. By default, the request is signed with an access token, but can be turned off by passing ``is_signed=False``. """ params = params or {} headers = headers or {} if is_signed: params.update(self.get_signing_params()) if method.upper() == "GET": url = '%s?%s' % (url, urllib.urlencode(params)) return self.client().request(url, method=method, headers=headers) return self.client().request(url, method, body=urllib.urlencode(params), headers=headers)
[ "def", "request", "(", "self", ",", "url", ",", "method", "=", "\"GET\"", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "is_signed", "=", "True", ")", ":", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{...
Make a request against ``url``. By default, the request is signed with an access token, but can be turned off by passing ``is_signed=False``.
[ "Make", "a", "request", "against", "url", ".", "By", "default", "the", "request", "is", "signed", "with", "an", "access", "token", "but", "can", "be", "turned", "off", "by", "passing", "is_signed", "=", "False", "." ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L337-L351
train
37,035
flashingpumpkin/django-socialregistration
socialregistration/contrib/google/client.py
Google.request_access_token
def request_access_token(self, params): """ Google requires correct content-type for POST requests """ return self.client().request(self.access_token_url, method="POST", body=urllib.urlencode(params), headers={'Content-Type':'application/x-www-form-urlencoded'})
python
def request_access_token(self, params): """ Google requires correct content-type for POST requests """ return self.client().request(self.access_token_url, method="POST", body=urllib.urlencode(params), headers={'Content-Type':'application/x-www-form-urlencoded'})
[ "def", "request_access_token", "(", "self", ",", "params", ")", ":", "return", "self", ".", "client", "(", ")", ".", "request", "(", "self", ".", "access_token_url", ",", "method", "=", "\"POST\"", ",", "body", "=", "urllib", ".", "urlencode", "(", "para...
Google requires correct content-type for POST requests
[ "Google", "requires", "correct", "content", "-", "type", "for", "POST", "requests" ]
9da9fb83c9bf79997ff81fe1378ab5ca3074b32b
https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/contrib/google/client.py#L33-L37
train
37,036
adafruit/Adafruit_Python_MAX31855
Adafruit_MAX31855/MAX31855.py
MAX31855.readInternalC
def readInternalC(self): """Return internal temperature value in degrees celsius.""" v = self._read32() # Ignore bottom 4 bits of thermocouple data. v >>= 4 # Grab bottom 11 bits as internal temperature data. internal = v & 0x7FF if v & 0x800: # Negative value, take 2's compliment. Compute this with subtraction # because python is a little odd about handling signed/unsigned. internal -= 4096 # Scale by 0.0625 degrees C per bit and return value. return internal * 0.0625
python
def readInternalC(self): """Return internal temperature value in degrees celsius.""" v = self._read32() # Ignore bottom 4 bits of thermocouple data. v >>= 4 # Grab bottom 11 bits as internal temperature data. internal = v & 0x7FF if v & 0x800: # Negative value, take 2's compliment. Compute this with subtraction # because python is a little odd about handling signed/unsigned. internal -= 4096 # Scale by 0.0625 degrees C per bit and return value. return internal * 0.0625
[ "def", "readInternalC", "(", "self", ")", ":", "v", "=", "self", ".", "_read32", "(", ")", "# Ignore bottom 4 bits of thermocouple data.", "v", ">>=", "4", "# Grab bottom 11 bits as internal temperature data.", "internal", "=", "v", "&", "0x7FF", "if", "v", "&", "...
Return internal temperature value in degrees celsius.
[ "Return", "internal", "temperature", "value", "in", "degrees", "celsius", "." ]
a74832ebcea36487559ec96497398f99fd9355a5
https://github.com/adafruit/Adafruit_Python_MAX31855/blob/a74832ebcea36487559ec96497398f99fd9355a5/Adafruit_MAX31855/MAX31855.py#L56-L68
train
37,037
adafruit/Adafruit_Python_MAX31855
Adafruit_MAX31855/MAX31855.py
MAX31855.readTempC
def readTempC(self): """Return the thermocouple temperature value in degrees celsius.""" v = self._read32() # Check for error reading value. if v & 0x7: return float('NaN') # Check if signed bit is set. if v & 0x80000000: # Negative value, take 2's compliment. Compute this with subtraction # because python is a little odd about handling signed/unsigned. v >>= 18 v -= 16384 else: # Positive value, just shift the bits to get the value. v >>= 18 # Scale by 0.25 degrees C per bit and return value. return v * 0.25
python
def readTempC(self): """Return the thermocouple temperature value in degrees celsius.""" v = self._read32() # Check for error reading value. if v & 0x7: return float('NaN') # Check if signed bit is set. if v & 0x80000000: # Negative value, take 2's compliment. Compute this with subtraction # because python is a little odd about handling signed/unsigned. v >>= 18 v -= 16384 else: # Positive value, just shift the bits to get the value. v >>= 18 # Scale by 0.25 degrees C per bit and return value. return v * 0.25
[ "def", "readTempC", "(", "self", ")", ":", "v", "=", "self", ".", "_read32", "(", ")", "# Check for error reading value.", "if", "v", "&", "0x7", ":", "return", "float", "(", "'NaN'", ")", "# Check if signed bit is set.", "if", "v", "&", "0x80000000", ":", ...
Return the thermocouple temperature value in degrees celsius.
[ "Return", "the", "thermocouple", "temperature", "value", "in", "degrees", "celsius", "." ]
a74832ebcea36487559ec96497398f99fd9355a5
https://github.com/adafruit/Adafruit_Python_MAX31855/blob/a74832ebcea36487559ec96497398f99fd9355a5/Adafruit_MAX31855/MAX31855.py#L70-L86
train
37,038
geographika/mappyfile
mappyfile/pprint.py
Quoter.escape_quotes
def escape_quotes(self, val): """ Escape any quotes in a value """ if self.is_string(val) and self._in_quotes(val, self.quote): # make sure any previously escaped quotes are not re-escaped middle = self.remove_quotes(val).replace("\\" + self.quote, self.quote) middle = middle.replace(self.quote, "\\" + self.quote) val = self.add_quotes(middle) return val
python
def escape_quotes(self, val): """ Escape any quotes in a value """ if self.is_string(val) and self._in_quotes(val, self.quote): # make sure any previously escaped quotes are not re-escaped middle = self.remove_quotes(val).replace("\\" + self.quote, self.quote) middle = middle.replace(self.quote, "\\" + self.quote) val = self.add_quotes(middle) return val
[ "def", "escape_quotes", "(", "self", ",", "val", ")", ":", "if", "self", ".", "is_string", "(", "val", ")", "and", "self", ".", "_in_quotes", "(", "val", ",", "self", ".", "quote", ")", ":", "# make sure any previously escaped quotes are not re-escaped", "midd...
Escape any quotes in a value
[ "Escape", "any", "quotes", "in", "a", "value" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L46-L56
train
37,039
geographika/mappyfile
mappyfile/pprint.py
Quoter.standardise_quotes
def standardise_quotes(self, val): """ Change the quotes used to wrap a value to the pprint default E.g. "val" to 'val' or 'val' to "val" """ if self._in_quotes(val, self.altquote): middle = self.remove_quotes(val) val = self.add_quotes(middle) return self.escape_quotes(val)
python
def standardise_quotes(self, val): """ Change the quotes used to wrap a value to the pprint default E.g. "val" to 'val' or 'val' to "val" """ if self._in_quotes(val, self.altquote): middle = self.remove_quotes(val) val = self.add_quotes(middle) return self.escape_quotes(val)
[ "def", "standardise_quotes", "(", "self", ",", "val", ")", ":", "if", "self", ".", "_in_quotes", "(", "val", ",", "self", ".", "altquote", ")", ":", "middle", "=", "self", ".", "remove_quotes", "(", "val", ")", "val", "=", "self", ".", "add_quotes", ...
Change the quotes used to wrap a value to the pprint default E.g. "val" to 'val' or 'val' to "val"
[ "Change", "the", "quotes", "used", "to", "wrap", "a", "value", "to", "the", "pprint", "default", "E", ".", "g", ".", "val", "to", "val", "or", "val", "to", "val" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L91-L100
train
37,040
geographika/mappyfile
mappyfile/pprint.py
PrettyPrinter.process_dict
def process_dict(self, d, level, comments): """ Process keys and values within a block """ lines = [] for k, v in d.items(): if not self.__is_metadata(k): qk = self.quoter.add_quotes(k) qv = self.quoter.add_quotes(v) line = self.__format_line(self.whitespace(level, 2), qk, qv) line += self.process_attribute_comment(comments, k) lines.append(line) return lines
python
def process_dict(self, d, level, comments): """ Process keys and values within a block """ lines = [] for k, v in d.items(): if not self.__is_metadata(k): qk = self.quoter.add_quotes(k) qv = self.quoter.add_quotes(v) line = self.__format_line(self.whitespace(level, 2), qk, qv) line += self.process_attribute_comment(comments, k) lines.append(line) return lines
[ "def", "process_dict", "(", "self", ",", "d", ",", "level", ",", "comments", ")", ":", "lines", "=", "[", "]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "not", "self", ".", "__is_metadata", "(", "k", ")", ":", "qk", ...
Process keys and values within a block
[ "Process", "keys", "and", "values", "within", "a", "block" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L174-L188
train
37,041
geographika/mappyfile
mappyfile/pprint.py
PrettyPrinter.process_config_dict
def process_config_dict(self, key, d, level): """ Process the CONFIG block """ lines = [] for k, v in d.items(): k = "CONFIG {}".format(self.quoter.add_quotes(k.upper())) v = self.quoter.add_quotes(v) lines.append(self.__format_line(self.whitespace(level, 1), k, v)) return lines
python
def process_config_dict(self, key, d, level): """ Process the CONFIG block """ lines = [] for k, v in d.items(): k = "CONFIG {}".format(self.quoter.add_quotes(k.upper())) v = self.quoter.add_quotes(v) lines.append(self.__format_line(self.whitespace(level, 1), k, v)) return lines
[ "def", "process_config_dict", "(", "self", ",", "key", ",", "d", ",", "level", ")", ":", "lines", "=", "[", "]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "k", "=", "\"CONFIG {}\"", ".", "format", "(", "self", ".", "quoter", ...
Process the CONFIG block
[ "Process", "the", "CONFIG", "block" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L190-L199
train
37,042
geographika/mappyfile
mappyfile/pprint.py
PrettyPrinter.is_hidden_container
def is_hidden_container(self, key, val): """ The key is not one of the Mapfile keywords, and its values are a list """ if key in ("layers", "classes", "styles", "symbols", "labels", "outputformats", "features", "scaletokens", "composites") and isinstance(val, list): return True else: return False
python
def is_hidden_container(self, key, val): """ The key is not one of the Mapfile keywords, and its values are a list """ if key in ("layers", "classes", "styles", "symbols", "labels", "outputformats", "features", "scaletokens", "composites") and isinstance(val, list): return True else: return False
[ "def", "is_hidden_container", "(", "self", ",", "key", ",", "val", ")", ":", "if", "key", "in", "(", "\"layers\"", ",", "\"classes\"", ",", "\"styles\"", ",", "\"symbols\"", ",", "\"labels\"", ",", "\"outputformats\"", ",", "\"features\"", ",", "\"scaletokens\...
The key is not one of the Mapfile keywords, and its values are a list
[ "The", "key", "is", "not", "one", "of", "the", "Mapfile", "keywords", "and", "its", "values", "are", "a", "list" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L273-L284
train
37,043
geographika/mappyfile
mappyfile/pprint.py
PrettyPrinter.pprint
def pprint(self, composites): """ Print out a nicely indented Mapfile """ # if only a single composite is used then cast to list # and allow for multiple root composites if composites and not isinstance(composites, list): composites = [composites] lines = [] for composite in composites: type_ = composite["__type__"] if type_ in ("metadata", "validation"): # types are being parsed directly, and not as an attr of a parent lines += self.process_key_dict(type_, composite, level=0) else: lines += self._format(composite) result = str(self.newlinechar.join(lines)) return result
python
def pprint(self, composites): """ Print out a nicely indented Mapfile """ # if only a single composite is used then cast to list # and allow for multiple root composites if composites and not isinstance(composites, list): composites = [composites] lines = [] for composite in composites: type_ = composite["__type__"] if type_ in ("metadata", "validation"): # types are being parsed directly, and not as an attr of a parent lines += self.process_key_dict(type_, composite, level=0) else: lines += self._format(composite) result = str(self.newlinechar.join(lines)) return result
[ "def", "pprint", "(", "self", ",", "composites", ")", ":", "# if only a single composite is used then cast to list", "# and allow for multiple root composites", "if", "composites", "and", "not", "isinstance", "(", "composites", ",", "list", ")", ":", "composites", "=", ...
Print out a nicely indented Mapfile
[ "Print", "out", "a", "nicely", "indented", "Mapfile" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L286-L308
train
37,044
geographika/mappyfile
mappyfile/pprint.py
PrettyPrinter.process_composite_comment
def process_composite_comment(self, level, comments, key): """ Process comments for composites such as MAP, LAYER etc. """ if key not in comments: comment = "" else: value = comments[key] spacer = self.whitespace(level, 0) if isinstance(value, list): comments = [self.format_comment(spacer, v) for v in value] comment = self.newlinechar.join(comments) else: comment = self.format_comment(spacer, value) return comment
python
def process_composite_comment(self, level, comments, key): """ Process comments for composites such as MAP, LAYER etc. """ if key not in comments: comment = "" else: value = comments[key] spacer = self.whitespace(level, 0) if isinstance(value, list): comments = [self.format_comment(spacer, v) for v in value] comment = self.newlinechar.join(comments) else: comment = self.format_comment(spacer, value) return comment
[ "def", "process_composite_comment", "(", "self", ",", "level", ",", "comments", ",", "key", ")", ":", "if", "key", "not", "in", "comments", ":", "comment", "=", "\"\"", "else", ":", "value", "=", "comments", "[", "key", "]", "spacer", "=", "self", ".",...
Process comments for composites such as MAP, LAYER etc.
[ "Process", "comments", "for", "composites", "such", "as", "MAP", "LAYER", "etc", "." ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L417-L433
train
37,045
geographika/mappyfile
mappyfile/transformer.py
MapfileTransformer.start
def start(self, children): """ Parses a MapServer Mapfile Parsing of partial Mapfiles or lists of composites is also possible """ composites = [] for composite_dict in children: if False and self.include_position: key_token = composite_dict[1] key_name = key_token.value.lower() composites_position = self.get_position_dict(composite_dict) composites_position[key_name] = self.create_position_dict(key_token, None) composites.append(composite_dict) # only return a list when there are multiple root composites (e.g. # several CLASSes) if len(composites) == 1: return composites[0] else: return composites
python
def start(self, children): """ Parses a MapServer Mapfile Parsing of partial Mapfiles or lists of composites is also possible """ composites = [] for composite_dict in children: if False and self.include_position: key_token = composite_dict[1] key_name = key_token.value.lower() composites_position = self.get_position_dict(composite_dict) composites_position[key_name] = self.create_position_dict(key_token, None) composites.append(composite_dict) # only return a list when there are multiple root composites (e.g. # several CLASSes) if len(composites) == 1: return composites[0] else: return composites
[ "def", "start", "(", "self", ",", "children", ")", ":", "composites", "=", "[", "]", "for", "composite_dict", "in", "children", ":", "if", "False", "and", "self", ".", "include_position", ":", "key_token", "=", "composite_dict", "[", "1", "]", "key_name", ...
Parses a MapServer Mapfile Parsing of partial Mapfiles or lists of composites is also possible
[ "Parses", "a", "MapServer", "Mapfile", "Parsing", "of", "partial", "Mapfiles", "or", "lists", "of", "composites", "is", "also", "possible" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/transformer.py#L38-L60
train
37,046
geographika/mappyfile
mappyfile/transformer.py
MapfileTransformer.check_composite_tokens
def check_composite_tokens(self, name, tokens): """ Return the key and contents of a KEY..END block for PATTERN, POINTS, and PROJECTION """ assert len(tokens) >= 2 key = tokens[0] assert key.value.lower() == name assert tokens[-1].value.lower() == "end" if len(tokens) == 2: body = [] # empty TYPE..END block else: body = tokens[1:-1] body_tokens = [] for t in body: if isinstance(t, dict): body_tokens.append(t["__tokens__"]) else: body_tokens.append(t) return key, body_tokens
python
def check_composite_tokens(self, name, tokens): """ Return the key and contents of a KEY..END block for PATTERN, POINTS, and PROJECTION """ assert len(tokens) >= 2 key = tokens[0] assert key.value.lower() == name assert tokens[-1].value.lower() == "end" if len(tokens) == 2: body = [] # empty TYPE..END block else: body = tokens[1:-1] body_tokens = [] for t in body: if isinstance(t, dict): body_tokens.append(t["__tokens__"]) else: body_tokens.append(t) return key, body_tokens
[ "def", "check_composite_tokens", "(", "self", ",", "name", ",", "tokens", ")", ":", "assert", "len", "(", "tokens", ")", ">=", "2", "key", "=", "tokens", "[", "0", "]", "assert", "key", ".", "value", ".", "lower", "(", ")", "==", "name", "assert", ...
Return the key and contents of a KEY..END block for PATTERN, POINTS, and PROJECTION
[ "Return", "the", "key", "and", "contents", "of", "a", "KEY", "..", "END", "block", "for", "PATTERN", "POINTS", "and", "PROJECTION" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/transformer.py#L293-L316
train
37,047
geographika/mappyfile
mappyfile/transformer.py
MapfileTransformer.process_value_pairs
def process_value_pairs(self, tokens, type_): """ Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed """ key, body = self.check_composite_tokens(type_, tokens) key_name = self.key_name(key) d = CaseInsensitiveOrderedDict(CaseInsensitiveOrderedDict) for t in body: k = self.clean_string(t[0].value).lower() v = self.clean_string(t[1].value) if k in d.keys(): log.warning("A duplicate key ({}) was found in {}. Only the last value ({}) will be used. ".format( k, type_, v)) d[k] = v if self.include_position: pd = self.create_position_dict(key, body) d["__position__"] = pd d["__type__"] = key_name # return the token as well as the processed dict so the # composites function works the same way return d
python
def process_value_pairs(self, tokens, type_): """ Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed """ key, body = self.check_composite_tokens(type_, tokens) key_name = self.key_name(key) d = CaseInsensitiveOrderedDict(CaseInsensitiveOrderedDict) for t in body: k = self.clean_string(t[0].value).lower() v = self.clean_string(t[1].value) if k in d.keys(): log.warning("A duplicate key ({}) was found in {}. Only the last value ({}) will be used. ".format( k, type_, v)) d[k] = v if self.include_position: pd = self.create_position_dict(key, body) d["__position__"] = pd d["__type__"] = key_name # return the token as well as the processed dict so the # composites function works the same way return d
[ "def", "process_value_pairs", "(", "self", ",", "tokens", ",", "type_", ")", ":", "key", ",", "body", "=", "self", ".", "check_composite_tokens", "(", "type_", ",", "tokens", ")", "key_name", "=", "self", ".", "key_name", "(", "key", ")", "d", "=", "Ca...
Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed
[ "Metadata", "Values", "and", "Validation", "blocks", "can", "either", "have", "string", "pairs", "or", "attributes", "Attributes", "will", "already", "be", "processed" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/transformer.py#L318-L347
train
37,048
geographika/mappyfile
mappyfile/transformer.py
CommentsTransformer.add_metadata_comments
def add_metadata_comments(self, d, metadata): """ Any duplicate keys will be replaced with the last duplicate along with comments """ if len(metadata) > 2: string_pairs = metadata[1:-1] # get all metadata pairs for sp in string_pairs: # get the raw metadata key if isinstance(sp.children[0], Token): token = sp.children[0] assert token.type == "UNQUOTED_STRING" key = token.value else: # quoted string (double or single) token = sp.children[0].children[0] key = token.value # clean it to match the dict key key = self._mapfile_todict.clean_string(key).lower() assert key in d.keys() key_comments = self.get_comments(sp.meta) d["__comments__"][key] = key_comments return d
python
def add_metadata_comments(self, d, metadata): """ Any duplicate keys will be replaced with the last duplicate along with comments """ if len(metadata) > 2: string_pairs = metadata[1:-1] # get all metadata pairs for sp in string_pairs: # get the raw metadata key if isinstance(sp.children[0], Token): token = sp.children[0] assert token.type == "UNQUOTED_STRING" key = token.value else: # quoted string (double or single) token = sp.children[0].children[0] key = token.value # clean it to match the dict key key = self._mapfile_todict.clean_string(key).lower() assert key in d.keys() key_comments = self.get_comments(sp.meta) d["__comments__"][key] = key_comments return d
[ "def", "add_metadata_comments", "(", "self", ",", "d", ",", "metadata", ")", ":", "if", "len", "(", "metadata", ")", ">", "2", ":", "string_pairs", "=", "metadata", "[", "1", ":", "-", "1", "]", "# get all metadata pairs", "for", "sp", "in", "string_pair...
Any duplicate keys will be replaced with the last duplicate along with comments
[ "Any", "duplicate", "keys", "will", "be", "replaced", "with", "the", "last", "duplicate", "along", "with", "comments" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/transformer.py#L605-L630
train
37,049
geographika/mappyfile
mappyfile/parser.py
Parser.assign_comments
def assign_comments(self, tree, comments): """ Capture any comments in the tree header_comments stores comments preceding a node """ comments = list(comments) comments.sort(key=lambda c: c.line) idx_by_line = {0: 0} # {line_no: comment_idx} for i, c in enumerate(comments): if c.line not in idx_by_line: idx_by_line[c.line] = i idx = [] # convert comment tokens to strings, and remove any line breaks self.comments = [c.value.strip() for c in comments] last_comment_line = max(idx_by_line.keys()) # make a list with an entry for each line # number associated with a comment list index for i in range(last_comment_line, 0, -1): if i in idx_by_line: # associate line with new comment idx.append(idx_by_line[i]) else: # associate line with following comment idx.append(idx[-1]) idx.append(0) # line numbers start from 1 idx.reverse() self.idx = idx self._assign_comments(tree, 0)
python
def assign_comments(self, tree, comments): """ Capture any comments in the tree header_comments stores comments preceding a node """ comments = list(comments) comments.sort(key=lambda c: c.line) idx_by_line = {0: 0} # {line_no: comment_idx} for i, c in enumerate(comments): if c.line not in idx_by_line: idx_by_line[c.line] = i idx = [] # convert comment tokens to strings, and remove any line breaks self.comments = [c.value.strip() for c in comments] last_comment_line = max(idx_by_line.keys()) # make a list with an entry for each line # number associated with a comment list index for i in range(last_comment_line, 0, -1): if i in idx_by_line: # associate line with new comment idx.append(idx_by_line[i]) else: # associate line with following comment idx.append(idx[-1]) idx.append(0) # line numbers start from 1 idx.reverse() self.idx = idx self._assign_comments(tree, 0)
[ "def", "assign_comments", "(", "self", ",", "tree", ",", "comments", ")", ":", "comments", "=", "list", "(", "comments", ")", "comments", ".", "sort", "(", "key", "=", "lambda", "c", ":", "c", ".", "line", ")", "idx_by_line", "=", "{", "0", ":", "0...
Capture any comments in the tree header_comments stores comments preceding a node
[ "Capture", "any", "comments", "in", "the", "tree" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/parser.py#L80-L116
train
37,050
geographika/mappyfile
mappyfile/parser.py
Parser.parse
def parse(self, text, fn=None): """ Parse the Mapfile """ if PY2 and not isinstance(text, unicode): # specify Unicode for Python 2.7 text = unicode(text, 'utf-8') if self.expand_includes: text = self.load_includes(text, fn=fn) try: self._comments[:] = [] # clear any comments from a previous parse tree = self.lalr.parse(text) if self.include_comments: self.assign_comments(tree, self._comments) return tree except (ParseError, UnexpectedInput) as ex: if fn: log.error("Parsing of {} unsuccessful".format(fn)) else: log.error("Parsing of Mapfile unsuccessful") log.info(ex) raise
python
def parse(self, text, fn=None): """ Parse the Mapfile """ if PY2 and not isinstance(text, unicode): # specify Unicode for Python 2.7 text = unicode(text, 'utf-8') if self.expand_includes: text = self.load_includes(text, fn=fn) try: self._comments[:] = [] # clear any comments from a previous parse tree = self.lalr.parse(text) if self.include_comments: self.assign_comments(tree, self._comments) return tree except (ParseError, UnexpectedInput) as ex: if fn: log.error("Parsing of {} unsuccessful".format(fn)) else: log.error("Parsing of Mapfile unsuccessful") log.info(ex) raise
[ "def", "parse", "(", "self", ",", "text", ",", "fn", "=", "None", ")", ":", "if", "PY2", "and", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "# specify Unicode for Python 2.7", "text", "=", "unicode", "(", "text", ",", "'utf-8'", ")", "i...
Parse the Mapfile
[ "Parse", "the", "Mapfile" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/parser.py#L184-L208
train
37,051
geographika/mappyfile
mappyfile/validator.py
Validator.validate
def validate(self, value, add_comments=False, schema_name="map"): """ verbose - also return the jsonschema error details """ validator = self.get_schema_validator(schema_name) error_messages = [] if isinstance(value, list): for d in value: error_messages += self._validate(d, validator, add_comments, schema_name) else: error_messages = self._validate(value, validator, add_comments, schema_name) return error_messages
python
def validate(self, value, add_comments=False, schema_name="map"): """ verbose - also return the jsonschema error details """ validator = self.get_schema_validator(schema_name) error_messages = [] if isinstance(value, list): for d in value: error_messages += self._validate(d, validator, add_comments, schema_name) else: error_messages = self._validate(value, validator, add_comments, schema_name) return error_messages
[ "def", "validate", "(", "self", ",", "value", ",", "add_comments", "=", "False", ",", "schema_name", "=", "\"map\"", ")", ":", "validator", "=", "self", ".", "get_schema_validator", "(", "schema_name", ")", "error_messages", "=", "[", "]", "if", "isinstance"...
verbose - also return the jsonschema error details
[ "verbose", "-", "also", "return", "the", "jsonschema", "error", "details" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/validator.py#L169-L183
train
37,052
geographika/mappyfile
docs/examples/parsing.py
output
def output(s): """ Parse, transform, and pretty print the result """ p = Parser() t = ExpressionsTransformer() ast = p.parse(s) logging.debug(ast.pretty()) print(ast.pretty()) d = t.transform(ast) print(json.dumps(d, indent=4)) return d
python
def output(s): """ Parse, transform, and pretty print the result """ p = Parser() t = ExpressionsTransformer() ast = p.parse(s) logging.debug(ast.pretty()) print(ast.pretty()) d = t.transform(ast) print(json.dumps(d, indent=4)) return d
[ "def", "output", "(", "s", ")", ":", "p", "=", "Parser", "(", ")", "t", "=", "ExpressionsTransformer", "(", ")", "ast", "=", "p", ".", "parse", "(", "s", ")", "logging", ".", "debug", "(", "ast", ".", "pretty", "(", ")", ")", "print", "(", "ast...
Parse, transform, and pretty print the result
[ "Parse", "transform", "and", "pretty", "print", "the", "result" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/docs/examples/parsing.py#L117-L130
train
37,053
geographika/mappyfile
mappyfile/cli.py
main
def main(ctx, verbose, quiet): """ Execute the main mappyfile command """ verbosity = verbose - quiet configure_logging(verbosity) ctx.obj = {} ctx.obj['verbosity'] = verbosity
python
def main(ctx, verbose, quiet): """ Execute the main mappyfile command """ verbosity = verbose - quiet configure_logging(verbosity) ctx.obj = {} ctx.obj['verbosity'] = verbosity
[ "def", "main", "(", "ctx", ",", "verbose", ",", "quiet", ")", ":", "verbosity", "=", "verbose", "-", "quiet", "configure_logging", "(", "verbosity", ")", "ctx", ".", "obj", "=", "{", "}", "ctx", ".", "obj", "[", "'verbosity'", "]", "=", "verbosity" ]
Execute the main mappyfile command
[ "Execute", "the", "main", "mappyfile", "command" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/cli.py#L41-L48
train
37,054
geographika/mappyfile
mappyfile/cli.py
format
def format(ctx, input_mapfile, output_mapfile, indent, spacer, quote, newlinechar, expand, comments): """ Format a the input-mapfile and save as output-mapfile. Note output-mapfile will be overwritten if it already exists. Example of formatting a single Mapfile: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map Example of formatting a single Mapfile with single quotes and tabs for indentation: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map --quote=\\' --indent=1 --spacer=\t Example of formatting a single Mapfile without expanding includes, but including comments: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map --no-expand --comments """ quote = codecs.decode(quote, 'unicode_escape') # ensure \t is handled as a tab spacer = codecs.decode(spacer, 'unicode_escape') # ensure \t is handled as a tab newlinechar = codecs.decode(newlinechar, 'unicode_escape') # ensure \n is handled as a newline d = mappyfile.open(input_mapfile, expand_includes=expand, include_comments=comments, include_position=True) mappyfile.save(d, output_mapfile, indent=indent, spacer=spacer, quote=quote, newlinechar=newlinechar) sys.exit(0)
python
def format(ctx, input_mapfile, output_mapfile, indent, spacer, quote, newlinechar, expand, comments): """ Format a the input-mapfile and save as output-mapfile. Note output-mapfile will be overwritten if it already exists. Example of formatting a single Mapfile: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map Example of formatting a single Mapfile with single quotes and tabs for indentation: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map --quote=\\' --indent=1 --spacer=\t Example of formatting a single Mapfile without expanding includes, but including comments: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map --no-expand --comments """ quote = codecs.decode(quote, 'unicode_escape') # ensure \t is handled as a tab spacer = codecs.decode(spacer, 'unicode_escape') # ensure \t is handled as a tab newlinechar = codecs.decode(newlinechar, 'unicode_escape') # ensure \n is handled as a newline d = mappyfile.open(input_mapfile, expand_includes=expand, include_comments=comments, include_position=True) mappyfile.save(d, output_mapfile, indent=indent, spacer=spacer, quote=quote, newlinechar=newlinechar) sys.exit(0)
[ "def", "format", "(", "ctx", ",", "input_mapfile", ",", "output_mapfile", ",", "indent", ",", "spacer", ",", "quote", ",", "newlinechar", ",", "expand", ",", "comments", ")", ":", "quote", "=", "codecs", ".", "decode", "(", "quote", ",", "'unicode_escape'"...
Format a the input-mapfile and save as output-mapfile. Note output-mapfile will be overwritten if it already exists. Example of formatting a single Mapfile: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map Example of formatting a single Mapfile with single quotes and tabs for indentation: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map --quote=\\' --indent=1 --spacer=\t Example of formatting a single Mapfile without expanding includes, but including comments: mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map --no-expand --comments
[ "Format", "a", "the", "input", "-", "mapfile", "and", "save", "as", "output", "-", "mapfile", ".", "Note", "output", "-", "mapfile", "will", "be", "overwritten", "if", "it", "already", "exists", "." ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/cli.py#L61-L85
train
37,055
geographika/mappyfile
mappyfile/utils.py
open
def open(fn, expand_includes=True, include_comments=False, include_position=False, **kwargs): """ Load a Mapfile from the supplied filename into a Python dictionary. Parameters ---------- fn: string The path to the Mapfile, or partial Mapfile expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a filename and return it as a dictionary object:: d = mappyfile.open('mymap.map') Notes ----- Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object. """ p = Parser(expand_includes=expand_includes, include_comments=include_comments, **kwargs) ast = p.parse_file(fn) m = MapfileToDict(include_position=include_position, include_comments=include_comments, **kwargs) d = m.transform(ast) return d
python
def open(fn, expand_includes=True, include_comments=False, include_position=False, **kwargs): """ Load a Mapfile from the supplied filename into a Python dictionary. Parameters ---------- fn: string The path to the Mapfile, or partial Mapfile expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a filename and return it as a dictionary object:: d = mappyfile.open('mymap.map') Notes ----- Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object. """ p = Parser(expand_includes=expand_includes, include_comments=include_comments, **kwargs) ast = p.parse_file(fn) m = MapfileToDict(include_position=include_position, include_comments=include_comments, **kwargs) d = m.transform(ast) return d
[ "def", "open", "(", "fn", ",", "expand_includes", "=", "True", ",", "include_comments", "=", "False", ",", "include_position", "=", "False", ",", "*", "*", "kwargs", ")", ":", "p", "=", "Parser", "(", "expand_includes", "=", "expand_includes", ",", "includ...
Load a Mapfile from the supplied filename into a Python dictionary. Parameters ---------- fn: string The path to the Mapfile, or partial Mapfile expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a filename and return it as a dictionary object:: d = mappyfile.open('mymap.map') Notes ----- Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object.
[ "Load", "a", "Mapfile", "from", "the", "supplied", "filename", "into", "a", "Python", "dictionary", "." ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L34-L75
train
37,056
geographika/mappyfile
mappyfile/utils.py
load
def load(fp, expand_includes=True, include_position=False, include_comments=False, **kwargs): """ Load a Mapfile from an open file or file-like object. Parameters ---------- fp: file A file-like object - as with all Mapfiles this should be encoded in "utf-8" expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a file and return it as a dictionary object:: with open('mymap.map') as fp: d = mappyfile.load(fp) Notes ----- Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object. """ p = Parser(expand_includes=expand_includes, include_comments=include_comments, **kwargs) ast = p.load(fp) m = MapfileToDict(include_position=include_position, include_comments=include_comments, **kwargs) d = m.transform(ast) return d
python
def load(fp, expand_includes=True, include_position=False, include_comments=False, **kwargs): """ Load a Mapfile from an open file or file-like object. Parameters ---------- fp: file A file-like object - as with all Mapfiles this should be encoded in "utf-8" expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a file and return it as a dictionary object:: with open('mymap.map') as fp: d = mappyfile.load(fp) Notes ----- Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object. """ p = Parser(expand_includes=expand_includes, include_comments=include_comments, **kwargs) ast = p.load(fp) m = MapfileToDict(include_position=include_position, include_comments=include_comments, **kwargs) d = m.transform(ast) return d
[ "def", "load", "(", "fp", ",", "expand_includes", "=", "True", ",", "include_position", "=", "False", ",", "include_comments", "=", "False", ",", "*", "*", "kwargs", ")", ":", "p", "=", "Parser", "(", "expand_includes", "=", "expand_includes", ",", "includ...
Load a Mapfile from an open file or file-like object. Parameters ---------- fp: file A file-like object - as with all Mapfiles this should be encoded in "utf-8" expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a file and return it as a dictionary object:: with open('mymap.map') as fp: d = mappyfile.load(fp) Notes ----- Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object.
[ "Load", "a", "Mapfile", "from", "an", "open", "file", "or", "file", "-", "like", "object", "." ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L78-L119
train
37,057
geographika/mappyfile
mappyfile/utils.py
loads
def loads(s, expand_includes=True, include_position=False, include_comments=False, **kwargs): """ Load a Mapfile from a string Parameters ---------- s: string The Mapfile, or partial Mapfile, text expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a string and return it as a dictionary object:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) assert d["name"] == "TEST" """ p = Parser(expand_includes=expand_includes, include_comments=include_comments, **kwargs) ast = p.parse(s) m = MapfileToDict(include_position=include_position, include_comments=include_comments, **kwargs) d = m.transform(ast) return d
python
def loads(s, expand_includes=True, include_position=False, include_comments=False, **kwargs): """ Load a Mapfile from a string Parameters ---------- s: string The Mapfile, or partial Mapfile, text expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a string and return it as a dictionary object:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) assert d["name"] == "TEST" """ p = Parser(expand_includes=expand_includes, include_comments=include_comments, **kwargs) ast = p.parse(s) m = MapfileToDict(include_position=include_position, include_comments=include_comments, **kwargs) d = m.transform(ast) return d
[ "def", "loads", "(", "s", ",", "expand_includes", "=", "True", ",", "include_position", "=", "False", ",", "include_comments", "=", "False", ",", "*", "*", "kwargs", ")", ":", "p", "=", "Parser", "(", "expand_includes", "=", "expand_includes", ",", "includ...
Load a Mapfile from a string Parameters ---------- s: string The Mapfile, or partial Mapfile, text expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard comment strings from the Mapfile - *experimental* include_position: boolean Include the position of the Mapfile tokens in the output Returns ------- dict A Python dictionary representing the Mapfile in the mappyfile format Example ------- To open a Mapfile from a string and return it as a dictionary object:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) assert d["name"] == "TEST"
[ "Load", "a", "Mapfile", "from", "a", "string" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L122-L161
train
37,058
geographika/mappyfile
mappyfile/utils.py
save
def save(d, output_file, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs): """ Write a dictionary to an output Mapfile on disk Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema output_file: string The output filename indent: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Returns ------- string The output_file passed into the function Example ------- To open a Mapfile from a string, and then save it to a file:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) fn = "C:/Data/mymap.map" mappyfile.save(d, fn) """ map_string = _pprint(d, indent, spacer, quote, newlinechar, end_comment) _save(output_file, map_string) return output_file
python
def save(d, output_file, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs): """ Write a dictionary to an output Mapfile on disk Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema output_file: string The output filename indent: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Returns ------- string The output_file passed into the function Example ------- To open a Mapfile from a string, and then save it to a file:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) fn = "C:/Data/mymap.map" mappyfile.save(d, fn) """ map_string = _pprint(d, indent, spacer, quote, newlinechar, end_comment) _save(output_file, map_string) return output_file
[ "def", "save", "(", "d", ",", "output_file", ",", "indent", "=", "4", ",", "spacer", "=", "\" \"", ",", "quote", "=", "'\"'", ",", "newlinechar", "=", "\"\\n\"", ",", "end_comment", "=", "False", ",", "*", "*", "kwargs", ")", ":", "map_string", "=", ...
Write a dictionary to an output Mapfile on disk Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema output_file: string The output filename indent: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Returns ------- string The output_file passed into the function Example ------- To open a Mapfile from a string, and then save it to a file:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) fn = "C:/Data/mymap.map" mappyfile.save(d, fn)
[ "Write", "a", "dictionary", "to", "an", "output", "Mapfile", "on", "disk" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L205-L248
train
37,059
geographika/mappyfile
mappyfile/utils.py
dumps
def dumps(d, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs): """ Output a Mapfile dictionary as a string Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema indent: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Returns ------- string The Mapfile as a string Example ------- To open a Mapfile from a string, and then print it back out as a string using tabs:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) print(mappyfile.dumps(d, indent=1, spacer="\\t")) """ return _pprint(d, indent, spacer, quote, newlinechar, end_comment, **kwargs)
python
def dumps(d, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs): """ Output a Mapfile dictionary as a string Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema indent: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Returns ------- string The Mapfile as a string Example ------- To open a Mapfile from a string, and then print it back out as a string using tabs:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) print(mappyfile.dumps(d, indent=1, spacer="\\t")) """ return _pprint(d, indent, spacer, quote, newlinechar, end_comment, **kwargs)
[ "def", "dumps", "(", "d", ",", "indent", "=", "4", ",", "spacer", "=", "\" \"", ",", "quote", "=", "'\"'", ",", "newlinechar", "=", "\"\\n\"", ",", "end_comment", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "_pprint", "(", "d", ",", ...
Output a Mapfile dictionary as a string Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema indent: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Returns ------- string The Mapfile as a string Example ------- To open a Mapfile from a string, and then print it back out as a string using tabs:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) print(mappyfile.dumps(d, indent=1, spacer="\\t"))
[ "Output", "a", "Mapfile", "dictionary", "as", "a", "string" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L251-L290
train
37,060
geographika/mappyfile
mappyfile/utils.py
find
def find(lst, key, value): """ Find an item in a list of dicts using a key and a value Parameters ---------- list: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list key: value The value to search for Returns ------- dict The first composite dictionary object with a key that matches the value Example ------- To find the ``LAYER`` in a list of layers with ``NAME`` set to ``Layer2``:: s = ''' MAP LAYER NAME "Layer1" TYPE POLYGON END LAYER NAME "Layer2" TYPE POLYGON CLASS NAME "Class1" COLOR 0 0 -8 END END END ''' d = mappyfile.loads(s) cmp = mappyfile.find(d["layers"], "name", "Layer2") assert cmp["name"] == "Layer2" """ return next((item for item in lst if item[key.lower()] == value), None)
python
def find(lst, key, value): """ Find an item in a list of dicts using a key and a value Parameters ---------- list: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list key: value The value to search for Returns ------- dict The first composite dictionary object with a key that matches the value Example ------- To find the ``LAYER`` in a list of layers with ``NAME`` set to ``Layer2``:: s = ''' MAP LAYER NAME "Layer1" TYPE POLYGON END LAYER NAME "Layer2" TYPE POLYGON CLASS NAME "Class1" COLOR 0 0 -8 END END END ''' d = mappyfile.loads(s) cmp = mappyfile.find(d["layers"], "name", "Layer2") assert cmp["name"] == "Layer2" """ return next((item for item in lst if item[key.lower()] == value), None)
[ "def", "find", "(", "lst", ",", "key", ",", "value", ")", ":", "return", "next", "(", "(", "item", "for", "item", "in", "lst", "if", "item", "[", "key", ".", "lower", "(", ")", "]", "==", "value", ")", ",", "None", ")" ]
Find an item in a list of dicts using a key and a value Parameters ---------- list: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list key: value The value to search for Returns ------- dict The first composite dictionary object with a key that matches the value Example ------- To find the ``LAYER`` in a list of layers with ``NAME`` set to ``Layer2``:: s = ''' MAP LAYER NAME "Layer1" TYPE POLYGON END LAYER NAME "Layer2" TYPE POLYGON CLASS NAME "Class1" COLOR 0 0 -8 END END END ''' d = mappyfile.loads(s) cmp = mappyfile.find(d["layers"], "name", "Layer2") assert cmp["name"] == "Layer2"
[ "Find", "an", "item", "in", "a", "list", "of", "dicts", "using", "a", "key", "and", "a", "value" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L293-L339
train
37,061
geographika/mappyfile
mappyfile/utils.py
findall
def findall(lst, key, value): """ Find all items in lst where key matches value. For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE`` Parameters ---------- list: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list key: value The value to search for Returns ------- list A Python list containing the matching composite dictionaries Example ------- To find all ``LAYER`` s with ``GROUP`` set to ``test``:: s = ''' MAP LAYER NAME "Layer1" TYPE POLYGON GROUP "test" END LAYER NAME "Layer2" TYPE POLYGON GROUP "test1" END LAYER NAME "Layer3" TYPE POLYGON GROUP "test2" END LAYER NAME "Layer4" TYPE POLYGON GROUP "test" END END ''' d = mappyfile.loads(s) layers = mappyfile.findall(d["layers"], "group", "test") assert len(layers) == 2 """ return [item for item in lst if item[key.lower()] in value]
python
def findall(lst, key, value): """ Find all items in lst where key matches value. For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE`` Parameters ---------- list: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list key: value The value to search for Returns ------- list A Python list containing the matching composite dictionaries Example ------- To find all ``LAYER`` s with ``GROUP`` set to ``test``:: s = ''' MAP LAYER NAME "Layer1" TYPE POLYGON GROUP "test" END LAYER NAME "Layer2" TYPE POLYGON GROUP "test1" END LAYER NAME "Layer3" TYPE POLYGON GROUP "test2" END LAYER NAME "Layer4" TYPE POLYGON GROUP "test" END END ''' d = mappyfile.loads(s) layers = mappyfile.findall(d["layers"], "group", "test") assert len(layers) == 2 """ return [item for item in lst if item[key.lower()] in value]
[ "def", "findall", "(", "lst", ",", "key", ",", "value", ")", ":", "return", "[", "item", "for", "item", "in", "lst", "if", "item", "[", "key", ".", "lower", "(", ")", "]", "in", "value", "]" ]
Find all items in lst where key matches value. For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE`` Parameters ---------- list: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list key: value The value to search for Returns ------- list A Python list containing the matching composite dictionaries Example ------- To find all ``LAYER`` s with ``GROUP`` set to ``test``:: s = ''' MAP LAYER NAME "Layer1" TYPE POLYGON GROUP "test" END LAYER NAME "Layer2" TYPE POLYGON GROUP "test1" END LAYER NAME "Layer3" TYPE POLYGON GROUP "test2" END LAYER NAME "Layer4" TYPE POLYGON GROUP "test" END END ''' d = mappyfile.loads(s) layers = mappyfile.findall(d["layers"], "group", "test") assert len(layers) == 2
[ "Find", "all", "items", "in", "lst", "where", "key", "matches", "value", ".", "For", "example", "find", "all", "LAYER", "s", "in", "a", "MAP", "where", "GROUP", "equals", "VALUE" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L342-L397
train
37,062
geographika/mappyfile
mappyfile/utils.py
findunique
def findunique(lst, key): """ Find all unique key values for items in lst. Parameters ---------- lst: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list Returns ------- list A sorted Python list of unique keys in the list Example ------- To find all ``GROUP`` values for ``CLASS`` in a ``LAYER``:: s = ''' LAYER CLASS GROUP "group1" NAME "Class1" COLOR 0 0 0 END CLASS GROUP "group2" NAME "Class2" COLOR 0 0 0 END CLASS GROUP "group1" NAME "Class3" COLOR 0 0 0 END END ''' d = mappyfile.loads(s) groups = mappyfile.findunique(d["classes"], "group") assert groups == ["group1", "group2"] """ return sorted(set([item[key.lower()] for item in lst]))
python
def findunique(lst, key): """ Find all unique key values for items in lst. Parameters ---------- lst: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list Returns ------- list A sorted Python list of unique keys in the list Example ------- To find all ``GROUP`` values for ``CLASS`` in a ``LAYER``:: s = ''' LAYER CLASS GROUP "group1" NAME "Class1" COLOR 0 0 0 END CLASS GROUP "group2" NAME "Class2" COLOR 0 0 0 END CLASS GROUP "group1" NAME "Class3" COLOR 0 0 0 END END ''' d = mappyfile.loads(s) groups = mappyfile.findunique(d["classes"], "group") assert groups == ["group1", "group2"] """ return sorted(set([item[key.lower()] for item in lst]))
[ "def", "findunique", "(", "lst", ",", "key", ")", ":", "return", "sorted", "(", "set", "(", "[", "item", "[", "key", ".", "lower", "(", ")", "]", "for", "item", "in", "lst", "]", ")", ")" ]
Find all unique key values for items in lst. Parameters ---------- lst: list A list of composite dictionaries e.g. ``layers``, ``classes`` key: string The key name to search each dictionary in the list Returns ------- list A sorted Python list of unique keys in the list Example ------- To find all ``GROUP`` values for ``CLASS`` in a ``LAYER``:: s = ''' LAYER CLASS GROUP "group1" NAME "Class1" COLOR 0 0 0 END CLASS GROUP "group2" NAME "Class2" COLOR 0 0 0 END CLASS GROUP "group1" NAME "Class3" COLOR 0 0 0 END END ''' d = mappyfile.loads(s) groups = mappyfile.findunique(d["classes"], "group") assert groups == ["group1", "group2"]
[ "Find", "all", "unique", "key", "values", "for", "items", "in", "lst", "." ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L400-L447
train
37,063
geographika/mappyfile
mappyfile/utils.py
update
def update(d1, d2): """ Update dict d1 with properties from d2 Note ---- Allows deletion of objects with a special ``__delete__`` key For any list of dicts new items can be added when updating Parameters ---------- d1: dict A Python dictionary d2: dict A Python dictionary that will be used to update any keys with the same name in d1 Returns ------- dict The updated dictionary """ NoneType = type(None) if d2.get("__delete__", False): return {} for k, v in d2.items(): if isinstance(v, dict): if v.get("__delete__", False): # allow a __delete__ property to be set to delete objects del d1[k] else: d1[k] = update(d1.get(k, {}), v) elif isinstance(v, (tuple, list)) and all(isinstance(li, (NoneType, dict)) for li in v): # a list of dicts and/or NoneType orig_list = d1.get(k, []) new_list = [] pairs = list(zip_longest(orig_list, v, fillvalue=None)) for orig_item, new_item in pairs: if orig_item is None: orig_item = {} # can't use {} for fillvalue as only one dict created/modified! if new_item is None: new_item = {} if new_item.get("__delete__", False): d = None # orig_list.remove(orig_item) # remove the item to delete else: d = update(orig_item, new_item) if d is not None: new_list.append(d) d1[k] = new_list else: if k in d1 and v == "__delete__": del d1[k] else: d1[k] = v return d1
python
def update(d1, d2): """ Update dict d1 with properties from d2 Note ---- Allows deletion of objects with a special ``__delete__`` key For any list of dicts new items can be added when updating Parameters ---------- d1: dict A Python dictionary d2: dict A Python dictionary that will be used to update any keys with the same name in d1 Returns ------- dict The updated dictionary """ NoneType = type(None) if d2.get("__delete__", False): return {} for k, v in d2.items(): if isinstance(v, dict): if v.get("__delete__", False): # allow a __delete__ property to be set to delete objects del d1[k] else: d1[k] = update(d1.get(k, {}), v) elif isinstance(v, (tuple, list)) and all(isinstance(li, (NoneType, dict)) for li in v): # a list of dicts and/or NoneType orig_list = d1.get(k, []) new_list = [] pairs = list(zip_longest(orig_list, v, fillvalue=None)) for orig_item, new_item in pairs: if orig_item is None: orig_item = {} # can't use {} for fillvalue as only one dict created/modified! if new_item is None: new_item = {} if new_item.get("__delete__", False): d = None # orig_list.remove(orig_item) # remove the item to delete else: d = update(orig_item, new_item) if d is not None: new_list.append(d) d1[k] = new_list else: if k in d1 and v == "__delete__": del d1[k] else: d1[k] = v return d1
[ "def", "update", "(", "d1", ",", "d2", ")", ":", "NoneType", "=", "type", "(", "None", ")", "if", "d2", ".", "get", "(", "\"__delete__\"", ",", "False", ")", ":", "return", "{", "}", "for", "k", ",", "v", "in", "d2", ".", "items", "(", ")", "...
Update dict d1 with properties from d2 Note ---- Allows deletion of objects with a special ``__delete__`` key For any list of dicts new items can be added when updating Parameters ---------- d1: dict A Python dictionary d2: dict A Python dictionary that will be used to update any keys with the same name in d1 Returns ------- dict The updated dictionary
[ "Update", "dict", "d1", "with", "properties", "from", "d2" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L500-L561
train
37,064
geographika/mappyfile
docs/examples/geometry/geometry.py
erosion
def erosion(mapfile, dilated): """ We will continue to work with the modified Mapfile If we wanted to start from scratch we could simply reread it """ ll = mappyfile.find(mapfile["layers"], "name", "line") ll["status"] = "OFF" pl = mappyfile.find(mapfile["layers"], "name", "polygon") # make a deep copy of the polygon layer in the Map # so any modification are made to this layer only pl2 = deepcopy(pl) pl2["name"] = "newpolygon" mapfile["layers"].append(pl2) dilated = dilated.buffer(-0.3) pl2["features"][0]["wkt"] = dilated.wkt style = pl["classes"][0]["styles"][0] style["color"] = "#999999" style["outlinecolor"] = "#b2b2b2"
python
def erosion(mapfile, dilated): """ We will continue to work with the modified Mapfile If we wanted to start from scratch we could simply reread it """ ll = mappyfile.find(mapfile["layers"], "name", "line") ll["status"] = "OFF" pl = mappyfile.find(mapfile["layers"], "name", "polygon") # make a deep copy of the polygon layer in the Map # so any modification are made to this layer only pl2 = deepcopy(pl) pl2["name"] = "newpolygon" mapfile["layers"].append(pl2) dilated = dilated.buffer(-0.3) pl2["features"][0]["wkt"] = dilated.wkt style = pl["classes"][0]["styles"][0] style["color"] = "#999999" style["outlinecolor"] = "#b2b2b2"
[ "def", "erosion", "(", "mapfile", ",", "dilated", ")", ":", "ll", "=", "mappyfile", ".", "find", "(", "mapfile", "[", "\"layers\"", "]", ",", "\"name\"", ",", "\"line\"", ")", "ll", "[", "\"status\"", "]", "=", "\"OFF\"", "pl", "=", "mappyfile", ".", ...
We will continue to work with the modified Mapfile If we wanted to start from scratch we could simply reread it
[ "We", "will", "continue", "to", "work", "with", "the", "modified", "Mapfile", "If", "we", "wanted", "to", "start", "from", "scratch", "we", "could", "simply", "reread", "it" ]
aecbc5e66ec06896bc4c5db41313503468829d00
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/docs/examples/geometry/geometry.py#L23-L45
train
37,065
dpursehouse/pygerrit2
pygerrit2/rest/__init__.py
GerritRestAPI.translate_kwargs
def translate_kwargs(self, **kwargs): """Translate kwargs replacing `data` with `json` if necessary.""" local_kwargs = self.kwargs.copy() local_kwargs.update(kwargs) if "data" in local_kwargs and "json" in local_kwargs: raise ValueError("Cannot use data and json together") if "data" in local_kwargs and isinstance(local_kwargs["data"], dict): local_kwargs.update({"json": local_kwargs["data"]}) del local_kwargs["data"] headers = DEFAULT_HEADERS.copy() if "headers" in kwargs: headers.update(kwargs["headers"]) if "json" in local_kwargs: headers.update({"Content-Type": "application/json;charset=UTF-8"}) local_kwargs.update({"headers": headers}) return local_kwargs
python
def translate_kwargs(self, **kwargs): """Translate kwargs replacing `data` with `json` if necessary.""" local_kwargs = self.kwargs.copy() local_kwargs.update(kwargs) if "data" in local_kwargs and "json" in local_kwargs: raise ValueError("Cannot use data and json together") if "data" in local_kwargs and isinstance(local_kwargs["data"], dict): local_kwargs.update({"json": local_kwargs["data"]}) del local_kwargs["data"] headers = DEFAULT_HEADERS.copy() if "headers" in kwargs: headers.update(kwargs["headers"]) if "json" in local_kwargs: headers.update({"Content-Type": "application/json;charset=UTF-8"}) local_kwargs.update({"headers": headers}) return local_kwargs
[ "def", "translate_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "local_kwargs", "=", "self", ".", "kwargs", ".", "copy", "(", ")", "local_kwargs", ".", "update", "(", "kwargs", ")", "if", "\"data\"", "in", "local_kwargs", "and", "\"json\"", "i...
Translate kwargs replacing `data` with `json` if necessary.
[ "Translate", "kwargs", "replacing", "data", "with", "json", "if", "necessary", "." ]
141031469603b33369d89c38c703390eb3786bd0
https://github.com/dpursehouse/pygerrit2/blob/141031469603b33369d89c38c703390eb3786bd0/pygerrit2/rest/__init__.py#L133-L152
train
37,066
dpursehouse/pygerrit2
pygerrit2/rest/__init__.py
GerritRestAPI.post
def post(self, endpoint, return_response=False, **kwargs): """Send HTTP POST to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error. """ args = self.translate_kwargs(**kwargs) response = self.session.post(self.make_url(endpoint), **args) decoded_response = _decode_response(response) if return_response: return decoded_response, response return decoded_response
python
def post(self, endpoint, return_response=False, **kwargs): """Send HTTP POST to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error. """ args = self.translate_kwargs(**kwargs) response = self.session.post(self.make_url(endpoint), **args) decoded_response = _decode_response(response) if return_response: return decoded_response, response return decoded_response
[ "def", "post", "(", "self", ",", "endpoint", ",", "return_response", "=", "False", ",", "*", "*", "kwargs", ")", ":", "args", "=", "self", ".", "translate_kwargs", "(", "*", "*", "kwargs", ")", "response", "=", "self", ".", "session", ".", "post", "(...
Send HTTP POST to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error.
[ "Send", "HTTP", "POST", "to", "the", "endpoint", "." ]
141031469603b33369d89c38c703390eb3786bd0
https://github.com/dpursehouse/pygerrit2/blob/141031469603b33369d89c38c703390eb3786bd0/pygerrit2/rest/__init__.py#L197-L216
train
37,067
dpursehouse/pygerrit2
pygerrit2/__init__.py
escape_string
def escape_string(string): """Escape a string for use in Gerrit commands. :arg str string: The string to escape. :returns: The string with necessary escapes and surrounding double quotes so that it can be passed to any of the Gerrit commands that require double-quoted strings. """ result = string result = result.replace('\\', '\\\\') result = result.replace('"', '\\"') return '"' + result + '"'
python
def escape_string(string): """Escape a string for use in Gerrit commands. :arg str string: The string to escape. :returns: The string with necessary escapes and surrounding double quotes so that it can be passed to any of the Gerrit commands that require double-quoted strings. """ result = string result = result.replace('\\', '\\\\') result = result.replace('"', '\\"') return '"' + result + '"'
[ "def", "escape_string", "(", "string", ")", ":", "result", "=", "string", "result", "=", "result", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "result", "=", "result", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "return", "'\"'", "+", ...
Escape a string for use in Gerrit commands. :arg str string: The string to escape. :returns: The string with necessary escapes and surrounding double quotes so that it can be passed to any of the Gerrit commands that require double-quoted strings.
[ "Escape", "a", "string", "for", "use", "in", "Gerrit", "commands", "." ]
141031469603b33369d89c38c703390eb3786bd0
https://github.com/dpursehouse/pygerrit2/blob/141031469603b33369d89c38c703390eb3786bd0/pygerrit2/__init__.py#L49-L62
train
37,068
dpursehouse/pygerrit2
pygerrit2/__init__.py
GerritReviewMessageFormatter.append
def append(self, data): """Append the given `data` to the output. :arg data: If a list, it is formatted as a bullet list with each entry in the list being a separate bullet. Otherwise if it is a string, the string is added as a paragraph. :raises: ValueError if `data` is not a list or a string. """ if not data: return if isinstance(data, list): # First we need to clean up the data. # # Gerrit creates new bullet items when it gets newline characters # within a bullet list paragraph, so unless we remove the newlines # from the texts the resulting bullet list will contain multiple # bullets and look crappy. # # We add the '*' character on the beginning of each bullet text in # the next step, so we strip off any existing leading '*' that the # caller has added, and then strip off any leading or trailing # whitespace. _items = [x.replace("\n", " ").strip().lstrip('*').strip() for x in data] # Create the bullet list only with the items that still have any # text in them after cleaning up. _paragraph = "\n".join(["* %s" % x for x in _items if x]) if _paragraph: self.paragraphs.append(_paragraph) elif isinstance(data, str): _paragraph = data.strip() if _paragraph: self.paragraphs.append(_paragraph) else: raise ValueError('Data must be a list or a string')
python
def append(self, data): """Append the given `data` to the output. :arg data: If a list, it is formatted as a bullet list with each entry in the list being a separate bullet. Otherwise if it is a string, the string is added as a paragraph. :raises: ValueError if `data` is not a list or a string. """ if not data: return if isinstance(data, list): # First we need to clean up the data. # # Gerrit creates new bullet items when it gets newline characters # within a bullet list paragraph, so unless we remove the newlines # from the texts the resulting bullet list will contain multiple # bullets and look crappy. # # We add the '*' character on the beginning of each bullet text in # the next step, so we strip off any existing leading '*' that the # caller has added, and then strip off any leading or trailing # whitespace. _items = [x.replace("\n", " ").strip().lstrip('*').strip() for x in data] # Create the bullet list only with the items that still have any # text in them after cleaning up. _paragraph = "\n".join(["* %s" % x for x in _items if x]) if _paragraph: self.paragraphs.append(_paragraph) elif isinstance(data, str): _paragraph = data.strip() if _paragraph: self.paragraphs.append(_paragraph) else: raise ValueError('Data must be a list or a string')
[ "def", "append", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "return", "if", "isinstance", "(", "data", ",", "list", ")", ":", "# First we need to clean up the data.", "#", "# Gerrit creates new bullet items when it gets newline characters", "# withi...
Append the given `data` to the output. :arg data: If a list, it is formatted as a bullet list with each entry in the list being a separate bullet. Otherwise if it is a string, the string is added as a paragraph. :raises: ValueError if `data` is not a list or a string.
[ "Append", "the", "given", "data", "to", "the", "output", "." ]
141031469603b33369d89c38c703390eb3786bd0
https://github.com/dpursehouse/pygerrit2/blob/141031469603b33369d89c38c703390eb3786bd0/pygerrit2/__init__.py#L87-L125
train
37,069
dpursehouse/pygerrit2
pygerrit2/__init__.py
GerritReviewMessageFormatter.format
def format(self): """Format the message parts to a string. :Returns: A string of all the message parts separated into paragraphs, with header and footer paragraphs if they were specified in the constructor. """ message = "" if self.paragraphs: if self.header: message += (self.header + '\n\n') message += "\n\n".join(self.paragraphs) if self.footer: message += ('\n\n' + self.footer) return message
python
def format(self): """Format the message parts to a string. :Returns: A string of all the message parts separated into paragraphs, with header and footer paragraphs if they were specified in the constructor. """ message = "" if self.paragraphs: if self.header: message += (self.header + '\n\n') message += "\n\n".join(self.paragraphs) if self.footer: message += ('\n\n' + self.footer) return message
[ "def", "format", "(", "self", ")", ":", "message", "=", "\"\"", "if", "self", ".", "paragraphs", ":", "if", "self", ".", "header", ":", "message", "+=", "(", "self", ".", "header", "+", "'\\n\\n'", ")", "message", "+=", "\"\\n\\n\"", ".", "join", "("...
Format the message parts to a string. :Returns: A string of all the message parts separated into paragraphs, with header and footer paragraphs if they were specified in the constructor.
[ "Format", "the", "message", "parts", "to", "a", "string", "." ]
141031469603b33369d89c38c703390eb3786bd0
https://github.com/dpursehouse/pygerrit2/blob/141031469603b33369d89c38c703390eb3786bd0/pygerrit2/__init__.py#L135-L150
train
37,070
Zimbra-Community/python-zimbra
pythonzimbra/request.py
Request.enable_batch
def enable_batch(self, onerror="continue"): """ Enables batch request gathering. Do this first and then consecutively call "add_request" to add more requests. :param onerror: "continue" (default) if one request fails (and response with soap Faults for the request) or "stop" processing. """ self.batch_request = True self.batch_request_id = 1 self._create_batch_node(onerror)
python
def enable_batch(self, onerror="continue"): """ Enables batch request gathering. Do this first and then consecutively call "add_request" to add more requests. :param onerror: "continue" (default) if one request fails (and response with soap Faults for the request) or "stop" processing. """ self.batch_request = True self.batch_request_id = 1 self._create_batch_node(onerror)
[ "def", "enable_batch", "(", "self", ",", "onerror", "=", "\"continue\"", ")", ":", "self", ".", "batch_request", "=", "True", "self", ".", "batch_request_id", "=", "1", "self", ".", "_create_batch_node", "(", "onerror", ")" ]
Enables batch request gathering. Do this first and then consecutively call "add_request" to add more requests. :param onerror: "continue" (default) if one request fails (and response with soap Faults for the request) or "stop" processing.
[ "Enables", "batch", "request", "gathering", "." ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/request.py#L75-L89
train
37,071
Zimbra-Community/python-zimbra
pythonzimbra/response.py
Response._filter_response
def _filter_response(self, response_dict): """ Add additional filters to the response dictionary Currently the response dictionary is filtered like this: * If a list only has one item, the list is replaced by that item * Namespace-Keys (_jsns and xmlns) are removed :param response_dict: the pregenerated, but unfiltered response dict :type response_dict: dict :return: The filtered dictionary :rtype: dict """ filtered_dict = {} for key, value in response_dict.items(): if key == "_jsns": continue if key == "xmlns": continue if type(value) == list and len(value) == 1: filtered_dict[key] = value[0] elif type(value) == dict and len(value.keys()) == 1 and "_content" \ in value.keys(): filtered_dict[key] = value["_content"] elif type(value) == dict: tmp_dict = self._filter_response(value) filtered_dict[key] = tmp_dict else: filtered_dict[key] = value return filtered_dict
python
def _filter_response(self, response_dict): """ Add additional filters to the response dictionary Currently the response dictionary is filtered like this: * If a list only has one item, the list is replaced by that item * Namespace-Keys (_jsns and xmlns) are removed :param response_dict: the pregenerated, but unfiltered response dict :type response_dict: dict :return: The filtered dictionary :rtype: dict """ filtered_dict = {} for key, value in response_dict.items(): if key == "_jsns": continue if key == "xmlns": continue if type(value) == list and len(value) == 1: filtered_dict[key] = value[0] elif type(value) == dict and len(value.keys()) == 1 and "_content" \ in value.keys(): filtered_dict[key] = value["_content"] elif type(value) == dict: tmp_dict = self._filter_response(value) filtered_dict[key] = tmp_dict else: filtered_dict[key] = value return filtered_dict
[ "def", "_filter_response", "(", "self", ",", "response_dict", ")", ":", "filtered_dict", "=", "{", "}", "for", "key", ",", "value", "in", "response_dict", ".", "items", "(", ")", ":", "if", "key", "==", "\"_jsns\"", ":", "continue", "if", "key", "==", ...
Add additional filters to the response dictionary Currently the response dictionary is filtered like this: * If a list only has one item, the list is replaced by that item * Namespace-Keys (_jsns and xmlns) are removed :param response_dict: the pregenerated, but unfiltered response dict :type response_dict: dict :return: The filtered dictionary :rtype: dict
[ "Add", "additional", "filters", "to", "the", "response", "dictionary" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/response.py#L151-L197
train
37,072
Zimbra-Community/python-zimbra
pythonzimbra/tools/preauth.py
create_preauth
def create_preauth(byval, key, by='name', expires=0, timestamp=None): """ Generates a zimbra preauth value :param byval: The value of the targeted user (according to the by-parameter). For example: The account name, if "by" is "name". :param key: The domain preauth key (you can retrieve that using zmprov gd) :param by: What type is the byval-parameter? Valid parameters are "name" (default), "id" and "foreignPrincipal" :param expires: Milliseconds when the auth token expires. Defaults to 0 for default account expiration :param timestamp: Current timestamp (is calculated by default) :returns: The preauth value to be used in an AuthRequest :rtype: str """ if timestamp is None: timestamp = int(datetime.now().strftime("%s")) * 1000 pak = hmac.new( codecs.latin_1_encode(key)[0], ('%s|%s|%s|%s' % ( byval, by, expires, timestamp )).encode("utf-8"), hashlib.sha1 ).hexdigest() return pak
python
def create_preauth(byval, key, by='name', expires=0, timestamp=None): """ Generates a zimbra preauth value :param byval: The value of the targeted user (according to the by-parameter). For example: The account name, if "by" is "name". :param key: The domain preauth key (you can retrieve that using zmprov gd) :param by: What type is the byval-parameter? Valid parameters are "name" (default), "id" and "foreignPrincipal" :param expires: Milliseconds when the auth token expires. Defaults to 0 for default account expiration :param timestamp: Current timestamp (is calculated by default) :returns: The preauth value to be used in an AuthRequest :rtype: str """ if timestamp is None: timestamp = int(datetime.now().strftime("%s")) * 1000 pak = hmac.new( codecs.latin_1_encode(key)[0], ('%s|%s|%s|%s' % ( byval, by, expires, timestamp )).encode("utf-8"), hashlib.sha1 ).hexdigest() return pak
[ "def", "create_preauth", "(", "byval", ",", "key", ",", "by", "=", "'name'", ",", "expires", "=", "0", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "int", "(", "datetime", ".", "now", "(", ")", "....
Generates a zimbra preauth value :param byval: The value of the targeted user (according to the by-parameter). For example: The account name, if "by" is "name". :param key: The domain preauth key (you can retrieve that using zmprov gd) :param by: What type is the byval-parameter? Valid parameters are "name" (default), "id" and "foreignPrincipal" :param expires: Milliseconds when the auth token expires. Defaults to 0 for default account expiration :param timestamp: Current timestamp (is calculated by default) :returns: The preauth value to be used in an AuthRequest :rtype: str
[ "Generates", "a", "zimbra", "preauth", "value" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/tools/preauth.py#L8-L38
train
37,073
Zimbra-Community/python-zimbra
pythonzimbra/tools/dict.py
zimbra_to_python
def zimbra_to_python(zimbra_dict, key_attribute="n", content_attribute="_content"): """ Converts single level Zimbra dicts to a standard python dict :param zimbra_dict: The dictionary in Zimbra-Format :return: A native python dict """ local_dict = {} for item in zimbra_dict: local_dict[item[key_attribute]] = item[content_attribute] return local_dict
python
def zimbra_to_python(zimbra_dict, key_attribute="n", content_attribute="_content"): """ Converts single level Zimbra dicts to a standard python dict :param zimbra_dict: The dictionary in Zimbra-Format :return: A native python dict """ local_dict = {} for item in zimbra_dict: local_dict[item[key_attribute]] = item[content_attribute] return local_dict
[ "def", "zimbra_to_python", "(", "zimbra_dict", ",", "key_attribute", "=", "\"n\"", ",", "content_attribute", "=", "\"_content\"", ")", ":", "local_dict", "=", "{", "}", "for", "item", "in", "zimbra_dict", ":", "local_dict", "[", "item", "[", "key_attribute", "...
Converts single level Zimbra dicts to a standard python dict :param zimbra_dict: The dictionary in Zimbra-Format :return: A native python dict
[ "Converts", "single", "level", "Zimbra", "dicts", "to", "a", "standard", "python", "dict" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/tools/dict.py#L15-L31
train
37,074
Zimbra-Community/python-zimbra
pythonzimbra/tools/dict.py
get_value
def get_value(haystack, needle, key_attribute="n", content_attribute="_content"): """ Fetch a value from a zimbra-like json dict (keys are "n", values are "_content" This function may be slightly faster than zimbra_to_python(haystack)[ needle], because it doesn't necessarily iterate over the complete list. :param haystack: The list in zimbra-dict format :param needle: the key to search for :return: the value or None, if the key is not found """ for value in haystack: if value[key_attribute] == needle: return value[content_attribute] return None
python
def get_value(haystack, needle, key_attribute="n", content_attribute="_content"): """ Fetch a value from a zimbra-like json dict (keys are "n", values are "_content" This function may be slightly faster than zimbra_to_python(haystack)[ needle], because it doesn't necessarily iterate over the complete list. :param haystack: The list in zimbra-dict format :param needle: the key to search for :return: the value or None, if the key is not found """ for value in haystack: if value[key_attribute] == needle: return value[content_attribute] return None
[ "def", "get_value", "(", "haystack", ",", "needle", ",", "key_attribute", "=", "\"n\"", ",", "content_attribute", "=", "\"_content\"", ")", ":", "for", "value", "in", "haystack", ":", "if", "value", "[", "key_attribute", "]", "==", "needle", ":", "return", ...
Fetch a value from a zimbra-like json dict (keys are "n", values are "_content" This function may be slightly faster than zimbra_to_python(haystack)[ needle], because it doesn't necessarily iterate over the complete list. :param haystack: The list in zimbra-dict format :param needle: the key to search for :return: the value or None, if the key is not found
[ "Fetch", "a", "value", "from", "a", "zimbra", "-", "like", "json", "dict", "(", "keys", "are", "n", "values", "are", "_content" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/tools/dict.py#L34-L54
train
37,075
Zimbra-Community/python-zimbra
pythonzimbra/tools/xmlserializer.py
dict_to_dom
def dict_to_dom(root_node, xml_dict): """ Create a DOM node and optionally several subnodes from a dictionary. :param root_node: DOM-Node set the dictionary is applied upon :type root_node: xml.dom.Element :param xml_dict: The dictionary containing the nodes to process :type xml_dict: dict """ if '_content' in list(xml_dict.keys()): root_node.appendChild( root_node.ownerDocument.createTextNode( convert_to_str(xml_dict['_content']) ) ) for key, value in xml_dict.items(): if key == '_content': continue if type(value) == dict: # Root node tmp_node = root_node.ownerDocument.createElement(key) dict_to_dom(tmp_node, value) root_node.appendChild(tmp_node) elif type(value) == list: for multinode in value: tmp_node = root_node.ownerDocument.createElement(key) dict_to_dom(tmp_node, multinode) root_node.appendChild(tmp_node) else: # Attributes root_node.setAttribute( key, convert_to_str(value) )
python
def dict_to_dom(root_node, xml_dict): """ Create a DOM node and optionally several subnodes from a dictionary. :param root_node: DOM-Node set the dictionary is applied upon :type root_node: xml.dom.Element :param xml_dict: The dictionary containing the nodes to process :type xml_dict: dict """ if '_content' in list(xml_dict.keys()): root_node.appendChild( root_node.ownerDocument.createTextNode( convert_to_str(xml_dict['_content']) ) ) for key, value in xml_dict.items(): if key == '_content': continue if type(value) == dict: # Root node tmp_node = root_node.ownerDocument.createElement(key) dict_to_dom(tmp_node, value) root_node.appendChild(tmp_node) elif type(value) == list: for multinode in value: tmp_node = root_node.ownerDocument.createElement(key) dict_to_dom(tmp_node, multinode) root_node.appendChild(tmp_node) else: # Attributes root_node.setAttribute( key, convert_to_str(value) )
[ "def", "dict_to_dom", "(", "root_node", ",", "xml_dict", ")", ":", "if", "'_content'", "in", "list", "(", "xml_dict", ".", "keys", "(", ")", ")", ":", "root_node", ".", "appendChild", "(", "root_node", ".", "ownerDocument", ".", "createTextNode", "(", "con...
Create a DOM node and optionally several subnodes from a dictionary. :param root_node: DOM-Node set the dictionary is applied upon :type root_node: xml.dom.Element :param xml_dict: The dictionary containing the nodes to process :type xml_dict: dict
[ "Create", "a", "DOM", "node", "and", "optionally", "several", "subnodes", "from", "a", "dictionary", "." ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/tools/xmlserializer.py#L28-L77
train
37,076
Zimbra-Community/python-zimbra
pythonzimbra/tools/xmlserializer.py
dom_to_dict
def dom_to_dict(root_node): """ Serializes the given node to the dictionary Serializes the given node to the documented dictionary format. :param root_node: Node to serialize :returns: The dictionary :rtype: dict """ # Remove namespaces from tagname tag = root_node.tagName if ":" in tag: tag = tag.split(":")[1] root_dict = { tag: {} } node_dict = root_dict[tag] # Set attributes if root_node.hasAttributes(): for key in list(root_node.attributes.keys()): node_dict[key] = root_node.getAttribute(key) # Check out child nodes for child in root_node.childNodes: if child.nodeType == root_node.TEXT_NODE: # This is the content node_dict['_content'] = child.data else: subnode_dict = dom_to_dict(child) child_tag = child.tagName if ":" in child_tag: child_tag = child_tag.split(":")[1] new_val = subnode_dict[child_tag] # If we have several child with same name, put them in a list. if child_tag in node_dict: prev_val = node_dict[child_tag] if type(prev_val) != list: node_dict[child_tag] = [prev_val] node_dict[child_tag].append(new_val) else: node_dict[child_tag] = new_val return root_dict
python
def dom_to_dict(root_node): """ Serializes the given node to the dictionary Serializes the given node to the documented dictionary format. :param root_node: Node to serialize :returns: The dictionary :rtype: dict """ # Remove namespaces from tagname tag = root_node.tagName if ":" in tag: tag = tag.split(":")[1] root_dict = { tag: {} } node_dict = root_dict[tag] # Set attributes if root_node.hasAttributes(): for key in list(root_node.attributes.keys()): node_dict[key] = root_node.getAttribute(key) # Check out child nodes for child in root_node.childNodes: if child.nodeType == root_node.TEXT_NODE: # This is the content node_dict['_content'] = child.data else: subnode_dict = dom_to_dict(child) child_tag = child.tagName if ":" in child_tag: child_tag = child_tag.split(":")[1] new_val = subnode_dict[child_tag] # If we have several child with same name, put them in a list. if child_tag in node_dict: prev_val = node_dict[child_tag] if type(prev_val) != list: node_dict[child_tag] = [prev_val] node_dict[child_tag].append(new_val) else: node_dict[child_tag] = new_val return root_dict
[ "def", "dom_to_dict", "(", "root_node", ")", ":", "# Remove namespaces from tagname", "tag", "=", "root_node", ".", "tagName", "if", "\":\"", "in", "tag", ":", "tag", "=", "tag", ".", "split", "(", "\":\"", ")", "[", "1", "]", "root_dict", "=", "{", "tag...
Serializes the given node to the dictionary Serializes the given node to the documented dictionary format. :param root_node: Node to serialize :returns: The dictionary :rtype: dict
[ "Serializes", "the", "given", "node", "to", "the", "dictionary" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/tools/xmlserializer.py#L80-L148
train
37,077
Zimbra-Community/python-zimbra
pythonzimbra/tools/urllib2_tls.py
TLS1Connection.connect
def connect(self): """Overrides HTTPSConnection.connect to specify TLS version""" # Standard implementation from HTTPSConnection, which is not # designed for extension, unfortunately sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) if getattr(self, '_tunnel_host', None): self.sock = sock # pragma: no cover self._tunnel() # pragma: no cover # This is the only difference; default wrap_socket uses SSLv23 self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1_2)
python
def connect(self): """Overrides HTTPSConnection.connect to specify TLS version""" # Standard implementation from HTTPSConnection, which is not # designed for extension, unfortunately sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) if getattr(self, '_tunnel_host', None): self.sock = sock # pragma: no cover self._tunnel() # pragma: no cover # This is the only difference; default wrap_socket uses SSLv23 self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1_2)
[ "def", "connect", "(", "self", ")", ":", "# Standard implementation from HTTPSConnection, which is not", "# designed for extension, unfortunately", "sock", "=", "socket", ".", "create_connection", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ",", "sel...
Overrides HTTPSConnection.connect to specify TLS version
[ "Overrides", "HTTPSConnection", ".", "connect", "to", "specify", "TLS", "version" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/tools/urllib2_tls.py#L22-L34
train
37,078
Zimbra-Community/python-zimbra
pythonzimbra/communication.py
Communication.gen_request
def gen_request(self, request_type="json", token=None, set_batch=False, batch_onerror=None): """ Convenience method to quickly generate a token :param request_type: Type of request (defaults to json) :param token: Authentication token :param set_batch: Also set this request to batch mode? :param batch_onerror: Onerror-parameter for batch mode :return: The request """ if request_type == "json": local_request = RequestJson() elif request_type == "xml": local_request = RequestXml() else: raise UnknownRequestType() if token is not None: local_request.set_auth_token(token) if set_batch: local_request.enable_batch(batch_onerror) return local_request
python
def gen_request(self, request_type="json", token=None, set_batch=False, batch_onerror=None): """ Convenience method to quickly generate a token :param request_type: Type of request (defaults to json) :param token: Authentication token :param set_batch: Also set this request to batch mode? :param batch_onerror: Onerror-parameter for batch mode :return: The request """ if request_type == "json": local_request = RequestJson() elif request_type == "xml": local_request = RequestXml() else: raise UnknownRequestType() if token is not None: local_request.set_auth_token(token) if set_batch: local_request.enable_batch(batch_onerror) return local_request
[ "def", "gen_request", "(", "self", ",", "request_type", "=", "\"json\"", ",", "token", "=", "None", ",", "set_batch", "=", "False", ",", "batch_onerror", "=", "None", ")", ":", "if", "request_type", "==", "\"json\"", ":", "local_request", "=", "RequestJson",...
Convenience method to quickly generate a token :param request_type: Type of request (defaults to json) :param token: Authentication token :param set_batch: Also set this request to batch mode? :param batch_onerror: Onerror-parameter for batch mode :return: The request
[ "Convenience", "method", "to", "quickly", "generate", "a", "token" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/communication.py#L54-L84
train
37,079
Zimbra-Community/python-zimbra
pythonzimbra/communication.py
Communication.send_request
def send_request(self, request, response=None): """ Send the request. Sends the request and retrieves the results, formats them and returns them in a dict or a list (when it's a batchresponse). If something goes wrong, raises a SoapFailure or a HTTPError on system-side failures. Note: AuthRequest raises an HTTPError on failed authentications! :param request: The request to send :type request: pythonzimbra.request.Request :param response: A prebuilt response object :type response: pythonzimbra.response.Response :raises: pythonzimbra.exceptions.communication.SoapFailure or urllib2.HTTPError """ local_response = None if response is None: if request.request_type == "json": local_response = ResponseJson() elif request.request_type == "xml": local_response = ResponseXml() else: raise UnknownRequestType() try: server_request = ur.urlopen( self.url, request.get_request().encode("utf-8"), self.timeout ) server_response = server_request.read() if isinstance(server_response, bytes): server_response = server_response.decode("utf-8") if response is None: local_response.set_response( server_response ) else: response.set_response(server_response) except ue.HTTPError as e: if e.code == 500: # 500 codes normally returns a SoapFault, that we can use server_response = e.fp.read() if isinstance(server_response, bytes): server_response = server_response.decode("utf-8") if response is None: local_response.set_response(server_response) else: response.set_response(server_response) else: raise e if response is None: return local_response
python
def send_request(self, request, response=None): """ Send the request. Sends the request and retrieves the results, formats them and returns them in a dict or a list (when it's a batchresponse). If something goes wrong, raises a SoapFailure or a HTTPError on system-side failures. Note: AuthRequest raises an HTTPError on failed authentications! :param request: The request to send :type request: pythonzimbra.request.Request :param response: A prebuilt response object :type response: pythonzimbra.response.Response :raises: pythonzimbra.exceptions.communication.SoapFailure or urllib2.HTTPError """ local_response = None if response is None: if request.request_type == "json": local_response = ResponseJson() elif request.request_type == "xml": local_response = ResponseXml() else: raise UnknownRequestType() try: server_request = ur.urlopen( self.url, request.get_request().encode("utf-8"), self.timeout ) server_response = server_request.read() if isinstance(server_response, bytes): server_response = server_response.decode("utf-8") if response is None: local_response.set_response( server_response ) else: response.set_response(server_response) except ue.HTTPError as e: if e.code == 500: # 500 codes normally returns a SoapFault, that we can use server_response = e.fp.read() if isinstance(server_response, bytes): server_response = server_response.decode("utf-8") if response is None: local_response.set_response(server_response) else: response.set_response(server_response) else: raise e if response is None: return local_response
[ "def", "send_request", "(", "self", ",", "request", ",", "response", "=", "None", ")", ":", "local_response", "=", "None", "if", "response", "is", "None", ":", "if", "request", ".", "request_type", "==", "\"json\"", ":", "local_response", "=", "ResponseJson"...
Send the request. Sends the request and retrieves the results, formats them and returns them in a dict or a list (when it's a batchresponse). If something goes wrong, raises a SoapFailure or a HTTPError on system-side failures. Note: AuthRequest raises an HTTPError on failed authentications! :param request: The request to send :type request: pythonzimbra.request.Request :param response: A prebuilt response object :type response: pythonzimbra.response.Response :raises: pythonzimbra.exceptions.communication.SoapFailure or urllib2.HTTPError
[ "Send", "the", "request", "." ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/communication.py#L86-L169
train
37,080
Zimbra-Community/python-zimbra
pythonzimbra/tools/auth.py
authenticate
def authenticate(url, account, key, by='name', expires=0, timestamp=None, timeout=None, request_type="xml", admin_auth=False, use_password=False, raise_on_error=False): """ Authenticate to the Zimbra server :param url: URL of Zimbra SOAP service :param account: The account to be authenticated against :param key: The preauth key of the domain of the account or a password (if admin_auth or use_password is True) :param by: If the account is specified as a name, an ID or a ForeignPrincipal :param expires: When the token expires (or 0 for default expiration) :param timestamp: When the token was requested (None for "now") :param timeout: Timeout for the communication with the server. Defaults to the urllib2-default :param request_type: Which type of request to use ("xml" (default) or "json") :param admin_auth: This request should authenticate and generate an admin token. The "key"-parameter therefore holds the admin password (implies use_password) :param use_password: The "key"-parameter holds a password. Do a password- based user authentication. :param raise_on_error: Should I raise an exception when an authentication error occurs or just return None? :return: The authentication token or None :rtype: str or None or unicode """ if timestamp is None: timestamp = int(time.time()) * 1000 pak = "" if not admin_auth: pak = preauth.create_preauth(account, key, by, expires, timestamp) if request_type == 'xml': auth_request = RequestXml() else: auth_request = RequestJson() request_data = { 'account': { 'by': by, '_content': account } } ns = "urn:zimbraAccount" if admin_auth: ns = "urn:zimbraAdmin" request_data['password'] = key elif use_password: request_data['password'] = { "_content": key } else: request_data['preauth'] = { 'timestamp': timestamp, 'expires': expires, '_content': pak } auth_request.add_request( 'AuthRequest', request_data, ns ) server = Communication(url, timeout) if request_type == 'xml': response = ResponseXml() else: response = ResponseJson() server.send_request(auth_request, response) if response.is_fault(): if raise_on_error: raise AuthenticationFailed( "Cannot authenticate user: (%s) %s" % ( response.get_fault_code(), response.get_fault_message() ) ) return None return response.get_response()['AuthResponse']['authToken']
python
def authenticate(url, account, key, by='name', expires=0, timestamp=None, timeout=None, request_type="xml", admin_auth=False, use_password=False, raise_on_error=False): """ Authenticate to the Zimbra server :param url: URL of Zimbra SOAP service :param account: The account to be authenticated against :param key: The preauth key of the domain of the account or a password (if admin_auth or use_password is True) :param by: If the account is specified as a name, an ID or a ForeignPrincipal :param expires: When the token expires (or 0 for default expiration) :param timestamp: When the token was requested (None for "now") :param timeout: Timeout for the communication with the server. Defaults to the urllib2-default :param request_type: Which type of request to use ("xml" (default) or "json") :param admin_auth: This request should authenticate and generate an admin token. The "key"-parameter therefore holds the admin password (implies use_password) :param use_password: The "key"-parameter holds a password. Do a password- based user authentication. :param raise_on_error: Should I raise an exception when an authentication error occurs or just return None? :return: The authentication token or None :rtype: str or None or unicode """ if timestamp is None: timestamp = int(time.time()) * 1000 pak = "" if not admin_auth: pak = preauth.create_preauth(account, key, by, expires, timestamp) if request_type == 'xml': auth_request = RequestXml() else: auth_request = RequestJson() request_data = { 'account': { 'by': by, '_content': account } } ns = "urn:zimbraAccount" if admin_auth: ns = "urn:zimbraAdmin" request_data['password'] = key elif use_password: request_data['password'] = { "_content": key } else: request_data['preauth'] = { 'timestamp': timestamp, 'expires': expires, '_content': pak } auth_request.add_request( 'AuthRequest', request_data, ns ) server = Communication(url, timeout) if request_type == 'xml': response = ResponseXml() else: response = ResponseJson() server.send_request(auth_request, response) if response.is_fault(): if raise_on_error: raise AuthenticationFailed( "Cannot authenticate user: (%s) %s" % ( response.get_fault_code(), response.get_fault_message() ) ) return None return response.get_response()['AuthResponse']['authToken']
[ "def", "authenticate", "(", "url", ",", "account", ",", "key", ",", "by", "=", "'name'", ",", "expires", "=", "0", ",", "timestamp", "=", "None", ",", "timeout", "=", "None", ",", "request_type", "=", "\"xml\"", ",", "admin_auth", "=", "False", ",", ...
Authenticate to the Zimbra server :param url: URL of Zimbra SOAP service :param account: The account to be authenticated against :param key: The preauth key of the domain of the account or a password (if admin_auth or use_password is True) :param by: If the account is specified as a name, an ID or a ForeignPrincipal :param expires: When the token expires (or 0 for default expiration) :param timestamp: When the token was requested (None for "now") :param timeout: Timeout for the communication with the server. Defaults to the urllib2-default :param request_type: Which type of request to use ("xml" (default) or "json") :param admin_auth: This request should authenticate and generate an admin token. The "key"-parameter therefore holds the admin password (implies use_password) :param use_password: The "key"-parameter holds a password. Do a password- based user authentication. :param raise_on_error: Should I raise an exception when an authentication error occurs or just return None? :return: The authentication token or None :rtype: str or None or unicode
[ "Authenticate", "to", "the", "Zimbra", "server" ]
8b839143c64b0507a30a9908ff39066ae4ef5d03
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/tools/auth.py#L15-L119
train
37,081
openfisca/openfisca-survey-manager
openfisca_survey_manager/read_dbf.py
read_dbf
def read_dbf(dbf_path, index = None, cols = False, incl_index = False): """ Read a dbf file as a pandas.DataFrame, optionally selecting the index variable and which columns are to be loaded. __author__ = "Dani Arribas-Bel <darribas@asu.edu> " ... Arguments --------- dbf_path : str Path to the DBF file to be read index : str Name of the column to be used as the index of the DataFrame cols : list List with the names of the columns to be read into the DataFrame. Defaults to False, which reads the whole dbf incl_index : Boolean If True index is included in the DataFrame as a column too. Defaults to False Returns ------- df : DataFrame pandas.DataFrame object created """ db = ps.open(dbf_path) if cols: if incl_index: cols.append(index) vars_to_read = cols else: vars_to_read = db.header data = dict([(var, db.by_col(var)) for var in vars_to_read]) if index: index = db.by_col(index) db.close() return pd.DataFrame(data, index=index) else: db.close() return pd.DataFrame(data)
python
def read_dbf(dbf_path, index = None, cols = False, incl_index = False): """ Read a dbf file as a pandas.DataFrame, optionally selecting the index variable and which columns are to be loaded. __author__ = "Dani Arribas-Bel <darribas@asu.edu> " ... Arguments --------- dbf_path : str Path to the DBF file to be read index : str Name of the column to be used as the index of the DataFrame cols : list List with the names of the columns to be read into the DataFrame. Defaults to False, which reads the whole dbf incl_index : Boolean If True index is included in the DataFrame as a column too. Defaults to False Returns ------- df : DataFrame pandas.DataFrame object created """ db = ps.open(dbf_path) if cols: if incl_index: cols.append(index) vars_to_read = cols else: vars_to_read = db.header data = dict([(var, db.by_col(var)) for var in vars_to_read]) if index: index = db.by_col(index) db.close() return pd.DataFrame(data, index=index) else: db.close() return pd.DataFrame(data)
[ "def", "read_dbf", "(", "dbf_path", ",", "index", "=", "None", ",", "cols", "=", "False", ",", "incl_index", "=", "False", ")", ":", "db", "=", "ps", ".", "open", "(", "dbf_path", ")", "if", "cols", ":", "if", "incl_index", ":", "cols", ".", "appen...
Read a dbf file as a pandas.DataFrame, optionally selecting the index variable and which columns are to be loaded. __author__ = "Dani Arribas-Bel <darribas@asu.edu> " ... Arguments --------- dbf_path : str Path to the DBF file to be read index : str Name of the column to be used as the index of the DataFrame cols : list List with the names of the columns to be read into the DataFrame. Defaults to False, which reads the whole dbf incl_index : Boolean If True index is included in the DataFrame as a column too. Defaults to False Returns ------- df : DataFrame pandas.DataFrame object created
[ "Read", "a", "dbf", "file", "as", "a", "pandas", ".", "DataFrame", "optionally", "selecting", "the", "index", "variable", "and", "which", "columns", "are", "to", "be", "loaded", "." ]
bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/read_dbf.py#L44-L84
train
37,082
Crunch-io/crunch-cube
src/cr/cube/min_base_size_mask.py
MinBaseSizeMask.column_mask
def column_mask(self): """ndarray, True where column margin <= min_base_size, same shape as slice.""" margin = compress_pruned( self._slice.margin( axis=0, weighted=False, include_transforms_for_dims=self._hs_dims, prune=self._prune, ) ) mask = margin < self._size if margin.shape == self._shape: # If margin shape is the same as slice's (such as in a col margin for # MR x CAT), don't broadcast the mask to the array shape, since # they're already the same. return mask # If the row margin is a row vector - broadcast it's mask to the array shape return np.logical_or(np.zeros(self._shape, dtype=bool), mask)
python
def column_mask(self): """ndarray, True where column margin <= min_base_size, same shape as slice.""" margin = compress_pruned( self._slice.margin( axis=0, weighted=False, include_transforms_for_dims=self._hs_dims, prune=self._prune, ) ) mask = margin < self._size if margin.shape == self._shape: # If margin shape is the same as slice's (such as in a col margin for # MR x CAT), don't broadcast the mask to the array shape, since # they're already the same. return mask # If the row margin is a row vector - broadcast it's mask to the array shape return np.logical_or(np.zeros(self._shape, dtype=bool), mask)
[ "def", "column_mask", "(", "self", ")", ":", "margin", "=", "compress_pruned", "(", "self", ".", "_slice", ".", "margin", "(", "axis", "=", "0", ",", "weighted", "=", "False", ",", "include_transforms_for_dims", "=", "self", ".", "_hs_dims", ",", "prune", ...
ndarray, True where column margin <= min_base_size, same shape as slice.
[ "ndarray", "True", "where", "column", "margin", "<", "=", "min_base_size", "same", "shape", "as", "slice", "." ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/min_base_size_mask.py#L28-L47
train
37,083
Crunch-io/crunch-cube
src/cr/cube/min_base_size_mask.py
MinBaseSizeMask.table_mask
def table_mask(self): """ndarray, True where table margin <= min_base_size, same shape as slice.""" margin = compress_pruned( self._slice.margin( axis=None, weighted=False, include_transforms_for_dims=self._hs_dims, prune=self._prune, ) ) mask = margin < self._size if margin.shape == self._shape: return mask if self._slice.dim_types[0] == DT.MR: # If the margin is a column vector - broadcast it's mask to the array shape return np.logical_or(np.zeros(self._shape, dtype=bool), mask[:, None]) return np.logical_or(np.zeros(self._shape, dtype=bool), mask)
python
def table_mask(self): """ndarray, True where table margin <= min_base_size, same shape as slice.""" margin = compress_pruned( self._slice.margin( axis=None, weighted=False, include_transforms_for_dims=self._hs_dims, prune=self._prune, ) ) mask = margin < self._size if margin.shape == self._shape: return mask if self._slice.dim_types[0] == DT.MR: # If the margin is a column vector - broadcast it's mask to the array shape return np.logical_or(np.zeros(self._shape, dtype=bool), mask[:, None]) return np.logical_or(np.zeros(self._shape, dtype=bool), mask)
[ "def", "table_mask", "(", "self", ")", ":", "margin", "=", "compress_pruned", "(", "self", ".", "_slice", ".", "margin", "(", "axis", "=", "None", ",", "weighted", "=", "False", ",", "include_transforms_for_dims", "=", "self", ".", "_hs_dims", ",", "prune"...
ndarray, True where table margin <= min_base_size, same shape as slice.
[ "ndarray", "True", "where", "table", "margin", "<", "=", "min_base_size", "same", "shape", "as", "slice", "." ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/min_base_size_mask.py#L72-L91
train
37,084
Crunch-io/crunch-cube
src/cr/cube/measures/pairwise_significance.py
PairwiseSignificance.values
def values(self): """list of _ColumnPairwiseSignificance tests. Result has as many elements as there are coliumns in the slice. Each significance test contains `p_vals` and `t_stats` significance tests. """ # TODO: Figure out how to intersperse pairwise objects for columns # that represent H&S return [ _ColumnPairwiseSignificance( self._slice, col_idx, self._axis, self._weighted, self._alpha, self._only_larger, self._hs_dims, ) for col_idx in range(self._slice.get_shape(hs_dims=self._hs_dims)[1]) ]
python
def values(self): """list of _ColumnPairwiseSignificance tests. Result has as many elements as there are coliumns in the slice. Each significance test contains `p_vals` and `t_stats` significance tests. """ # TODO: Figure out how to intersperse pairwise objects for columns # that represent H&S return [ _ColumnPairwiseSignificance( self._slice, col_idx, self._axis, self._weighted, self._alpha, self._only_larger, self._hs_dims, ) for col_idx in range(self._slice.get_shape(hs_dims=self._hs_dims)[1]) ]
[ "def", "values", "(", "self", ")", ":", "# TODO: Figure out how to intersperse pairwise objects for columns", "# that represent H&S", "return", "[", "_ColumnPairwiseSignificance", "(", "self", ".", "_slice", ",", "col_idx", ",", "self", ".", "_axis", ",", "self", ".", ...
list of _ColumnPairwiseSignificance tests. Result has as many elements as there are coliumns in the slice. Each significance test contains `p_vals` and `t_stats` significance tests.
[ "list", "of", "_ColumnPairwiseSignificance", "tests", "." ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/pairwise_significance.py#L33-L52
train
37,085
Crunch-io/crunch-cube
src/cr/cube/measures/pairwise_significance.py
PairwiseSignificance.pairwise_indices
def pairwise_indices(self): """ndarray containing tuples of pairwise indices.""" return np.array([sig.pairwise_indices for sig in self.values]).T
python
def pairwise_indices(self): """ndarray containing tuples of pairwise indices.""" return np.array([sig.pairwise_indices for sig in self.values]).T
[ "def", "pairwise_indices", "(", "self", ")", ":", "return", "np", ".", "array", "(", "[", "sig", ".", "pairwise_indices", "for", "sig", "in", "self", ".", "values", "]", ")", ".", "T" ]
ndarray containing tuples of pairwise indices.
[ "ndarray", "containing", "tuples", "of", "pairwise", "indices", "." ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/pairwise_significance.py#L55-L57
train
37,086
Crunch-io/crunch-cube
src/cr/cube/measures/pairwise_significance.py
PairwiseSignificance.summary_pairwise_indices
def summary_pairwise_indices(self): """ndarray containing tuples of pairwise indices for the column summary.""" summary_pairwise_indices = np.empty( self.values[0].t_stats.shape[1], dtype=object ) summary_pairwise_indices[:] = [ sig.summary_pairwise_indices for sig in self.values ] return summary_pairwise_indices
python
def summary_pairwise_indices(self): """ndarray containing tuples of pairwise indices for the column summary.""" summary_pairwise_indices = np.empty( self.values[0].t_stats.shape[1], dtype=object ) summary_pairwise_indices[:] = [ sig.summary_pairwise_indices for sig in self.values ] return summary_pairwise_indices
[ "def", "summary_pairwise_indices", "(", "self", ")", ":", "summary_pairwise_indices", "=", "np", ".", "empty", "(", "self", ".", "values", "[", "0", "]", ".", "t_stats", ".", "shape", "[", "1", "]", ",", "dtype", "=", "object", ")", "summary_pairwise_indic...
ndarray containing tuples of pairwise indices for the column summary.
[ "ndarray", "containing", "tuples", "of", "pairwise", "indices", "for", "the", "column", "summary", "." ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/pairwise_significance.py#L60-L68
train
37,087
openfisca/openfisca-survey-manager
openfisca_survey_manager/calibration.py
Calibration.reset
def reset(self): """ Reset the calibration to it initial state """ simulation = self.survey_scenario.simulation holder = simulation.get_holder(self.weight_name) holder.array = numpy.array(self.initial_weight, dtype = holder.variable.dtype)
python
def reset(self): """ Reset the calibration to it initial state """ simulation = self.survey_scenario.simulation holder = simulation.get_holder(self.weight_name) holder.array = numpy.array(self.initial_weight, dtype = holder.variable.dtype)
[ "def", "reset", "(", "self", ")", ":", "simulation", "=", "self", ".", "survey_scenario", ".", "simulation", "holder", "=", "simulation", ".", "get_holder", "(", "self", ".", "weight_name", ")", "holder", ".", "array", "=", "numpy", ".", "array", "(", "s...
Reset the calibration to it initial state
[ "Reset", "the", "calibration", "to", "it", "initial", "state" ]
bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/calibration.py#L45-L51
train
37,088
openfisca/openfisca-survey-manager
openfisca_survey_manager/calibration.py
Calibration._set_survey_scenario
def _set_survey_scenario(self, survey_scenario): """ Set survey scenario :param survey_scenario: the survey scenario """ self.survey_scenario = survey_scenario # TODO deal with baseline if reform is present if survey_scenario.simulation is None: survey_scenario.simulation = survey_scenario.new_simulation() period = self.period self.filter_by = filter_by = survey_scenario.calculate_variable( variable = self.filter_by_name, period = period) # TODO: shoud not be france specific self.weight_name = weight_name = self.survey_scenario.weight_column_name_by_entity['menage'] self.initial_weight_name = weight_name + "_ini" self.initial_weight = initial_weight = survey_scenario.calculate_variable( variable = weight_name, period = period) self.initial_total_population = sum(initial_weight * filter_by) self.weight = survey_scenario.calculate_variable(variable = weight_name, period = period)
python
def _set_survey_scenario(self, survey_scenario): """ Set survey scenario :param survey_scenario: the survey scenario """ self.survey_scenario = survey_scenario # TODO deal with baseline if reform is present if survey_scenario.simulation is None: survey_scenario.simulation = survey_scenario.new_simulation() period = self.period self.filter_by = filter_by = survey_scenario.calculate_variable( variable = self.filter_by_name, period = period) # TODO: shoud not be france specific self.weight_name = weight_name = self.survey_scenario.weight_column_name_by_entity['menage'] self.initial_weight_name = weight_name + "_ini" self.initial_weight = initial_weight = survey_scenario.calculate_variable( variable = weight_name, period = period) self.initial_total_population = sum(initial_weight * filter_by) self.weight = survey_scenario.calculate_variable(variable = weight_name, period = period)
[ "def", "_set_survey_scenario", "(", "self", ",", "survey_scenario", ")", ":", "self", ".", "survey_scenario", "=", "survey_scenario", "# TODO deal with baseline if reform is present", "if", "survey_scenario", ".", "simulation", "is", "None", ":", "survey_scenario", ".", ...
Set survey scenario :param survey_scenario: the survey scenario
[ "Set", "survey", "scenario" ]
bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/calibration.py#L53-L72
train
37,089
openfisca/openfisca-survey-manager
openfisca_survey_manager/calibration.py
Calibration.set_parameters
def set_parameters(self, parameter, value): """ Set parameters value :param parameter: the parameter to be set :param value: the valeu used to set the parameter """ if parameter == 'lo': self.parameters['lo'] = 1 / value else: self.parameters[parameter] = value
python
def set_parameters(self, parameter, value): """ Set parameters value :param parameter: the parameter to be set :param value: the valeu used to set the parameter """ if parameter == 'lo': self.parameters['lo'] = 1 / value else: self.parameters[parameter] = value
[ "def", "set_parameters", "(", "self", ",", "parameter", ",", "value", ")", ":", "if", "parameter", "==", "'lo'", ":", "self", ".", "parameters", "[", "'lo'", "]", "=", "1", "/", "value", "else", ":", "self", ".", "parameters", "[", "parameter", "]", ...
Set parameters value :param parameter: the parameter to be set :param value: the valeu used to set the parameter
[ "Set", "parameters", "value" ]
bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/calibration.py#L74-L84
train
37,090
openfisca/openfisca-survey-manager
openfisca_survey_manager/calibration.py
Calibration._build_calmar_data
def _build_calmar_data(self): """ Builds the data dictionnary used as calmar input argument """ # Select only filtered entities assert self.initial_weight_name is not None data = pd.DataFrame() data[self.initial_weight_name] = self.initial_weight * self.filter_by for variable in self.margins_by_variable: if variable == 'total_population': continue assert variable in self.survey_scenario.tax_benefit_system.variables period = self.period data[variable] = self.survey_scenario.calculate_variable(variable = variable, period = period) return data
python
def _build_calmar_data(self): """ Builds the data dictionnary used as calmar input argument """ # Select only filtered entities assert self.initial_weight_name is not None data = pd.DataFrame() data[self.initial_weight_name] = self.initial_weight * self.filter_by for variable in self.margins_by_variable: if variable == 'total_population': continue assert variable in self.survey_scenario.tax_benefit_system.variables period = self.period data[variable] = self.survey_scenario.calculate_variable(variable = variable, period = period) return data
[ "def", "_build_calmar_data", "(", "self", ")", ":", "# Select only filtered entities", "assert", "self", ".", "initial_weight_name", "is", "not", "None", "data", "=", "pd", ".", "DataFrame", "(", ")", "data", "[", "self", ".", "initial_weight_name", "]", "=", ...
Builds the data dictionnary used as calmar input argument
[ "Builds", "the", "data", "dictionnary", "used", "as", "calmar", "input", "argument" ]
bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/calibration.py#L131-L146
train
37,091
openfisca/openfisca-survey-manager
openfisca_survey_manager/calibration.py
Calibration._update_weights
def _update_weights(self, margins, parameters = {}): """ Run calmar, stores new weights and returns adjusted margins """ data = self._build_calmar_data() assert self.initial_weight_name is not None parameters['initial_weight'] = self.initial_weight_name val_pondfin, lambdasol, updated_margins = calmar( data, margins, **parameters) # Updating only afetr filtering weights self.weight = val_pondfin * self.filter_by + self.weight * (logical_not(self.filter_by)) return updated_margins
python
def _update_weights(self, margins, parameters = {}): """ Run calmar, stores new weights and returns adjusted margins """ data = self._build_calmar_data() assert self.initial_weight_name is not None parameters['initial_weight'] = self.initial_weight_name val_pondfin, lambdasol, updated_margins = calmar( data, margins, **parameters) # Updating only afetr filtering weights self.weight = val_pondfin * self.filter_by + self.weight * (logical_not(self.filter_by)) return updated_margins
[ "def", "_update_weights", "(", "self", ",", "margins", ",", "parameters", "=", "{", "}", ")", ":", "data", "=", "self", ".", "_build_calmar_data", "(", ")", "assert", "self", ".", "initial_weight_name", "is", "not", "None", "parameters", "[", "'initial_weigh...
Run calmar, stores new weights and returns adjusted margins
[ "Run", "calmar", "stores", "new", "weights", "and", "returns", "adjusted", "margins" ]
bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/calibration.py#L148-L159
train
37,092
openfisca/openfisca-survey-manager
openfisca_survey_manager/calibration.py
Calibration.set_calibrated_weights
def set_calibrated_weights(self): """ Modify the weights to use the calibrated weights """ period = self.period survey_scenario = self.survey_scenario assert survey_scenario.simulation is not None for simulation in [survey_scenario.simulation, survey_scenario.baseline_simulation]: if simulation is None: continue simulation.set_input(self.weight_name, period, self.weight)
python
def set_calibrated_weights(self): """ Modify the weights to use the calibrated weights """ period = self.period survey_scenario = self.survey_scenario assert survey_scenario.simulation is not None for simulation in [survey_scenario.simulation, survey_scenario.baseline_simulation]: if simulation is None: continue simulation.set_input(self.weight_name, period, self.weight)
[ "def", "set_calibrated_weights", "(", "self", ")", ":", "period", "=", "self", ".", "period", "survey_scenario", "=", "self", ".", "survey_scenario", "assert", "survey_scenario", ".", "simulation", "is", "not", "None", "for", "simulation", "in", "[", "survey_sce...
Modify the weights to use the calibrated weights
[ "Modify", "the", "weights", "to", "use", "the", "calibrated", "weights" ]
bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/calibration.py#L178-L188
train
37,093
wooey/clinto
clinto/parsers/argparse_.py
get_parameter_action
def get_parameter_action(action): """ To foster a general schema that can accomodate multiple parsers, the general behavior here is described rather than the specific language of a given parser. For instance, the 'append' action of an argument is collapsing each argument given to a single argument. It also returns a set of actions as well, since presumably some actions can impact multiple parameter options """ actions = set() if isinstance(action, argparse._AppendAction): actions.add(SPECIFY_EVERY_PARAM) return actions
python
def get_parameter_action(action): """ To foster a general schema that can accomodate multiple parsers, the general behavior here is described rather than the specific language of a given parser. For instance, the 'append' action of an argument is collapsing each argument given to a single argument. It also returns a set of actions as well, since presumably some actions can impact multiple parameter options """ actions = set() if isinstance(action, argparse._AppendAction): actions.add(SPECIFY_EVERY_PARAM) return actions
[ "def", "get_parameter_action", "(", "action", ")", ":", "actions", "=", "set", "(", ")", "if", "isinstance", "(", "action", ",", "argparse", ".", "_AppendAction", ")", ":", "actions", ".", "add", "(", "SPECIFY_EVERY_PARAM", ")", "return", "actions" ]
To foster a general schema that can accomodate multiple parsers, the general behavior here is described rather than the specific language of a given parser. For instance, the 'append' action of an argument is collapsing each argument given to a single argument. It also returns a set of actions as well, since presumably some actions can impact multiple parameter options
[ "To", "foster", "a", "general", "schema", "that", "can", "accomodate", "multiple", "parsers", "the", "general", "behavior", "here", "is", "described", "rather", "than", "the", "specific", "language", "of", "a", "given", "parser", ".", "For", "instance", "the",...
f25be36710a391f1dc13214756df3be7cfa26993
https://github.com/wooey/clinto/blob/f25be36710a391f1dc13214756df3be7cfa26993/clinto/parsers/argparse_.py#L45-L55
train
37,094
Crunch-io/crunch-cube
src/cr/cube/distributions/wishart.py
WishartCDF.wishart_pfaffian
def wishart_pfaffian(self): """ndarray of wishart pfaffian CDF, before normalization""" return np.array( [Pfaffian(self, val).value for i, val in np.ndenumerate(self._chisq)] ).reshape(self._chisq.shape)
python
def wishart_pfaffian(self): """ndarray of wishart pfaffian CDF, before normalization""" return np.array( [Pfaffian(self, val).value for i, val in np.ndenumerate(self._chisq)] ).reshape(self._chisq.shape)
[ "def", "wishart_pfaffian", "(", "self", ")", ":", "return", "np", ".", "array", "(", "[", "Pfaffian", "(", "self", ",", "val", ")", ".", "value", "for", "i", ",", "val", "in", "np", ".", "ndenumerate", "(", "self", ".", "_chisq", ")", "]", ")", "...
ndarray of wishart pfaffian CDF, before normalization
[ "ndarray", "of", "wishart", "pfaffian", "CDF", "before", "normalization" ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/distributions/wishart.py#L50-L54
train
37,095
Crunch-io/crunch-cube
src/cr/cube/distributions/wishart.py
WishartCDF.other_ind
def other_ind(self): """last row or column of square A""" return np.full(self.n_min, self.size - 1, dtype=np.int)
python
def other_ind(self): """last row or column of square A""" return np.full(self.n_min, self.size - 1, dtype=np.int)
[ "def", "other_ind", "(", "self", ")", ":", "return", "np", ".", "full", "(", "self", ".", "n_min", ",", "self", ".", "size", "-", "1", ",", "dtype", "=", "np", ".", "int", ")" ]
last row or column of square A
[ "last", "row", "or", "column", "of", "square", "A" ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/distributions/wishart.py#L77-L79
train
37,096
Crunch-io/crunch-cube
src/cr/cube/distributions/wishart.py
WishartCDF.K
def K(self): """Normalizing constant for wishart CDF.""" K1 = np.float_power(pi, 0.5 * self.n_min * self.n_min) K1 /= ( np.float_power(2, 0.5 * self.n_min * self._n_max) * self._mgamma(0.5 * self._n_max, self.n_min) * self._mgamma(0.5 * self.n_min, self.n_min) ) K2 = np.float_power( 2, self.alpha * self.size + 0.5 * self.size * (self.size + 1) ) for i in xrange(self.size): K2 *= gamma(self.alpha + i + 1) return K1 * K2
python
def K(self): """Normalizing constant for wishart CDF.""" K1 = np.float_power(pi, 0.5 * self.n_min * self.n_min) K1 /= ( np.float_power(2, 0.5 * self.n_min * self._n_max) * self._mgamma(0.5 * self._n_max, self.n_min) * self._mgamma(0.5 * self.n_min, self.n_min) ) K2 = np.float_power( 2, self.alpha * self.size + 0.5 * self.size * (self.size + 1) ) for i in xrange(self.size): K2 *= gamma(self.alpha + i + 1) return K1 * K2
[ "def", "K", "(", "self", ")", ":", "K1", "=", "np", ".", "float_power", "(", "pi", ",", "0.5", "*", "self", ".", "n_min", "*", "self", ".", "n_min", ")", "K1", "/=", "(", "np", ".", "float_power", "(", "2", ",", "0.5", "*", "self", ".", "n_mi...
Normalizing constant for wishart CDF.
[ "Normalizing", "constant", "for", "wishart", "CDF", "." ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/distributions/wishart.py#L89-L103
train
37,097
Crunch-io/crunch-cube
src/cr/cube/distributions/wishart.py
Pfaffian.value
def value(self): """return float Cumulative Distribution Function. The return value represents a floating point number of the CDF of the largest eigenvalue of a Wishart(n, p) evaluated at chisq_val. """ wishart = self._wishart_cdf # Prepare variables for integration algorithm A = self.A p = self._gammainc_a g = gamma(wishart.alpha_vec) q_ind = np.arange(2 * wishart.n_min - 2) q_vec = 2 * wishart.alpha + q_ind + 2 q = np.float_power(0.5, q_vec) * gamma(q_vec) * gammainc(q_vec, self._chisq_val) # Perform integration (i.e. calculate Pfaffian CDF) for i in xrange(wishart.n_min): # TODO consider index tricks instead of iteration here b = 0.5 * p[i] * p[i] for j in xrange(i, wishart.n_min - 1): b -= q[i + j] / (g[i] * g[j + 1]) A[j + 1, i] = p[i] * p[j + 1] - 2 * b A[i, j + 1] = -A[j + 1, i] if np.any(np.isnan(A)): return 0 return np.sqrt(det(A))
python
def value(self): """return float Cumulative Distribution Function. The return value represents a floating point number of the CDF of the largest eigenvalue of a Wishart(n, p) evaluated at chisq_val. """ wishart = self._wishart_cdf # Prepare variables for integration algorithm A = self.A p = self._gammainc_a g = gamma(wishart.alpha_vec) q_ind = np.arange(2 * wishart.n_min - 2) q_vec = 2 * wishart.alpha + q_ind + 2 q = np.float_power(0.5, q_vec) * gamma(q_vec) * gammainc(q_vec, self._chisq_val) # Perform integration (i.e. calculate Pfaffian CDF) for i in xrange(wishart.n_min): # TODO consider index tricks instead of iteration here b = 0.5 * p[i] * p[i] for j in xrange(i, wishart.n_min - 1): b -= q[i + j] / (g[i] * g[j + 1]) A[j + 1, i] = p[i] * p[j + 1] - 2 * b A[i, j + 1] = -A[j + 1, i] if np.any(np.isnan(A)): return 0 return np.sqrt(det(A))
[ "def", "value", "(", "self", ")", ":", "wishart", "=", "self", ".", "_wishart_cdf", "# Prepare variables for integration algorithm", "A", "=", "self", ".", "A", "p", "=", "self", ".", "_gammainc_a", "g", "=", "gamma", "(", "wishart", ".", "alpha_vec", ")", ...
return float Cumulative Distribution Function. The return value represents a floating point number of the CDF of the largest eigenvalue of a Wishart(n, p) evaluated at chisq_val.
[ "return", "float", "Cumulative", "Distribution", "Function", "." ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/distributions/wishart.py#L124-L151
train
37,098
Crunch-io/crunch-cube
src/cr/cube/distributions/wishart.py
Pfaffian.A
def A(self): """ndarray - a skew-symmetric matrix for integrating the target distribution""" wishart = self._wishart_cdf base = np.zeros([wishart.size, wishart.size]) if wishart.n_min % 2: # If matrix has odd number of elements, we need to append a # row and a col, in order for the pfaffian algorithm to work base = self._make_size_even(base) return base
python
def A(self): """ndarray - a skew-symmetric matrix for integrating the target distribution""" wishart = self._wishart_cdf base = np.zeros([wishart.size, wishart.size]) if wishart.n_min % 2: # If matrix has odd number of elements, we need to append a # row and a col, in order for the pfaffian algorithm to work base = self._make_size_even(base) return base
[ "def", "A", "(", "self", ")", ":", "wishart", "=", "self", ".", "_wishart_cdf", "base", "=", "np", ".", "zeros", "(", "[", "wishart", ".", "size", ",", "wishart", ".", "size", "]", ")", "if", "wishart", ".", "n_min", "%", "2", ":", "# If matrix has...
ndarray - a skew-symmetric matrix for integrating the target distribution
[ "ndarray", "-", "a", "skew", "-", "symmetric", "matrix", "for", "integrating", "the", "target", "distribution" ]
a837840755690eb14b2ec8e8d93b4104e01c854f
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/distributions/wishart.py#L154-L163
train
37,099