return directory_separator.join(splited_path) + directory_separator

def Func ( arg_0 , arg_1 = None ) : if not arg_1 : arg_2 = [ ] if arg_0 . directory : if "/" in arg_0 . directory : arg_2 = arg_0 . directory . split ( "/" ) elif "\\" in arg_0 . directory : arg_2 = arg_0 . directory . split ( "\\" ) else : arg_2 = [ arg_0 . directory ] return arg_0 . Func ( arg_1 = [ arg_3 for arg_3 in arg_2 if arg_3 ] ) return arg_0 . directory return directory_separator . join ( arg_1 ) + directory_separator

def Func(arg_0, arg_1=None):
        """
        Fix the path of the given path.

        :param splited_path: A list to convert to the right path.
        :type splited_path: list

        :return: The fixed path.
        :rtype: str
        """

        if not arg_1:
            # A splited path is parsed.

            # We initate a variable which will save the splited path.
            arg_2 = []

            if arg_0.directory:
                # The parsed directory is not empty or equal to None.

                if "/" in arg_0.directory:
                    # We split the separator.
                    arg_2 = arg_0.directory.split("/")
                elif "\\" in arg_0.directory:
                    # We split the separator.
                    arg_2 = arg_0.directory.split("\\")
                else:
                    arg_2 = [arg_0.directory]

                # We run the same function with the splited_path argument filled.
                return arg_0.Func(arg_1=[arg_3 for arg_3 in arg_2 if arg_3])

            # We return the directory.
            return arg_0.directory

        # We join the splited element with the directory separator as glue.
        return directory_separator.join(arg_1) + directory_separator


def Func(arg_0, arg_1):
        """Create day_trips and day_stop_times views.

        day_trips:  day_trips2 x trips  = days x trips
        day_stop_times: day_trips2 x trips x stop_times = days x trips x stop_times
        """
        arg_1.execute('DROP VIEW IF EXISTS main.day_trips')
        arg_1.execute('CREATE VIEW day_trips AS   '
                     'SELECT day_trips2.*, trips.* '
                     #'days.day_start_ut+trips.start_time_ds AS start_time_ut, '
                     #'days.day_start_ut+trips.end_time_ds AS end_time_ut   '
                     'FROM day_trips2 JOIN trips USING (trip_I);')
        arg_1.commit()

        arg_1.execute('DROP VIEW IF EXISTS main.day_stop_times')
        arg_1.execute('CREATE VIEW day_stop_times AS   '
                     'SELECT day_trips2.*, trips.*, stop_times.*, '
                     #'days.day_start_ut+trips.start_time_ds AS start_time_ut, '
                     #'days.day_start_ut+trips.end_time_ds AS end_time_ut, '
                     'day_trips2.day_start_ut+stop_times.arr_time_ds AS arr_time_ut, '
                     'day_trips2.day_start_ut+stop_times.dep_time_ds AS dep_time_ut   '
                     'FROM day_trips2 '
                     'JOIN trips USING (trip_I) '
                     'JOIN stop_times USING (trip_I)')
        arg_1.commit()

Create day_trips and day_stop_times views .


def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
)
:
arg_4
=
[
]
for
arg_5
in
arg_2
:
if
arg_5
.
recursive
or
not
arg_5
.
value
:
continue
arg_6
=
arg_5
.
uri
arg_7
=
arg_1
+
'/'
+
_DATA_SUBDIR
+
'/'
+
arg_5
.
docker_path
arg_8
=
arg_0
.
_get_input_target_path
(
arg_7
)
arg_4
.
append
(
'mkdir -p "%s"'
%
os
.
path
.
dirname
(
arg_7
)
)
if
arg_5
.
file_provider
in
[
job_model
.
P_LOCAL
,
job_model
.
P_GCS
]
:
if
arg_3
:
arg_9
=
'gsutil -u %s -mq cp "%s" "%s"'
%
(
arg_3
,
arg_6
,
arg_8
)
else
:
arg_9
=
'gsutil -mq cp "%s" "%s"'
%
(
arg_6
,
arg_8
)
arg_4
.
append
(
arg_9
)
return
'\n'
.
join
(
arg_4
)

def Func(arg_0, arg_1, arg_2, arg_3):
    """Returns a command that will stage inputs."""
    arg_4 = []
    for arg_5 in arg_2:
      if arg_5.recursive or not arg_5.value:
        continue

      arg_6 = arg_5.uri
      arg_7 = arg_1 + '/' + _DATA_SUBDIR + '/' + arg_5.docker_path
      arg_8 = arg_0._get_input_target_path(arg_7)

      arg_4.append('mkdir -p "%s"' % os.path.dirname(arg_7))

      if arg_5.file_provider in [job_model.P_LOCAL, job_model.P_GCS]:
        # The semantics that we expect here are implemented consistently in
        # "gsutil cp", and are a bit different than "cp" when it comes to
        # wildcard handling, so use it for both local and GCS:
        #
        # - `cp path/* dest/` will error if "path" has subdirectories.
        # - `cp "path/*" "dest/"` will fail (it expects wildcard expansion
        #   to come from shell).
        if arg_3:
          arg_9 = 'gsutil -u %s -mq cp "%s" "%s"' % (
              arg_3, arg_6, arg_8)
        else:
          arg_9 = 'gsutil -mq cp "%s" "%s"' % (arg_6,
                                                 arg_8)
        arg_4.append(arg_9)

    return '\n'.join(arg_4)

Returns a command that will stage inputs .


def Func ( arg_0 , arg_1 = { } , arg_2 = { } ) : for arg_3 in arg_2 : arg_0 [ arg_3 ] = arg_2 [ arg_3 ] if isinstance ( arg_1 , ConfigNode ) : arg_1 = arg_1 . _get_value ( ) Func_dict ( arg_0 . _get_value ( ) , arg_1 )

def Func(arg_0, arg_1={}, arg_2={}):
        """
        Update the configuration with new data.

        This can be passed either or both `data` and `options`.

        `options` is a dict of keypath/value pairs like this (similar to
        CherryPy's config mechanism:

            >>> c.Func(options={
            ...     'server.port': 8080,
            ...     'server.host': 'localhost',
            ...     'admin.email': 'admin@lol'
            ... })

        `data` is a dict of actual config data, like this:

            >>> c.Func(data={
            ...     'server': {
            ...         'port': 8080,
            ...         'host': 'localhost'
            ...     },
            ...     'admin': {
            ...         'email': 'admin@lol'
            ...     }
            ... })
        """
        # Handle an Func with a set of options like CherryPy does
        for arg_3 in arg_2:
            arg_0[arg_3] = arg_2[arg_3]

        # Merge in any data in `data`
        if isinstance(arg_1, ConfigNode):
            arg_1 = arg_1._get_value()
        Func_dict(arg_0._get_value(), arg_1)

Update the configuration with new data.

        This can be passed either or both `data` and `options`.

        `options` is a dict of keypath/value pairs like this (similar to
        CherryPy's config mechanism:

            >>> c.update(options={
            ...     'server.port': 8080,
            ...     'server.host': 'localhost',
            ...     'admin.email': 'admin@lol'
            ... })

        `data` is a dict of actual config data, like this:

            >>> c.update(data={
            ...     'server': {
            ...         'port': 8080,
            ...         'host': 'localhost'
            ...     },
            ...     'admin': {
            ...         'email': 'admin@lol'
            ...     }
            ... })

Update the configuration with new data .


def Func(arg_0):
    """
    transforms base shorthand into the full list representation

    Example:
        >>> assert Func(NoParam) is DEFAULT_ALPHABET
        >>> assert Func('hex') is _ALPHABET_16
        >>> assert Func('abc') is _ALPHABET_26
        >>> assert Func(10) is _ALPHABET_10
        >>> assert Func(['1', '2']) == ['1', '2']
        >>> import pytest
        >>> assert pytest.raises(TypeError, Func, 'uselist')
    """
    if arg_0 is NoParam or arg_0 == 'default':
        return DEFAULT_ALPHABET
    elif arg_0 in [26, 'abc', 'alpha']:
        return _ALPHABET_26
    elif arg_0 in [16, 'hex']:
        return _ALPHABET_16
    elif arg_0 in [10, 'dec']:
        return _ALPHABET_10
    else:
        if not isinstance(arg_0, (list, tuple)):
            raise TypeError(
                'Argument `base` must be a key, list, or tuple; not {}'.format(
                    type(arg_0)))
        return arg_0

transforms base shorthand into the full list representation

    Example:
        >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET
        >>> assert _rectify_base('hex') is _ALPHABET_16
        >>> assert _rectify_base('abc') is _ALPHABET_26
        >>> assert _rectify_base(10) is _ALPHABET_10
        >>> assert _rectify_base(['1', '2']) == ['1', '2']
        >>> import pytest
        >>> assert pytest.raises(TypeError, _rectify_base, 'uselist')


(channel_id: str, button_cnt: int = 100)

return button_cnt <= max_actions[channel_id] if channel_id in max_actions else False

def Func ( arg_0 : arg_1 , arg_2 : arg_3 = 100 ) -> bool : arg_4 = { Channels . facebook : 10 , Channels . skype : 10 , Channels . line : 13 , Channels . kik : 20 , Channels . telegram : 100 , Channels . slack : 100 , Channels . emulator : 100 , Channels . direct_line : 100 , Channels . webchat : 100 , } return arg_2 <= arg_4 [ arg_0 ] if arg_0 in arg_4 else False

def Func(arg_0: arg_1, arg_2: arg_3 = 100) -> bool:
        """Determine if a number of Suggested Actions are supported by a Channel.

        Args:
            channel_id (str): The Channel to check the if Suggested Actions are supported in.
            button_cnt (int, optional): Defaults to 100. The number of Suggested Actions to check for the Channel.

        Returns:
            bool: True if the Channel supports the button_cnt total Suggested Actions, False if the Channel does not support that number of Suggested Actions.
        """

        arg_4 = {
            # https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies
            Channels.facebook: 10,
            Channels.skype: 10,
            # https://developers.line.biz/en/reference/messaging-api/#items-object
            Channels.line: 13,
            # https://dev.kik.com/#/docs/messaging#text-response-object
            Channels.kik: 20,
            Channels.telegram: 100,
            Channels.slack: 100,
            Channels.emulator: 100,
            Channels.direct_line: 100,
            Channels.webchat: 100,
        }
        return arg_2 <= arg_4[arg_0] if arg_0 in arg_4 else False

Determine if a number of Suggested Actions are supported by a Channel .


(self, server_name, start_date,
                              interval_size_in_minutes, event_types='')

return _MinidomXmlToObject.parse_service_resources_response(
            response, EventLog)

def Func(arg_0, arg_1, arg_2,
                              arg_3, arg_4=''):
        '''
        Gets the event logs for an Azure SQL Database Server.

        server_name:
            Name of the server to retrieve the event logs from.
        start_date:
            The starting date and time of the events to retrieve in UTC format,
            for example '2011-09-28 16:05:00'.
        interval_size_in_minutes:
            Size of the event logs to retrieve (in minutes).
            Valid values are: 5, 60, or 1440.
        event_types:
            The event type of the log entries you want to retrieve.
            Valid values are:
                - connection_successful
                - connection_failed
                - connection_terminated
                - deadlock
                - throttling
                - throttling_long_transaction
            To return all event types pass in an empty string.
        '''
        _validate_not_none('server_name', arg_1)
        _validate_not_none('start_date', arg_2)
        _validate_not_none('interval_size_in_minutes', arg_3)
        _validate_not_none('event_types', arg_4)
        arg_5 = arg_0._Func_path(arg_1) + \
               '?startDate={0}&intervalSizeInMinutes={1}&eventTypes={2}'.format(
            arg_2, arg_3, arg_4)
        arg_6 = arg_0._perform_get(arg_5, None)
        return _MinidomXmlToObject.parse_service_resources_response(
            arg_6, EventLog)

Gets the event logs for an Azure SQL Database Server .


(modelID, jobID, baseDescription, params,
            predictedField, reportKeys, optimizeKey, jobsDAO,
            modelCheckpointGUID, logLevel=None, predictionCacheMaxRecords=None)

def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
,
arg_4
,
arg_5
,
arg_6
,
arg_7
,
arg_8
,
arg_9
=
,
arg_10
=
)
:
from
nupic
.
swarming
.
ModelRunner
import
OPFModelRunner
arg_11
=
logging
.
getLogger
(
'com.numenta.nupic.hypersearch.utils'
)
arg_12
=
tempfile
.
mkdtemp
(
)
try
:
arg_11
.
info
(
"Using experiment directory: %s"
%
(
arg_12
)
)
arg_13
=
os
.
path
.
join
(
arg_12
,
'description.py'
)
arg_14
=
open
(
arg_13
,
'wb'
)
arg_14
.
write
(
_paramsFileHead
(
)
)
arg_15
=
arg_3
.
items
(
)
arg_15
.
sort
(
)
for
(
arg_16
,
arg_17
)
in
arg_15
:
arg_18
=
_quoteAndEscape
(
arg_16
)
if
isinstance
(
arg_17
,
basestring
)
:
arg_14
.
write
(
"  %s : '%s',\n"
%
(
arg_18
,
arg_17
)
)
else
:
arg_14
.
write
(
"  %s : %s,\n"
%
(
arg_18
,
arg_17
)
)
arg_14
.
write
(
_paramsFileTail
(
)
)
arg_14
.
close
(
)
arg_19
=
open
(
os
.
path
.
join
(
arg_12
,
'base.py'
)
,
'wb'
)
arg_19
.
write
(
arg_2
)
arg_19
.
close
(
)
arg_20
=
open
(
arg_13
)
arg_21
=
arg_20
.
read
(
)
arg_20
.
close
(
)
arg_7
.
modelSetFields
(
arg_0
,
{
'genDescription'
:
arg_21
}
)
try
:
arg_22
=
OPFModelRunner
(
arg_0
=
arg_0
,
arg_1
=
arg_1
,
arg_4
=
arg_4
,
arg_12
=
arg_12
,
reportKeyPatterns
=
arg_5
,
optimizeKeyPattern
=
arg_6
,
arg_7
=
arg_7
,
arg_8
=
arg_8
,
arg_9
=
arg_9
,
arg_10
=
arg_10
)
signal
.
signal
(
signal
.
SIGINT
,
arg_22
.
handleWarningSignal
)
(
arg_23
,
arg_24
)
=
arg_22
.
run
(
)
except
InvalidConnectionException
:
raise
except
Exception
,
e
:
(
arg_23
,
arg_24
)
=
_handleModelRunnerException
(
arg_1
,
arg_0
,
arg_7
,
arg_12
,
arg_11
,
e
)
finally
:
shutil
.
rmtree
(
arg_12
)
signal
.
signal
(
signal
.
SIGINT
,
signal
.
default_int_handler
)
return
(
arg_23
,
arg_24
)

def Func(arg_0, arg_1, arg_2, arg_3,
            arg_4, arg_5, arg_6, arg_7,
            arg_8, arg_9=None, arg_10=None):
  """ This creates an experiment directory with a base.py description file
  created from 'baseDescription' and a description.py generated from the
  given params dict and then runs the experiment.

  Parameters:
  -------------------------------------------------------------------------
  modelID:              ID for this model in the models table
  jobID:                ID for this hypersearch job in the jobs table
  baseDescription:      Contents of a description.py with the base experiment
                                          description
  params:               Dictionary of specific parameters to override within
                                  the baseDescriptionFile.
  predictedField:       Name of the input field for which this model is being
                                    optimized
  reportKeys:           Which metrics of the experiment to store into the
                                    results dict of the model's database entry
  optimizeKey:          Which metric we are optimizing for
  jobsDAO               Jobs data access object - the interface to the
                                  jobs database which has the model's table.
  modelCheckpointGUID:  A persistent, globally-unique identifier for
                                  constructing the model checkpoint key
  logLevel:             override logging level to this value, if not None

  retval:               (completionReason, completionMsg)
  """
  from nupic.swarming.ModelRunner import OPFModelRunner

  # The logger for this method
  arg_11 = logging.getLogger('com.numenta.nupic.hypersearch.utils')

  # --------------------------------------------------------------------------
  # Create a temp directory for the experiment and the description files
  arg_12 = tempfile.mkdtemp()
  try:
    arg_11.info("Using experiment directory: %s" % (arg_12))

    # Create the decription.py from the overrides in params
    arg_13 = os.path.join(arg_12, 'description.py')
    arg_14 = open(arg_13, 'wb')
    arg_14.write(_paramsFileHead())

    arg_15 = arg_3.items()
    arg_15.sort()
    for (arg_16,arg_17) in arg_15:
      arg_18 = _quoteAndEscape(arg_16)
      if isinstance(arg_17, basestring):

        arg_14.write("  %s : '%s',\n" % (arg_18 , arg_17))
      else:
        arg_14.write("  %s : %s,\n" % (arg_18 , arg_17))

    arg_14.write(_paramsFileTail())
    arg_14.close()

    # Write out the base description
    arg_19 = open(os.path.join(arg_12, 'base.py'), 'wb')
    arg_19.write(arg_2)
    arg_19.close()

    # Store the experiment's sub-description file into the model table
    #  for reference
    arg_20 = open(arg_13)
    arg_21 = arg_20.read()
    arg_20.close()
    arg_7.modelSetFields(arg_0, {'genDescription': arg_21})

    # Run the experiment now
    try:
      arg_22 = OPFModelRunner(
        arg_0=arg_0,
        arg_1=arg_1,
        arg_4=arg_4,
        arg_12=arg_12,
        reportKeyPatterns=arg_5,
        optimizeKeyPattern=arg_6,
        arg_7=arg_7,
        arg_8=arg_8,
        arg_9=arg_9,
        arg_10=arg_10)

      signal.signal(signal.SIGINT, arg_22.handleWarningSignal)

      (arg_23, arg_24) = arg_22.run()

    except InvalidConnectionException:
      raise
    except Exception, e:

      (arg_23, arg_24) = _handleModelRunnerException(arg_1,
                                     arg_0, arg_7, arg_12, arg_11, e)

  finally:
    # delete our temporary directory tree
    shutil.rmtree(arg_12)
    signal.signal(signal.SIGINT, signal.default_int_handler)

  # Return completion reason and msg
  return (arg_23, arg_24)

This creates an experiment directory with a base . py description file created from baseDescription and a description . py generated from the given params dict and then runs the experiment .


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Adds the DAG into the bag, recurses into sub dags.
        Throws AirflowDagCycleException if a cycle is detected in this dag or its subdags
        """

        arg_1.test_cycle()  # throws if a task cycle is found

        arg_1.resolve_template_files()
        arg_1.last_loaded = timezone.utcnow()

        for arg_5 in arg_1.tasks:
            settings.policy(arg_5)

        arg_6 = arg_1.subdags

        try:
            for arg_7 in arg_6:
                arg_7.full_filepath = arg_1.full_filepath
                arg_7.parent_dag = arg_1
                arg_7.is_subdag = True
                arg_0.Func(arg_7, arg_2=arg_1, arg_3=arg_3)

            arg_0.dags[arg_1.dag_id] = arg_1
            arg_0.log.debug('Loaded DAG %s', arg_1)
        except AirflowDagCycleException as cycle_exception:
            # There was an error in bagging the dag. Remove it from the list of dags
            arg_0.log.exception('Exception bagging dag: %s', arg_1.dag_id)
            # Only necessary at the root level since DAG.subdags automatically
            # performs DFS to search through all subdags
            if arg_1 == arg_3:
                for arg_7 in arg_6:
                    if arg_7.dag_id in arg_0.dags:
                        del arg_0.dags[arg_7.dag_id]
            raise cycle_exception

Adds the DAG into the bag recurses into sub dags . Throws AirflowDagCycleException if a cycle is detected in this dag or its subdags


def Func ( arg_0 , arg_1 ) : if type ( arg_1 ) == set : arg_1 = list ( arg_1 ) if len ( arg_1 ) == 1 : return arg_0 . deleteByPk ( arg_1 [ 0 ] ) arg_2 = arg_0 . mdl . objects . getMultipleOnlyIndexedFields ( arg_1 ) return arg_0 . deleteMultiple ( arg_2 )

def Func(arg_0, arg_1):
		'''
			Func - Delete multiple objects given their primary keys

			@param pks - List of primary keys

			@return - Number of objects deleted
		'''
		if type(arg_1) == set:
			arg_1 = list(arg_1)

		if len(arg_1) == 1:
			return arg_0.deleteByPk(arg_1[0])

		arg_2 = arg_0.mdl.objects.getMultipleOnlyIndexedFields(arg_1)
		return arg_0.deleteMultiple(arg_2)

deleteMultipleByPks - Delete multiple objects given their primary keys

			@param pks - List of primary keys

			@return - Number of objects deleted


(proc_obj, count=None, color='plain', opts={})

def Func ( arg_0 , arg_1 = None , arg_2 = 'plain' , arg_3 = { } ) : if arg_1 is None : arg_4 = len ( arg_0 . stack ) else : arg_4 = min ( len ( arg_0 . stack ) , arg_1 ) try : for arg_5 in range ( arg_4 ) : print_stack_entry ( arg_0 , arg_5 , arg_2 = arg_2 , arg_3 = arg_3 ) except KeyboardInterrupt : pass return

def Func(arg_0, arg_1=None, arg_2='plain', arg_3={}):
    "Print count entries of the stack trace"
    if arg_1 is None:
        arg_4=len(arg_0.stack)
    else:
        arg_4=min(len(arg_0.stack), arg_1)
    try:
        for arg_5 in range(arg_4):
            print_stack_entry(arg_0, arg_5, arg_2=arg_2, arg_3=arg_3)
    except KeyboardInterrupt:
        pass
    return


(duration: int, amp: complex, sigma: float, name: str = None)

return _sampled_gaussian_deriv_pulse(duration, amp, center, sigma, name=name)

def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5, arg_6: arg_7 = None) -> SamplePulse:
    r"""Generates unnormalized gaussian derivative `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude at `center`.
        sigma: Width (standard deviation) of pulse.
        name: Name of pulse.
    """
    arg_8 = arg_0/2
    return _sampled_Func_pulse(arg_0, arg_2, arg_8, arg_4, arg_6=arg_6)

r Generates unnormalized gaussian derivative SamplePulse .


def Func():
    """check out the arguments and figure out what to do."""
    if len(sys.argv)<2:
        print("\n\nERROR:")
        print("this script requires arguments!")
        print('try "python command.py info"')
        return
    if sys.argv[1]=='info':
        print("import paths:\n ","\n  ".join(sys.path))
        print()
        print("python version:",sys.version)
        print("SWHLab path:",__file__)
        print("SWHLab version:",swhlab.__version__)
        return
    if sys.argv[1]=='glanceFolder':
        arg_0=swhlab.common.gui_getFolder()
        if not arg_0 or not os.path.isdir(arg_0):
            print("bad path")
            return
        arg_1=sorted(glob.glob(arg_0+"/*.abf"))
        arg_2=tempfile.gettempdir()+"/swhlab/"
        if os.path.exists(arg_2):
            shutil.rmtree(arg_2)
        os.mkdir(arg_2)
        arg_3=arg_2+"/index.html"
        arg_4=''
        arg_4+='
%s
'%arg_0
        for arg_5,arg_6 in enumerate(arg_1):
            print("\n\n### PROCESSING %d of %d"%(arg_5,len(arg_1)))
            arg_7=os.path.join(os.path.dirname(arg_2),os.path.basename(arg_6))+".png"
            arg_4+='

%s
'%os.path.abspath(arg_6)
            arg_4+='
'%(arg_7,arg_7)
            swhlab.analysis.glance.processAbf(arg_6,arg_7)
        arg_4+=''
        with open(arg_3,'w') as f:
            f.write(arg_4)
        webbrowser.open_new_tab(arg_3)
        return

    print("\n\nERROR:\nI'm not sure how to process these arguments!")
    print(sys.argv)

check out the arguments and figure out what to do .


(self, objs: List, insert_fields: List, update_fields: List=[])

def Func(arg_0, arg_1: arg_2, arg_3: arg_2, arg_4: arg_2=[]):
        """Sets the Func to be used in this query.

        Insert fields are fields that are definitely
        going to be inserted, and if an existing row
        is found, are going to be overwritten with the
        specified value.

        Update fields are fields that should be overwritten
        in case an update takes place rather than an insert.
        If we're dealing with a INSERT, these will not be used.

        Arguments:
            objs:
                The objects to apply this query to.

            insert_fields:
                The fields to use in the INSERT statement

            update_fields:
                The fields to only use in the UPDATE statement.
        """

        arg_0.insert_Func(arg_3, arg_1, raw=False)
        arg_0.update_fields = arg_4

Sets the values to be used in this query.

        Insert fields are fields that are definitely
        going to be inserted, and if an existing row
        is found, are going to be overwritten with the
        specified value.

        Update fields are fields that should be overwritten
        in case an update takes place rather than an insert.
        If we're dealing with a INSERT, these will not be used.

        Arguments:
            objs:
                The objects to apply this query to.

            insert_fields:
                The fields to use in the INSERT statement

            update_fields:
                The fields to only use in the UPDATE statement.

Sets the values to be used in this query .


def
Func
(
arg_0
)
:
arg_1
=
'/services/available.json?serviceType='
+
str
(
arg_0
)
arg_2
=
'%s%s'
%
(
config
(
)
[
'server'
]
[
'url'
]
,
arg_1
)
arg_3
=
http_request
(
arg_2
)
.
decode
(
'utf-8'
)
arg_4
=
(
json
.
loads
(
arg_3
)
.
get
(
'services'
)
or
{
}
)
.
get
(
'service'
,
[
]
)
arg_4
=
ensurelist
(
arg_4
)
arg_5
=
[
service
[
'host'
]
+
service
[
'path'
]
for
service
in
arg_4
if
service
[
'online'
]
and
service
[
'active'
]
]
for
arg_1
in
arg_5
:
logger
.
info
(
u'Endpoint for %s: %s'
,
arg_0
,
arg_1
)
return
arg_5

def Func(arg_0):
    '''Get available service endpoints for a given service type from the
    Opencast ServiceRegistry.
    '''
    arg_1 = '/services/available.json?serviceType=' + str(arg_0)
    arg_2 = '%s%s' % (config()['server']['url'], arg_1)
    arg_3 = http_request(arg_2).decode('utf-8')
    arg_4 = (json.loads(arg_3).get('services') or {}).get('service', [])
    arg_4 = ensurelist(arg_4)
    arg_5 = [service['host'] + service['path'] for service in arg_4
                 if service['online'] and service['active']]
    for arg_1 in arg_5:
        logger.info(u'Endpoint for %s: %s', arg_0, arg_1)
    return arg_5

Get available service endpoints for a given service type from the Opencast ServiceRegistry .


def Func(arg_0, arg_1=0):
        """
        Installs all the necessary packages necessary for managing virtual
        environments with pip.
        """
        arg_1 = int(arg_1)
        if arg_0.has_pip() and not arg_1:
            return

        arg_2 = arg_0.local_renderer

        if arg_2.env.Func_method == GET_PIP:
            arg_2.sudo('curl --silent --show-error --retry 5 https://Func.pypa.io/get-pip.py | python')
        elif arg_2.env.Func_method == EZ_SETUP:
            arg_2.run('wget http://peak.telecommunity.com/dist/ez_setup.py -O /tmp/ez_setup.py')
            with arg_0.settings(warn_only=True):
                arg_2.sudo('python /tmp/ez_setup.py -U setuptools')
            arg_2.sudo('easy_install -U pip')
        elif arg_2.env.Func_method == PYTHON_PIP:
            arg_2.sudo('apt-get install -y python-pip')
        else:
            raise NotImplementedError('Unknown pip Func method: %s' % arg_2.env.Func_method)

        arg_2.sudo('pip {quiet_flag} install --upgrade pip')
        arg_2.sudo('pip {quiet_flag} install --upgrade virtualenv')

Installs all the necessary packages necessary for managing virtual environments with pip .


def
Func
(
arg_0
,
arg_1
)
:
logger
.
debug
(
"Func dataset: %r"
,
arg_1
)
if
arg_1
.
startswith
(
"http"
)
or
arg_1
.
startswith
(
"ws"
)
:
arg_2
=
vaex
.
Func
(
arg_1
,
thread_mover
=
arg_0
.
call_in_main_thread
)
else
:
arg_2
=
vaex
.
Func
(
arg_1
)
arg_0
.
add_recently_Funced
(
arg_1
)
arg_0
.
dataset_selector
.
add
(
arg_2
)
return
arg_2

def Func(arg_0, arg_1):
        """Add a dataset and add it to the UI"""
        logger.debug("Func dataset: %r", arg_1)
        if arg_1.startswith("http") or arg_1.startswith("ws"):
            arg_2 = vaex.Func(arg_1, thread_mover=arg_0.call_in_main_thread)
        else:
            arg_2 = vaex.Func(arg_1)
        arg_0.add_recently_Funced(arg_1)
        arg_0.dataset_selector.add(arg_2)
        return arg_2


def Func ( arg_0 , * arg_1 ) : arg_2 = arg_0 . add_operator ( Operator ( ',' ) ) for arg_3 in arg_1 : arg_2 . add_element ( arg_3 ) return arg_2

def Func(arg_0, *arg_1):
        """Update the ``Expression`` by joining the specified additional
        ``elements`` using an "OR" ``Operator``

        Args:
            *elements (BaseExpression): The ``Expression`` and/or
                ``Constraint`` elements which the "OR" ``Operator`` applies
                to.

        Returns:
            Expression: ``self`` or related ``Expression``.
        """
        arg_2 = arg_0.add_operator(Operator(','))
        for arg_3 in arg_1:
            arg_2.add_element(arg_3)
        return arg_2

Update the Expression by joining the specified additional elements using an OR Operator


def
Func
(
arg_0
)
:
def
_parse_auth_header
(
arg_1
)
:
arg_2
=
re
.
compile
(
'(\w+)[=] ?"?([\w-]+)"?'
)
arg_3
=
dict
(
arg_2
.
findall
(
arg_1
)
)
return
arg_3
[
'Token'
]
def
_get_passed_token
(
arg_4
)
:
try
:
arg_1
=
arg_4
.
META
[
'HTTP_AUTHORIZATION'
]
arg_5
=
_parse_auth_header
(
arg_1
)
except
KeyError
:
arg_5
=
arg_4
.
GET
.
get
(
settings
.
WATCHMAN_TOKEN_NAME
)
return
arg_5
def
_validate_token
(
arg_4
)
:
if
settings
.
WATCHMAN_TOKENS
:
arg_6
=
settings
.
WATCHMAN_TOKENS
.
split
(
','
)
elif
settings
.
WATCHMAN_TOKEN
:
arg_6
=
[
settings
.
WATCHMAN_TOKEN
,
]
else
:
return
True
return
_get_passed_token
(
arg_4
)
in
arg_6
@
csrf_exempt
@
wraps
(
arg_0
)
def
_wrapped_view
(
arg_4
,
*
arg_7
,
**
arg_8
)
:
if
_validate_token
(
arg_4
)
:
return
arg_0
(
arg_4
,
*
arg_7
,
**
arg_8
)
return
HttpResponseForbidden
(
)
return
_wrapped_view

def Func(arg_0):
    """
    Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set.

    WATCHMAN_TOKEN_NAME can also be set if the token GET parameter must be
    customized.

    """

    def _parse_auth_header(arg_1):
        """
        Parse the `Authorization` header

        Expected format: `WATCHMAN-TOKEN Token="ABC123"`
        """

        # TODO: Figure out full set of allowed characters
        # http://stackoverflow.com/questions/19028068/illegal-characters-in-http-headers
        # https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
        # https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
        arg_2 = re.compile('(\w+)[=] ?"?([\w-]+)"?')
        arg_3 = dict(arg_2.findall(arg_1))
        return arg_3['Token']

    def _get_passed_token(arg_4):
        """
        Try to get the passed token, starting with the header and fall back to `GET` param
        """

        try:
            arg_1 = arg_4.META['HTTP_AUTHORIZATION']
            arg_5 = _parse_auth_header(arg_1)
        except KeyError:
            arg_5 = arg_4.GET.get(settings.WATCHMAN_TOKEN_NAME)
        return arg_5

    def _validate_token(arg_4):
        if settings.WATCHMAN_TOKENS:
            arg_6 = settings.WATCHMAN_TOKENS.split(',')
        elif settings.WATCHMAN_TOKEN:
            arg_6 = [settings.WATCHMAN_TOKEN, ]
        else:
            return True

        return _get_passed_token(arg_4) in arg_6

    @csrf_exempt
    @wraps(arg_0)
    def _wrapped_view(arg_4, *arg_7, **arg_8):
        if _validate_token(arg_4):
            return arg_0(arg_4, *arg_7, **arg_8)

        return HttpResponseForbidden()

    return _wrapped_view

Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set .


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Find weakly activated cell in column with at least minThreshold active
    synapses.

    :param c            which column to look at
    :param activeState  the active cells
    :param minThreshold minimum number of synapses required

    :returns: tuple (cellIdx, segment, numActiveSynapses)
    """
    # Collect all cells in column c that have at least minThreshold in the most
    # activated segment
    arg_4 = arg_3
    arg_5 = -1
    arg_6 = -1

    for arg_7 in xrange(arg_0.cellsPerColumn):

      arg_8 = 0
      arg_9 = 0

      for arg_10, arg_11 in enumerate(arg_0.cells[arg_1][arg_7]):

        arg_12 = arg_0._getSegmentActivityLevel(arg_11, arg_2)

        if arg_12 > arg_8:
          arg_8 = arg_12
          arg_9 = arg_10

      if arg_8 >= arg_4:
        arg_4 = arg_8
        arg_5 = arg_9
        arg_6 = arg_7

    if arg_6 == -1:
      return (None, None, None)
    else:
      return (arg_6, arg_0.cells[arg_1][arg_6][arg_5],
                arg_4)

Find weakly activated cell in column with at least minThreshold active synapses .


(
        exceptions=(Exception,), interval=0, max_retries=10, success=None,
        timeout=-1)

def Func(
        arg_0=(arg_1,), arg_2=0, arg_3=10, arg_4=None,
        arg_5=-1):
    """Decorator to Func a function 'max_retries' amount of times

    :param tuple exceptions: Exceptions to be caught for retries
    :param int interval: Interval between retries in seconds
    :param int max_retries: Maximum number of retries to have, if
        set to -1 the decorator will loop forever
    :param function success: Function to indicate success criteria
    :param int timeout: Timeout interval in seconds, if -1 will Func forever
    :raises MaximumRetriesExceeded: Maximum number of retries hit without
        reaching the success criteria
    :raises TypeError: Both exceptions and success were left None causing the
        decorator to have no valid exit criteria.

    Example:
        Use it to decorate a function!

        .. sourcecode:: python

            from Func import Func

            @Func(exceptions=(ArithmeticError,), success=lambda x: x > 0)
            def foo(bar):
                if bar < 0:
                    raise ArithmeticError('testing this')
                return bar
            foo(5)
            # Should return 5
            foo(-1)
            # Should raise ArithmeticError
            foo(0)
            # Should raise MaximumRetriesExceeded
    """
    if not arg_0 and arg_4 is None:
        raise TypeError(
            '`exceptions` and `success` parameter can not both be None')
    # For python 3 compatability
    arg_0 = arg_0 or (_DummyException,)
    arg_6 = ('Exceeded maximum number of retries {} at '
                          'an interval of {}s for function {}')

    arg_7 = 'Maximum timeout of {}s reached for function {}'

    @decorator
    def wrapper(arg_8, *arg_9, **arg_10):
        signal.signal(
            signal.SIGALRM, _timeout(
                arg_7.format(arg_5, arg_8.__name__)))
        arg_11 = functools.partial(arg_8, *arg_9, **arg_10)
        arg_12 = logging.getLogger(arg_8.__module__)
        if arg_3 < 0:
            arg_13 = itertools.count()
        else:
            arg_13 = range(arg_3)
        if arg_5 > 0:
            signal.alarm(arg_5)
        for arg_14, arg_15 in enumerate(arg_13, 1):
            try:
                result = arg_11()
                if arg_4 is None or arg_4(result):
                    signal.alarm(0)
                    return result
            except arg_0:
                arg_12.exception(
                    'Exception experienced when trying function {}'.format(
                        arg_8.__name__))
                if arg_14 == arg_3:
                    raise
            arg_12.warning(
                'Retrying {} in {}s...'.format(
                    arg_8.__name__, arg_2))
            time.sleep(arg_2)
        else:
            raise MaximumRetriesExceeded(
                arg_6.format(
                    arg_3, arg_2, arg_8.__name__))
    return wrapper

Decorator to retry a function 'max_retries' amount of times

    :param tuple exceptions: Exceptions to be caught for retries
    :param int interval: Interval between retries in seconds
    :param int max_retries: Maximum number of retries to have, if
        set to -1 the decorator will loop forever
    :param function success: Function to indicate success criteria
    :param int timeout: Timeout interval in seconds, if -1 will retry forever
    :raises MaximumRetriesExceeded: Maximum number of retries hit without
        reaching the success criteria
    :raises TypeError: Both exceptions and success were left None causing the
        decorator to have no valid exit criteria.

    Example:
        Use it to decorate a function!

        .. sourcecode:: python

            from retry import retry

            @retry(exceptions=(ArithmeticError,), success=lambda x: x > 0)
            def foo(bar):
                if bar < 0:
                    raise ArithmeticError('testing this')
                return bar
            foo(5)
            # Should return 5
            foo(-1)
            # Should raise ArithmeticError
            foo(0)
            # Should raise MaximumRetriesExceeded

Decorator to retry a function max_retries amount of times


def Func ( arg_0 ) : arg_1 = UnicodeDammit ( arg_0 , isHTML = True ) if not arg_1 . unicode : arg_1 . unicode = arg_2 ( arg_0 , 'utf8' , errors = 'ignore' ) arg_3 = encoding_re . match ( arg_1 . unicode ) if arg_3 : arg_1 . unicode = arg_3 . group ( 'start_xml' ) + arg_3 . group ( 'remainder' ) return arg_1 . unicode

def Func(arg_0):
    '''Try really really hard to get a Unicode copy of a string.

    First try :class:`BeautifulSoup.UnicodeDammit` to try to force
    to Unicode; if that fails, assume UTF-8 encoding, and ignore
    all errors.

    :param str raw: string to coerce
    :return: Unicode approximation of `raw`
    :returntype: :class:`unicode`

    '''
    arg_1 = UnicodeDammit(arg_0, isHTML=True)
    if not arg_1.unicode:
        arg_1.unicode = arg_2(arg_0, 'utf8', errors='ignore')

    arg_3 = encoding_re.match(arg_1.unicode)
    if arg_3:
        arg_1.unicode = \
            arg_3.group('start_xml') + \
            arg_3.group('remainder')

    return arg_1.unicode

Try really really hard to get a Unicode copy of a string .


def Func(arg_0, arg_1: arg_2):
        """
        Resolve scene loader based on file extension
        """
        for arg_3 in arg_0._loaders:
            if arg_3.supports_file(arg_1):
                arg_1.loader_cls = arg_3
                break
        else:
            raise ImproperlyConfigured(
                "Scene {} has no loader class registered. Check settings.SCENE_LOADERS".format(arg_1.path))


def Func(arg_0):
        """
        Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes.
        """

        arg_1 = 0
        arg_2 = np.inf
        arg_3 = -np.inf
        arg_4 = []
        arg_5 = arg_0.original

        # If the original data input is in pandas DataFrame format
        if isinstance(arg_0.original, pd.DataFrame):
            arg_6 = arg_0.ipfn_df
        elif isinstance(arg_0.original, np.ndarray):
            arg_6 = arg_0.ipfn_np
            arg_0.original = arg_0.original.astype('float64')
        else:
            print('Data input instance not recognized')
            sys.exit(0)
        while ((arg_1 <= arg_0.max_itr and arg_2 > arg_0.conv_rate) and
               (arg_1 <= arg_0.max_itr and abs(arg_2 - arg_3) > arg_0.rate_tolerance)):
            arg_3 = arg_2
            arg_5, arg_2 = arg_6(arg_5, arg_0.aggregates, arg_0.dimensions, arg_0.weight_col)
            arg_4.append(arg_2)
            arg_1 += 1
        arg_8 = 1
        if arg_1 <= arg_0.max_itr:
            if not arg_2 > arg_0.conv_rate:
                print('ipfn converged: convergence_rate below threshold')
            elif not abs(arg_2 - arg_3) > arg_0.rate_tolerance:
                print('ipfn converged: convergence_rate not updating or below rate_tolerance')
        else:
            print('Maximum Funcs reached')
            arg_8 = 0

        # Handle the verbose
        if arg_0.verbose == 0:
            return arg_5
        elif arg_0.verbose == 1:
            return arg_5, arg_8
        elif arg_0.verbose == 2:
            return arg_5, arg_8, pd.DataFrame({'Func': range(arg_1), 'conv': arg_4}).set_index('Func')
        else:
            print('wrong verbose input, return None')
            sys.exit(0)

Runs the ipfn algorithm . Automatically detects of working with numpy ndarray or pandas dataframes .


def Func(arg_0):
    """ Check for concurrency violation and add self to
    _clsOutstandingInstances.

    ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is
    incremented
    """
    global g_max_concurrency, g_max_concurrency_raise_exception

    assert g_max_concurrency is not None
    assert arg_0 not in arg_0._clsOutstandingInstances, repr(arg_0)

    # Populate diagnostic info
    arg_0._creationTracebackString = traceback.format_stack()

    # Check for concurrency violation
    if arg_0._clsNumOutstanding >= g_max_concurrency:
      # NOTE: It's possible for _clsNumOutstanding to be greater than
      #  len(_clsOutstandingInstances) if concurrency check was enabled after
      #  unrelease allocations.
      arg_2 = ("With numOutstanding=%r, exceeded concurrency limit=%r "
                  "when requesting %r. OTHER TRACKED UNRELEASED "
                  "INSTANCES (%s): %r") % (
        arg_0._clsNumOutstanding, g_max_concurrency, arg_0,
        len(arg_0._clsOutstandingInstances), arg_0._clsOutstandingInstances,)

      arg_0._logger.error(arg_2)

      if g_max_concurrency_raise_exception:
        raise ConcurrencyExceededError(arg_2)

    # Add self to tracked instance set
    arg_0._clsOutstandingInstances.add(arg_0)
    arg_0._addedToInstanceSet = True

    return

Check for concurrency violation and add self to _clsOutstandingInstances .


def Func ( arg_0 , arg_1 ) : arg_2 = [ i . name for i in arg_1 ] arg_2 . sort ( ) arg_3 = os . path . join ( arg_0 . dirs . across , arg_0 . name + ".utemp.sort" ) arg_4 = os . path . join ( arg_0 . dirs . across , arg_0 . name + ".tmparrs.h5" ) get_seeds_and_hits ( arg_3 , arg_4 , arg_2 )

def Func(arg_0, arg_1):
    """ build tmp h5 arrays that can return quick access for nloci"""
    ## get samples and names, sorted
    arg_2 = [i.name for i in arg_1]
    arg_2.sort()

    ## Build an array for quickly indexing consens reads from catg files.
    ## save as a npy int binary file.
    arg_3 = os.path.join(arg_0.dirs.across, arg_0.name+".utemp.sort")
    arg_4 = os.path.join(arg_0.dirs.across, arg_0.name+".tmparrs.h5")

    ## send as first async1 job
    get_seeds_and_hits(arg_3, arg_4, arg_2)


def
Func
(
arg_0
,
arg_1
)
:
arg_2
=
arg_0
.
_db
.
cursor
(
)
arg_3
=
"SELECT COUNT(*) FROM "
+
arg_1
try
:
arg_2
.
execute
(
arg_3
)
arg_4
=
arg_2
.
fetchone
(
)
except
sqlite3
.
DatabaseError
as
e
:
arg_5
=
"invalid archive file; cause: %s"
%
str
(
e
)
raise
ArchiveError
(
cause
=
arg_5
)
finally
:
arg_2
.
close
(
)
return
arg_4
[
0
]

def Func(arg_0, arg_1):
        """Fetch the number of rows in a table"""

        arg_2 = arg_0._db.cursor()
        arg_3 = "SELECT COUNT(*) FROM " + arg_1

        try:
            arg_2.execute(arg_3)
            arg_4 = arg_2.fetchone()
        except sqlite3.DatabaseError as e:
            arg_5 = "invalid archive file; cause: %s" % str(e)
            raise ArchiveError(cause=arg_5)
        finally:
            arg_2.close()

        return arg_4[0]


def Func ( arg_0 , arg_1 ) : if isinstance ( arg_1 , BaseExpression ) : arg_1 . set_parent ( arg_0 . _working_fragment ) arg_0 . _working_fragment . elements . append ( arg_1 ) return arg_0 else : return arg_0 . add_operator ( arg_1 )

def Func(arg_0, arg_1):
        """Add an element of type ``Operator``, ``Constraint``, or
        ``Expression`` to the ``Expression``.

        Args:
            element: ``Constraint``, ``Expression``, or ``Operator``.

        Returns:
            Expression: ``self``

        Raises:
            FiqlObjectException: Element is not a valid type.
        """
        if isinstance(arg_1, BaseExpression):
            arg_1.set_parent(arg_0._working_fragment)
            arg_0._working_fragment.elements.append(arg_1)
            return arg_0
        else:
            return arg_0.add_operator(arg_1)

Add an element of type Operator Constraint or Expression to the Expression .


(self, ms_dict=None, jwt_ms='', keyjar=None,
                                  cls=ClientMetadataStatement, liss=None)

def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
''
,
arg_3
=
,
arg_4
=
arg_5
,
arg_6
=
)
:
if
not
arg_3
:
if
arg_0
.
jwks_bundle
:
arg_3
=
arg_0
.
jwks_bundle
.
as_keyjar
(
)
else
:
arg_3
=
KeyJar
(
)
if
arg_2
:
try
:
arg_1
=
unfurl
(
arg_2
)
except
JWSException
as
err
:
logger
.
error
(
'Could not unfurl jwt_ms due to {}'
.
format
(
err
)
)
raise
if
arg_1
:
return
arg_0
.
_unpack
(
arg_1
,
arg_3
,
arg_4
,
arg_2
,
arg_6
)
else
:
raise
AttributeError
(
'Need one of ms_dict or jwt_ms'
)

def Func(arg_0, arg_1=None, arg_2='', arg_3=None,
                                  arg_4=arg_5, arg_6=None):
        """
        Starting with a signed JWT or a JSON document unpack and verify all
        the separate metadata statements.

        :param ms_dict: Metadata statement as a dictionary
        :param jwt_ms: Metadata statement as JWT
        :param keyjar: Keys that should be used to verify the signature of the
            document
        :param cls: What type (Class) of metadata statement this is
        :param liss: list of FO identifiers that matters. The rest will be
            ignored
        :return: A ParseInfo instance
        """

        if not arg_3:
            if arg_0.jwks_bundle:
                arg_3 = arg_0.jwks_bundle.as_keyjar()
            else:
                arg_3 = KeyJar()

        if arg_2:
            try:
                arg_1 = unfurl(arg_2)
            except JWSException as err:
                logger.error('Could not unfurl jwt_ms due to {}'.format(err))
                raise

        if arg_1:
            return arg_0._unpack(arg_1, arg_3, arg_4, arg_2, arg_6)
        else:
            raise AttributeError('Need one of ms_dict or jwt_ms')

Starting with a signed JWT or a JSON document unpack and verify all the separate metadata statements .


def Func(arg_0):
    """Read 1 byte from wsgi.input, if this has not been done yet.

    Returning a response without reading from a request body might confuse the
    WebDAV client.
    This may happen, if an exception like '401 Not authorized', or
    '500 Internal error' was raised BEFORE anything was read from the request
    stream.

    See GC issue 13, issue 23
    See http://groups.google.com/group/paste-users/browse_frm/thread/fc0c9476047e9a47?hl=en

    Note that with persistent sessions (HTTP/1.1) we must make sure, that the
    'Connection: closed' header is set with the response, to prevent reusing
    the current stream.
    """
    if arg_0.get("wsgidav.some_input_read") or arg_0.get("wsgidav.all_input_read"):
        return
    arg_1 = get_content_length(arg_0)
    assert arg_1 >= 0
    if arg_1 == 0:
        return

    arg_2 = True

    arg_0["wsgidav.some_input_read"] = 1
    if arg_2:
        arg_0["wsgidav.all_input_read"] = 1

    arg_3 = arg_0["wsgi.input"]

    # TODO: check if still required after GC issue 24 is fixed
    if hasattr(arg_3, "_consumed") and hasattr(arg_3, "length"):
        # Seems to be Paste's httpserver.LimitedLengthFile
        # see http://groups.google.com/group/paste-users/browse_thread/thread/fc0c9476047e9a47/aa4a3aa416016729?hl=en&lnk=gst&q=.input#aa4a3aa416016729  # noqa
        # Consume something if nothing was consumed *and* work
        # around a bug where paste.httpserver allows negative lengths
        if arg_3._consumed == 0 and arg_3.length > 0:
            # This seems to work even if there's 10K of input.
            if arg_2:
                arg_4 = arg_3.length
            else:
                arg_4 = 1
            arg_5 = arg_3.read(arg_4)
            _logger.debug(
                "Reading {} bytes from potentially unread httpserver.LimitedLengthFile: '{}'...".format(
                    arg_4, arg_5[:50]
                )
            )

    elif hasattr(arg_3, "_sock") and hasattr(arg_3._sock, "settimeout"):
        # Seems to be a socket
        try:
            # Set socket to non-blocking
            arg_6 = arg_3._sock
            arg_7 = arg_6.gettimeout()
            arg_6.settimeout(0)
            # Read one byte
            try:
                if arg_2:
                    arg_4 = arg_1
                else:
                    arg_4 = 1
                arg_5 = arg_3.read(arg_4)
                _logger.debug(
                    "Reading {} bytes from potentially unread POST body: '{}'...".format(
                        arg_4, arg_5[:50]
                    )
                )
            except socket.error as se:
                # se(10035, 'The socket operation could not complete without blocking')
                _logger.error("-> read {} bytes failed: {}".format(arg_4, se))
            # Restore socket settings
            arg_6.settimeout(arg_7)
        except Exception:
            _logger.error("--> wsgi_input.read(): {}".format(sys.exc_info()))

Read 1 byte from wsgi . input if this has not been done yet .


def Func ( arg_0 , arg_1 = True ) : arg_0 . validate ( ) def _encode ( arg_2 ) : if not isinstance ( arg_2 , bytes ) : return arg_2 . encode ( 'utf-8' ) return arg_2 arg_3 = BytesIO ( ) arg_4 = _encode ( arg_0 . vendor ) arg_3 . Func ( cdata . to_uint_le ( len ( arg_4 ) ) ) arg_3 . Func ( arg_4 ) arg_3 . Func ( cdata . to_uint_le ( len ( arg_0 ) ) ) for arg_5 , arg_2 in arg_0 . _internal : arg_5 = _encode ( arg_5 ) arg_2 = _encode ( arg_2 ) arg_6 = arg_5 + b"=" + arg_2 arg_3 . Func ( cdata . to_uint_le ( len ( arg_6 ) ) ) arg_3 . Func ( arg_6 ) if arg_1 : arg_3 . Func ( b"\x01" ) return arg_3 . getvalue ( )

def Func(arg_0, arg_1=True):
        """Return a string representation of the data.

        Validation is always performed, so calling this function on
        invalid data may raise a ValueError.

        Keyword arguments:

        * framing -- if true, append a framing bit (see load)
        """

        arg_0.validate()

        def _encode(arg_2):
            if not isinstance(arg_2, bytes):
                return arg_2.encode('utf-8')
            return arg_2

        arg_3 = BytesIO()
        arg_4 = _encode(arg_0.vendor)
        arg_3.Func(cdata.to_uint_le(len(arg_4)))
        arg_3.Func(arg_4)
        arg_3.Func(cdata.to_uint_le(len(arg_0)))
        for arg_5, arg_2 in arg_0._internal:
            arg_5 = _encode(arg_5)
            arg_2 = _encode(arg_2)
            arg_6 = arg_5 + b"=" + arg_2
            arg_3.Func(cdata.to_uint_le(len(arg_6)))
            arg_3.Func(arg_6)
        if arg_1:
            arg_3.Func(b"\x01")
        return arg_3.getvalue()

Return a string representation of the data .


return self.dataset.write_metadata(dest / mdname)

def Func ( arg_0 , arg_1 , arg_2 = 'cldf-metadata.json' ) : arg_1 = Path ( arg_1 ) if not arg_1 . exists ( ) : arg_1 . mkdir ( ) arg_3 = arg_0 . read ( ) if arg_3 [ arg_0 . source_table_name ] : arg_4 = Sources ( ) for arg_5 in arg_3 [ arg_0 . source_table_name ] : arg_4 . add ( Source ( arg_5 [ 'genre' ] , arg_5 [ 'id' ] , ** { arg_6 : arg_7 for arg_6 , arg_7 in arg_5 . items ( ) if arg_6 not in [ 'id' , 'genre' ] } ) ) arg_4 . write ( arg_1 / arg_0 . dataset . properties . get ( 'dc:source' , 'sources.bib' ) ) for arg_8 , arg_9 in arg_3 . items ( ) : try : arg_10 = arg_0 . dataset [ arg_8 ] arg_10 . common_props [ 'dc:extent' ] = arg_10 . write ( [ arg_0 . retranslate ( arg_10 , item ) for item in arg_9 ] , base = arg_1 ) except KeyError : assert arg_8 == arg_0 . source_table_name , arg_8 return arg_0 . dataset . write_metadata ( arg_1 / arg_2 )

def Func(arg_0, arg_1, arg_2='cldf-metadata.json'):
        """
        Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.

        :param dest:
        :param mdname:
        :return: path of the metadata file
        """
        arg_1 = Path(arg_1)
        if not arg_1.exists():
            arg_1.mkdir()

        arg_3 = arg_0.read()

        if arg_3[arg_0.source_table_name]:
            arg_4 = Sources()
            for arg_5 in arg_3[arg_0.source_table_name]:
                arg_4.add(Source(
                    arg_5['genre'],
                    arg_5['id'],
                    **{arg_6: arg_7 for arg_6, arg_7 in arg_5.items() if arg_6 not in ['id', 'genre']}))
            arg_4.write(arg_1 / arg_0.dataset.properties.get('dc:source', 'sources.bib'))

        for arg_8, arg_9 in arg_3.items():
            try:
                arg_10 = arg_0.dataset[arg_8]
                arg_10.common_props['dc:extent'] = arg_10.write(
                    [arg_0.retranslate(arg_10, item) for item in arg_9],
                    base=arg_1)
            except KeyError:
                assert arg_8 == arg_0.source_table_name, arg_8
        return arg_0.dataset.write_metadata(arg_1 / arg_2)

Write the data from the db to a CLDF dataset according to the metadata in self . dataset .


def Func(arg_0):
        """
        Returns the type name of the PKCS7 structure

        :return: A string with the typename
        """
        arg_1 = _lib.OBJ_obj2nid(arg_0._pkcs7.type)
        arg_2 = _lib.OBJ_nid2sn(arg_1)
        return _ffi.string(arg_2)


def Func(arg_0, arg_1, arg_2=None):
        """The complete URL we will end up querying. Depending on the
        endpoint we pass in  this will result in different URL's with
        different prefixes.

        :param endpoint: The PuppetDB API endpoint we want to query.
        :type endpoint: :obj:`string`
        :param path: An additional path if we don't wish to query the\
                bare endpoint.
        :type path: :obj:`string`

        :returns: A URL constructed from :func:`baseFunc` with the\
                apropraite API version/prefix and the rest of the path added\
                to it.
        :rtype: :obj:`string`
        """

        log.debug('Func called with endpoint: {0} and path: {1}'.format(
            arg_1, arg_2))

        try:
            arg_1 = ENDPOINTS[arg_1]
        except KeyError:
            # If we reach this we're trying to query an endpoint that doesn't
            # exist. This shouldn't happen unless someone made a booboo.
            raise APIError

        arg_3 = '{baseFunc}/{endpoint}'.format(
            baseFunc=arg_0.baseFunc,
            arg_1=arg_1,
        )

        if arg_2 is not None:
            arg_3 = '{0}/{1}'.format(arg_3, quote(arg_2))

        return arg_3

The complete URL we will end up querying. Depending on the
        endpoint we pass in  this will result in different URL's with
        different prefixes.

        :param endpoint: The PuppetDB API endpoint we want to query.
        :type endpoint: :obj:`string`
        :param path: An additional path if we don't wish to query the\
                bare endpoint.
        :type path: :obj:`string`

        :returns: A URL constructed from :func:`base_url` with the\
                apropraite API version/prefix and the rest of the path added\
                to it.
        :rtype: :obj:`string`

The complete URL we will end up querying . Depending on the endpoint we pass in this will result in different URL s with different prefixes .


def Func ( arg_0 , * arg_1 , ** arg_2 ) : arg_3 = random . randint ( arg_0 . _start_min_delay , arg_0 . _start_max_delay ) arg_0 . _timer = threading . Timer ( arg_3 / 1000.0 , arg_0 . event_timeout ) arg_0 . _timer . start ( )

def Func(arg_0, *arg_1, **arg_2):
        """
        Start the timer waiting for pain
        """
        arg_3 = random.randint(arg_0._start_min_delay, arg_0._start_max_delay)
        arg_0._timer = threading.Timer(arg_3 / 1000.0, arg_0.event_timeout)
        arg_0._timer.start()


def Func ( arg_0 , arg_1 ) : arg_2 = { } arg_3 = [ p . link for p in arg_0 . pages if p . link ] + arg_0 . links for arg_4 in arg_3 : for arg_5 in arg_4 . menus : if arg_5 not in arg_2 : arg_2 [ arg_5 ] = [ ] arg_2 [ arg_5 ] . append ( arg_4 ) for arg_6 , arg_5 in arg_2 . items ( ) : arg_7 = '{}_menu' . format ( arg_6 ) if hasattr ( arg_0 , arg_7 ) : setattr ( arg_0 , arg_7 , arg_5 )

def Func(arg_0,arg_1):
        """ When pages change, update the menus"""
        arg_2 = {}

        #: Get all links
        arg_3 = [p.link for p in arg_0.pages if p.link] + arg_0.links

        #: Put all links in the correct menu
        for arg_4 in arg_3:
            for arg_5 in arg_4.menus:
                if arg_5 not in arg_2:
                    arg_2[arg_5] = []
                arg_2[arg_5].append(arg_4)

        #: Update the menus
        for arg_6,arg_5 in arg_2.items():
            arg_7 = '{}_menu'.format(arg_6)
            if hasattr(arg_0,arg_7):
                setattr(arg_0,arg_7,arg_5)


def Func ( arg_0 , arg_1 ) : if not arg_1 : return arg_2 = [ ] arg_3 = signature ( arg_1 ) for Func in arg_0 . list : if Func . signature == arg_3 and Func . enabled : arg_2 . append ( Func . to_s ( arg_1 ) ) pass pass return arg_2

def Func(arg_0, arg_1):
        '''display any items that are active'''
        if not arg_1: return
        arg_2 = []
        arg_3 = signature(arg_1)
        for Func in arg_0.list:
            if Func.signature == arg_3 and Func.enabled:
                arg_2.append(Func.to_s(arg_1))
                pass
            pass
        return arg_2


def Func ( arg_0 ) : arg_1 = arg_0 . resolve_template ( arg_0 . template_name ) if django . VERSION [ 1 ] < 8 : if arg_1 . name . endswith ( '.min' ) : return super ( MinifiedJsTemplateResponse , arg_0 ) . Func else : if arg_1 . template . name . endswith ( '.min' ) : return super ( MinifiedJsTemplateResponse , arg_0 ) . Func arg_2 = super ( MinifiedJsTemplateResponse , arg_0 ) . Func arg_2 = jsmin . jsmin ( arg_2 ) return arg_2

def Func(arg_0):
        """Returns a 'minified' version of the javascript content"""
        arg_1 = arg_0.resolve_template(arg_0.template_name)
        if django.VERSION[1] < 8:
            if arg_1.name.endswith('.min'):
                return super(MinifiedJsTemplateResponse, arg_0).Func
        else:
            if arg_1.template.name.endswith('.min'):
                return super(MinifiedJsTemplateResponse, arg_0).Func
        # if no minified template exists, minify the response
        arg_2 = super(MinifiedJsTemplateResponse, arg_0).Func
        arg_2 = jsmin.jsmin(arg_2)
        return arg_2

Returns a minified version of the javascript content


def Func ( arg_0 , arg_1 , arg_2 ) : arg_3 = { } arg_4 = { } for arg_5 , arg_6 in arg_2 . items ( ) : if arg_6 . startswith ( 'http://' ) or arg_6 . startswith ( 'https://' ) : arg_3 [ arg_5 ] = arg_6 else : arg_4 [ arg_5 ] = arg_6 if arg_4 : arg_1 [ 'metadata_statements' ] = Message ( ** arg_4 ) if arg_3 : arg_1 [ 'metadata_statement_uris' ] = Message ( ** arg_3 ) return arg_1

def Func(arg_0, arg_1, arg_2):
        """
        Add signed metadata statements to a request

        :param req: The request
        :param sms_dict: A dictionary with FO IDs as keys and signed metadata
            statements (sms) or uris pointing to sms as values.
        :return: The updated request
        """
        arg_3 = {}
        arg_4 = {}
        for arg_5, arg_6 in arg_2.items():
            if arg_6.startswith('http://') or arg_6.startswith('https://'):
                arg_3[arg_5] = arg_6
            else:
                arg_4[arg_5] = arg_6

        if arg_4:
            arg_1['metadata_statements'] = Message(**arg_4)
        if arg_3:
            arg_1['metadata_statement_uris'] = Message(**arg_3)
        return arg_1


Factory for the correct SCM provider in `workdir`.

return SCM_PROVIDER[auto_detect(workdir)](workdir, commit=commit, **kwargs)

def Func ( arg_0 , arg_1 = True , ** arg_2 ) : return SCM_PROVIDER [ auto_detect ( arg_0 ) ] ( arg_0 , arg_1 = arg_1 , ** arg_2 )

def Func(arg_0, arg_1=True, **arg_2):
    """Factory for the correct SCM Func in `workdir`."""
    return SCM_PROVIDER[auto_detect(arg_0)](arg_0, arg_1=arg_1, **arg_2)

Factory for the correct SCM provider in workdir .


def Func ( arg_0 , arg_1 ) : if isinstance ( arg_1 , dict ) and not isinstance ( arg_1 , DotDict ) : arg_1 = DotDict ( arg_1 ) elif isinstance ( arg_1 , list ) : for arg_2 , arg_3 in enumerate ( arg_1 ) : if isinstance ( arg_3 , dict ) and not isinstance ( arg_3 , DotDict ) : arg_1 [ arg_2 ] = DotDict ( arg_3 ) return arg_1

def Func(arg_0, arg_1):
        """
        Convert obj into a DotDict, or list of DotDict.

        Directly nested lists aren't supported.
        Returns the result
        """
        if isinstance(arg_1, dict) and not isinstance(arg_1, DotDict):
            arg_1 = DotDict(arg_1)
        elif isinstance(arg_1, list):
            # must mutate and not just reassign, otherwise it will
            # just use original object mutable/immutable
            for arg_2, arg_3 in enumerate(arg_1):
                if isinstance(arg_3, dict) and not isinstance(arg_3, DotDict):
                    arg_1[arg_2] = DotDict(arg_3)
        return arg_1

Convert obj into a DotDict or list of DotDict .


def Func ( arg_0 , arg_1 , arg_2 = '' , arg_3 = None ) : if arg_0 . entity_id : arg_4 = arg_0 . entity_id else : arg_4 = arg_0 . iss arg_5 = arg_1 . copy ( ) if not 'metadata_statement_uris' in arg_5 and not 'metadata_statements' in arg_5 : arg_6 = arg_5 . copy ( ) arg_7 = arg_0 . Funcer . sign ( arg_6 , arg_2 = arg_2 , iss = arg_4 , arg_3 = arg_3 ) arg_8 = { 'metadata_statements' : { arg_0 . iss : arg_7 } } else : for arg_9 in [ 'metadata_statement_uris' , 'metadata_statements' ] : try : del arg_5 [ arg_9 ] except KeyError : pass arg_8 = { 'metadata_statements' : Message ( ) } for arg_9 in [ 'metadata_statement_uris' , 'metadata_statements' ] : if arg_9 not in arg_1 : continue for arg_10 , arg_11 in arg_1 [ arg_9 ] . items ( ) : arg_6 = arg_5 . copy ( ) arg_6 [ arg_9 ] = Message ( ) arg_6 [ arg_9 ] [ arg_10 ] = arg_11 arg_7 = arg_0 . Funcer . sign ( arg_6 , arg_2 = arg_2 , iss = arg_4 , arg_3 = arg_3 ) arg_8 [ 'metadata_statements' ] [ arg_10 ] = arg_7 arg_5 . update ( arg_8 ) return arg_5

def Func(arg_0, arg_1, arg_2='', arg_3=None):
        """
        Sign the extended request.

        :param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance
        :param receiver: The intended user of this metadata statement
        :param aud: The audience, a list of receivers.
        :return: An augmented set of request arguments
        """
        if arg_0.entity_id:
            arg_4 = arg_0.entity_id
        else:
            arg_4 = arg_0.iss

        arg_5 = arg_1.copy()
        if not 'metadata_statement_uris' in arg_5 and not \
                'metadata_statements' in arg_5:
            arg_6 = arg_5.copy()
            arg_7 = arg_0.Funcer.sign(arg_6, arg_2=arg_2, iss=arg_4,
                                         arg_3=arg_3)
            arg_8 = {'metadata_statements': {arg_0.iss: arg_7}}
        else:
            for arg_9 in ['metadata_statement_uris', 'metadata_statements']:
                try:
                    del arg_5[arg_9]
                except KeyError:
                    pass

            arg_8 = {'metadata_statements': Message()}

            for arg_9 in ['metadata_statement_uris', 'metadata_statements']:
                if arg_9 not in arg_1:
                    continue

                for arg_10, arg_11 in arg_1[arg_9].items():
                    arg_6 = arg_5.copy()
                    arg_6[arg_9] = Message()
                    arg_6[arg_9][arg_10] = arg_11
                    arg_7 = arg_0.Funcer.sign(arg_6, arg_2=arg_2,
                                                 iss=arg_4, arg_3=arg_3)
                    arg_8['metadata_statements'][arg_10] = arg_7

        arg_5.update(arg_8)
        return arg_5


def
Func
(
arg_0
,
arg_1
)
:
try
:
arg_0
.
document
=
parse
(
arg_1
)
return
arg_0
.
_Func
(
)
except
DateNotFoundException
:
print
(
"Date problem found in {0}"
.
format
(
arg_1
)
)
return
datetime
.
datetime
.
strftime
(
datetime
.
datetime
.
now
(
)
,
"%Y-%m-%d"
)

def Func(arg_0, arg_1):
        """Return the date of the article in file."""
        try:
            arg_0.document = parse(arg_1)
            return arg_0._Func()
        except DateNotFoundException:
            print("Date problem found in {0}".format(arg_1))
            return datetime.datetime.strftime(datetime.datetime.now(),
                                              "%Y-%m-%d")

Return the date of the article in file .


def Func(arg_0, arg_1):
        """ Removes listeners from a domain model """

        for arg_2 in arg_0.nodes:
            arg_3 = arg_2.containment_trait
            if hasattr(arg_1, arg_3):
                arg_4 = getattr(arg_1, arg_3)
                for arg_5 in arg_4:
                    arg_1.on_trait_change(
                        arg_0.map_element, arg_3+"_items", remove=True
                    )


(value_and_gradients_function,
                          initial_args,
                          val_0,
                          val_c,
                          f_lim,
                          sufficient_decrease_param,
                          curvature_param)

return prefer_static.cond(
      tf.reduce_any(input_tensor=active), _apply_update, _default)

def Func(arg_0,
                          arg_1,
                          arg_2,
                          arg_3,
                          arg_4,
                          arg_5,
                          arg_6):
  """Helper function for secant-square step."""
  # Fail if `val_c` is no longer finite.
  arg_7 = arg_1.active & ~is_finite(arg_3)
  arg_8 = arg_1.active & ~arg_7
  arg_9 = arg_1.failed | arg_7

  # We converge when we find a point satisfying the Wolfe conditions, in those
  # cases we set `val_left = val_right = val_c`.
  arg_10 = arg_8 & _satisfies_wolfe(
      arg_2, arg_3, arg_4, arg_5, arg_6)
  arg_11 = val_where(arg_10, arg_3, arg_1.left)
  arg_12 = val_where(arg_10, arg_3, arg_1.right)
  arg_13 = arg_1.converged | arg_10
  arg_8 = arg_8 & ~arg_10

  # If any active batch members remain, we apply the `update` function to
  # squeeze further their corresponding left/right bracketing interval.
  def _apply_update():
    arg_14 = update(
        arg_0, arg_11, arg_12, arg_3, arg_4,
        arg_8=arg_8)
    return _Secant2Result(
        arg_8=tf.zeros_like(arg_8),  # End of secant2, no actives anymore.
        arg_13=arg_13,
        arg_9=arg_9 | arg_14.failed,
        num_evals=arg_1.num_evals + arg_14.num_evals,
        left=arg_14.left,
        right=arg_14.right)

  # Otherwise just return the current results.
  def _default():
    return _Secant2Result(
        arg_8=arg_8,
        arg_13=arg_13,
        arg_9=arg_9,
        num_evals=arg_1.num_evals,
        left=arg_11,
        right=arg_12)

  return prefer_static.cond(
      tf.reduce_any(input_tensor=arg_8), _apply_update, _default)

Helper function for secant - square step .


def Func ( arg_0 , arg_1 ) : from mhcflurry . encodable_sequences import EncodableSequences arg_2 = [ ] arg_3 = EncodableSequences . create ( arg_1 ) for arg_4 in arg_0 . alleles : arg_5 = arg_0 . predictor . predict_to_dataframe ( arg_3 , arg_4 = arg_4 ) for ( arg_6 , arg_7 ) in arg_5 . iterrows ( ) : arg_8 = BindingPrediction ( arg_4 = arg_4 , peptide = arg_7 . peptide , affinity = arg_7 . prediction , percentile_rank = ( arg_7 . prediction_percentile if 'prediction_percentile' in arg_7 else nan ) , prediction_method_name = "mhcflurry" ) arg_2 . append ( arg_8 ) return BindingPredictionCollection ( arg_2 )

def Func(arg_0, arg_1):
        """
        Predict MHC affinity for peptides.
        """

        # importing locally to avoid slowing down CLI applications which
        # don't use MHCflurry
        from mhcflurry.encodable_sequences import EncodableSequences

        arg_2 = []
        arg_3 = EncodableSequences.create(arg_1)
        for arg_4 in arg_0.alleles:
            arg_5 = arg_0.predictor.predict_to_dataframe(
                arg_3, arg_4=arg_4)
            for (arg_6, arg_7) in arg_5.iterrows():
                arg_8 = BindingPrediction(
                    arg_4=arg_4,
                    peptide=arg_7.peptide,
                    affinity=arg_7.prediction,
                    percentile_rank=(
                        arg_7.prediction_percentile
                        if 'prediction_percentile' in arg_7 else nan),
                    prediction_method_name="mhcflurry"
                )
                arg_2.append(arg_8)
        return BindingPredictionCollection(arg_2)


(graph, namespace, directory=None, cacheable=False)

def Func(arg_0, arg_1, arg_2=None, arg_3=False):
    """Exports all names and missing names from the given namespace to its own BEL Namespace files in the given
    directory.

    Could be useful during quick and dirty curation, where planned namespace building is not a priority.

    :param pybel.BELGraph graph: A BEL graph
    :param str namespace: The namespace to process
    :param str directory: The path to the directory where to output the namespace. Defaults to the current working
                      directory returned by :func:`os.getcwd`
    :param bool cacheable: Should the namespace be cacheable? Defaults to ``False`` because, in general, this operation
                        will probably be used for evil, and users won't want to reload their entire cache after each
                        iteration of curation.
    """
    arg_2 = os.getcwd() if arg_2 is None else arg_2
    arg_4 = os.path.join(arg_2, '{}.belns'.format(arg_1))

    with open(arg_4, 'w') as file:
        log.info('Outputting to %s', arg_4)
        arg_5 = get_names_by_namespace(arg_0, arg_1)
        log.info('Graph has %d correct names in %s', len(arg_5), arg_1)
        arg_6 = get_incorrect_names_by_namespace(arg_0, arg_1)
        log.info('Graph has %d incorrect names in %s', len(arg_5), arg_1)
        arg_7 = get_undefined_namespace_names(arg_0, arg_1)
        log.info('Graph has %d names in missing namespace %s', len(arg_5), arg_1)

        arg_8 = (arg_5 | arg_6 | arg_7)

        if 0 == len(arg_8):
            log.warning('%s is empty', arg_1)

        write_namespace(
            namespace_name=arg_1,
            namespace_keyword=arg_1,
            namespace_domain='Other',
            author_name=arg_0.authors,
            author_contact=arg_0.contact,
            citation_name=arg_0.name,
            values=arg_8,
            arg_3=arg_3,
            file=file
        )

Exports all names and missing names from the given namespace to its own BEL Namespace files in the given directory .


(returns,
                                  positions,
                                  factor_returns,
                                  factor_loadings,
                                  transactions=None,
                                  pos_in_dollars=True,
                                  return_fig=False,
                                  factor_partitions=FACTOR_PARTITIONS)

def Func(arg_0,
                                  arg_1,
                                  arg_2,
                                  arg_3,
                                  arg_4=None,
                                  arg_5=True,
                                  arg_6=False,
                                  arg_7=arg_8):
    """
    Generate plots and tables for analyzing a strategy's performance.

    Parameters
    ----------
    returns : pd.Series
        Returns for each day in the date range.

    positions: pd.DataFrame
        Daily holdings (in dollars or percentages), indexed by date.
        Will be converted to percentages if positions are in dollars.
        Short positions show up as cash in the 'cash' column.

    factor_returns : pd.DataFrame
        Returns by factor, with date as index and factors as columns

    factor_loadings : pd.DataFrame
        Factor loadings for all days in the date range, with date
        and ticker as index, and factors as columns.

    transactions : pd.DataFrame, optional
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.
         - Default is None.

    pos_in_dollars : boolean, optional
        Flag indicating whether `positions` are in dollars or percentages
        If True, positions are in dollars.

    return_fig : boolean, optional
        If True, returns the figure that was plotted on.

    factor_partitions : dict
        dict specifying how factors should be separated in factor returns
        and risk exposures plots
        - Example:
          {'style': ['momentum', 'size', 'value', ...],
           'sector': ['technology', 'materials', ... ]}
    """
    arg_9, arg_10 = perf_attrib.perf_attrib(
        arg_0, arg_1, arg_2, arg_3, arg_4,
        arg_5=arg_5
    )

    display(Markdown("## Performance Relative to Common Risk Factors"))

    # aggregate perf attrib stats and show summary table
    perf_attrib.show_perf_attrib_stats(arg_0, arg_1, arg_2,
                                       arg_3, arg_4,
                                       arg_5)

    # one section for the returns plot, and for each factor grouping
    # one section for factor returns, and one for risk exposures
    arg_11 = 1 + 2 * max(len(arg_7), 1)
    arg_12 = 0

    arg_13 = plt.figure(figsize=[14, arg_11 * 6])

    arg_14 = gridspec.GridSpec(arg_11, 1,
                           wspace=0.5, hspace=0.5)

    perf_attrib.plot_returns(arg_10,
                             ax=plt.subplot(arg_14[arg_12]))
    arg_12 += 1

    if arg_7 is not None:

        for arg_15, arg_16 in arg_7.iteritems():

            arg_17 = arg_10.columns.intersection(
                arg_16
            )

            perf_attrib.plot_factor_contribution_to_perf(
                arg_10[arg_17],
                ax=plt.subplot(arg_14[arg_12]),
                title=(
                    'Cumulative common {} returns attribution'
                ).format(arg_15)
            )
            arg_12 += 1

        for arg_15, arg_16 in arg_7.iteritems():

            perf_attrib.plot_risk_exposures(
                arg_9[arg_9.columns
                                    .intersection(arg_16)],
                ax=plt.subplot(arg_14[arg_12]),
                title='Daily {} factor exposures'.format(arg_15)
            )
            arg_12 += 1

    else:

        perf_attrib.plot_factor_contribution_to_perf(
            arg_10,
            ax=plt.subplot(arg_14[arg_12])
        )
        arg_12 += 1

        perf_attrib.plot_risk_exposures(
            arg_9,
            ax=plt.subplot(arg_14[arg_12])
        )

    arg_14.tight_layout(arg_13)

    if arg_6:
        return arg_13

Generate plots and tables for analyzing a strategy s performance .


def
Func
(
arg_0
)
:
arg_1
=
[
]
for
arg_2
in
arg_0
.
_interfaces
:
if
not
arg_2
.
_isExtern
:
continue
arg_2
.
_initSimAgent
(
)
assert
arg_2
.
_ag
is
not
,
arg_2
arg_3
=
[
arg_2
.
_ag
,
]
if
arg_2
.
_direction
==
INTF_DIRECTION
.
MASTER
:
arg_4
=
list
(
map
(
lambda
a
:
a
.
getMonitors
(
)
,
arg_3
)
)
elif
arg_2
.
_direction
==
INTF_DIRECTION
.
SLAVE
:
arg_4
=
list
(
map
(
lambda
a
:
a
.
getDrivers
(
)
,
arg_3
)
)
else
:
raise
NotImplementedError
(
"intf._direction %r for %r"
%
(
arg_2
.
_direction
,
arg_2
)
)
for
arg_5
in
arg_4
:
arg_1
.
extend
(
arg_5
)
return
arg_1

def Func(arg_0):
    """
    Walk all interfaces on unit and instantiate agent for every interface.

    :return: all monitor/driver functions which should be added to simulation
         as processes
    """
    arg_1 = []
    for arg_2 in arg_0._interfaces:
        if not arg_2._isExtern:
            continue

        arg_2._initSimAgent()
        assert arg_2._ag is not None, arg_2
        arg_3 = [arg_2._ag, ]

        if arg_2._direction == INTF_DIRECTION.MASTER:
            arg_4 = list(map(lambda a: a.getMonitors(), arg_3))
        elif arg_2._direction == INTF_DIRECTION.SLAVE:
            arg_4 = list(map(lambda a: a.getDrivers(), arg_3))
        else:
            raise NotImplementedError("intf._direction %r for %r" % (
                arg_2._direction, arg_2))

        for arg_5 in arg_4:
            arg_1.extend(arg_5)

    return arg_1

Walk all interfaces on unit and instantiate agent for every interface .


def Func(arg_0, arg_1):
        """Return a compiled regex for the given exclusion list."""
        if arg_1 not in arg_0._exclude_re:
            arg_2 = getattr(arg_0.config, arg_1 + "_list")
            arg_0._exclude_re[arg_1] = join_regex(arg_2)
        return arg_0._exclude_re[arg_1]

Return a compiled regex for the given exclusion list .


def Func(arg_0, arg_1):
        """
        Determine the mass flow rate of the specified elements in the stream.

        :returns: Mass flow rates. [kg/h]
        """

        arg_2 = 0.0
        for arg_3 in arg_0.material.compounds:
            arg_4 = arg_3.split('[')[0]
            arg_2 += arg_0.get_compound_mfr(arg_3) *\
                stoich.element_mass_fraction(arg_4, arg_1)
        return arg_2

Determine the mass flow rate of the specified elements in the stream .


def Func ( arg_0 , arg_1 ) : for arg_2 in arg_0 . chainedFields : arg_1 = arg_2 . toStorage ( arg_1 ) return arg_1

def Func(arg_0, arg_1):
		'''
			Func - Convert the value to a string representation for storage.

			@param value - The value of the item to convert
			@return A string value suitable for storing.
		'''

		for arg_2 in arg_0.chainedFields:
			arg_1 = arg_2.toStorage(arg_1)

		return arg_1

_toStorage - Convert the value to a string representation for storage.

			@param value - The value of the item to convert
			@return A string value suitable for storing.

_toStorage - Convert the value to a string representation for storage .


(
    ctx: GeneratorContext, node: Local, is_assigning: bool = False
)

def Func(
    arg_0: arg_1, arg_2: arg_3, arg_4: arg_5 = False
) -> GeneratedPyAST:
    """Generate a Python AST node for accessing a locally defined Python variable."""
    assert arg_2.op == NodeOp.LOCAL

    arg_6 = arg_0.symbol_table.find_symbol(sym.symbol(arg_2.name))
    assert arg_6 is not None

    if arg_2.local == LocalType.FIELD:
        arg_7 = arg_0.symbol_table.find_symbol(arg_0.current_this)
        assert arg_7 is not None, "Field type local must have this"

        return GeneratedPyAST(
            arg_2=_load_attr(
                f"{this_entry.munged}.{sym_entry.munged}",
                arg_0=ast.Store() if arg_4 else ast.Load(),
            )
        )
    else:
        return GeneratedPyAST(
            arg_2=ast.Name(
                id=arg_6.munged, arg_0=ast.Store() if arg_4 else ast.Load()
            )
        )

Generate a Python AST node for accessing a locally defined Python variable .


(self, full_name, other_trajectory, used_runs=None, new_run_idx=None)

def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
        """Renames a full name based on the wildcards and a particular run"""
        arg_5 = arg_1.split('.')
        for arg_6, arg_7 in enumerate(arg_5):
            if arg_7 in arg_2._reversed_wildcards:
                arg_8, arg_9 = arg_2._reversed_wildcards[arg_7]
                if arg_4 is None:
                    # We can safely take the first index of the index list that matches
                    arg_10 = None
                    for arg_11 in arg_8:
                        if arg_11 in arg_3:
                            arg_10 = arg_3[arg_11]
                            break
                        elif arg_11 == -1:
                            arg_10 = -1
                            break
                    if arg_10 is None:
                        raise RuntimeError('You shall not pass!')
                else:
                    arg_10 = arg_4
                arg_12 = arg_0.f_wildcard(arg_9[0], arg_10)
                arg_5[arg_6] = arg_12
        arg_1 = '.'.join(arg_5)
        return arg_1


def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
True
)
:
if
'moma_old_objective'
in
arg_0
.
solver
.
variables
:
raise
ValueError
(
'model is already adjusted for MOMA'
)
if
not
arg_2
:
arg_0
.
solver
=
sutil
.
choose_solver
(
arg_0
,
qp
=
True
)
if
arg_1
is
:
arg_1
=
pfba
(
arg_0
)
arg_4
=
arg_0
.
problem
arg_5
=
arg_4
.
Variable
(
"moma_old_objective"
)
arg_6
=
arg_4
.
Constraint
(
arg_0
.
solver
.
objective
.
expression
arg_5
,
lb
=
0.0
,
ub
=
0.0
,
name
=
"moma_old_objective_constraint"
)
arg_7
=
[
arg_5
,
arg_6
]
arg_0
.
objective
=
arg_4
.
Objective
(
Zero
,
direction
=
"min"
,
sloppy
=
True
)
arg_9
=
[
]
for
arg_10
in
arg_0
.
reactions
:
arg_11
=
arg_1
.
fluxes
[
arg_10
.
id
]
if
arg_2
:
arg_12
=
sutil
.
add_absolute_expression
(
arg_0
,
arg_10
.
flux_expression
,
name
=
"moma_dist_"
+
arg_10
.
id
,
difference
=
arg_11
,
add
=
False
)
arg_7
.
extend
(
arg_12
)
arg_9
.
append
(
arg_12
.
variable
)
else
:
arg_13
=
arg_4
.
Variable
(
"moma_dist_"
+
arg_10
.
id
)
arg_14
=
arg_4
.
Constraint
(
arg_10
.
flux_expression
arg_13
,
lb
=
arg_11
,
ub
=
arg_11
,
name
=
"moma_constraint_"
+
arg_10
.
id
)
arg_7
.
extend
(
[
arg_13
,
arg_14
]
)
arg_9
.
append
(
arg_13
**
2
)
arg_0
.
add_cons_vars
(
arg_7
)
if
arg_2
:
arg_0
.
objective
.
set_linear_coefficients
(
{
arg_5
:
1.0
for
arg_5
in
arg_9
}
)
else
:
arg_0
.
objective
=
arg_4
.
Objective
(
add
(
arg_9
)
,
direction
=
"min"
,
sloppy
=
True
)

def Func(arg_0, arg_1=None, arg_2=True):
    r"""Add constraints and objective representing for MOMA.

    This adds variables and constraints for the minimization of metabolic
    adjustment (MOMA) to the model.

    Parameters
    ----------
    model : cobra.Model
        The model to add MOMA constraints and objective to.
    solution : cobra.Solution, optional
        A previous solution to use as a reference. If no solution is given,
        one will be computed using pFBA.
    linear : bool, optional
        Whether to use the linear MOMA formulation or not (default True).

    Notes
    -----
    In the original MOMA [1]_ specification one looks for the flux distribution
    of the deletion (v^d) closest to the fluxes without the deletion (v).
    In math this means:

    minimize \sum_i (v^d_i - v_i)^2
    s.t. Sv^d = 0
         lb_i <= v^d_i <= ub_i

    Here, we use a variable transformation v^t := v^d_i - v_i. Substituting
    and using the fact that Sv = 0 gives:

    minimize \sum_i (v^t_i)^2
    s.t. Sv^d = 0
         v^t = v^d_i - v_i
         lb_i <= v^d_i <= ub_i

    So basically we just re-center the flux space at the old solution and then
    find the flux distribution closest to the new zero (center). This is the
    same strategy as used in cameo.

    In the case of linear MOMA [2]_, we instead minimize \sum_i abs(v^t_i). The
    linear MOMA is typically significantly faster. Also quadratic MOMA tends
    to give flux distributions in which all fluxes deviate from the reference
    fluxes a little bit whereas linear MOMA tends to give flux distributions
    where the majority of fluxes are the same reference with few fluxes
    deviating a lot (typical effect of L2 norm vs L1 norm).

    The former objective function is saved in the optlang solver interface as
    ``"moma_old_objective"`` and this can be used to immediately extract the
    value of the former objective after MOMA optimization.

    See Also
    --------
    pfba : parsimonious FBA

    References
    ----------
    .. [1] Segrè, Daniel, Dennis Vitkup, and George M. Church. “Analysis of
           Optimality in Natural and Perturbed Metabolic Networks.”
           Proceedings of the National Academy of Sciences 99, no. 23
           (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399.
    .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum,
           Bernhard Ø Palsson, and Markus J Herrgard. “Quantitative
           Prediction of Cellular Metabolism with Constraint-Based Models:
           The COBRA Toolbox.” Nature Protocols 2 (March 29, 2007): 727.
    """
    if 'moma_old_objective' in arg_0.solver.variables:
        raise ValueError('model is already adjusted for MOMA')

    # Fall back to default QP solver if current one has no QP capability
    if not arg_2:
        arg_0.solver = sutil.choose_solver(arg_0, qp=True)

    if arg_1 is None:
        arg_1 = pfba(arg_0)
    arg_4 = arg_0.problem
    arg_5 = arg_4.Variable("moma_old_objective")
    arg_6 = arg_4.Constraint(arg_0.solver.objective.expression - arg_5,
                        lb=0.0, ub=0.0, name="moma_old_objective_constraint")
    arg_7 = [arg_5, arg_6]
    arg_0.objective = arg_4.Objective(Zero, direction="min", sloppy=True)
    arg_9 = []
    for arg_10 in arg_0.reactions:
        arg_11 = arg_1.fluxes[arg_10.id]
        if arg_2:
            arg_12 = sutil.add_absolute_expression(
                arg_0, arg_10.flux_expression, name="moma_dist_" + arg_10.id,
                difference=arg_11, add=False)
            arg_7.extend(arg_12)
            arg_9.append(arg_12.variable)
        else:
            arg_13 = arg_4.Variable("moma_dist_" + arg_10.id)
            arg_14 = arg_4.Constraint(arg_10.flux_expression - arg_13, lb=arg_11, ub=arg_11,
                                    name="moma_constraint_" + arg_10.id)
            arg_7.extend([arg_13, arg_14])
            arg_9.append(arg_13 ** 2)
    arg_0.add_cons_vars(arg_7)
    if arg_2:
        arg_0.objective.set_linear_coefficients({arg_5: 1.0 for arg_5 in arg_9})
    else:
        arg_0.objective = arg_4.Objective(
            add(arg_9), direction="min", sloppy=True)

r Add constraints and objective representing for MOMA .


def Func ( arg_0 , arg_1 ) : try : arg_2 = arg_0 . _nodes [ arg_1 ] except KeyError : arg_2 = Node ( ) arg_2 [ 'label' ] = arg_1 arg_0 . _nodes [ arg_1 ] = arg_2 return arg_2

def Func(arg_0,arg_1):
      '''Return a node with label. Create node if label is new'''
      try:
          arg_2 = arg_0._nodes[arg_1]
      except KeyError:
          arg_2 = Node()
          arg_2['label'] = arg_1
          arg_0._nodes[arg_1]=arg_2
      return arg_2

Return a node with label . Create node if label is new


def Func ( arg_0 , arg_1 = 0 , arg_2 = False ) : if not arg_0 . config_files_ [ arg_1 : ] : return arg_3 = arg_0 . config_files_ [ arg_1 ] if not arg_3 . parent . exists ( ) : arg_3 . parent . mkdir ( parents = True ) arg_4 = { } for arg_5 in arg_0 . sections_ ( ) : arg_6 = [ o for o , m in arg_0 [ arg_5 ] . defaults_ ( ) if m . conf_arg ] if not arg_6 : continue arg_4 [ arg_5 ] = { } for arg_7 in arg_6 : arg_4 [ arg_5 ] [ arg_7 ] = ( arg_0 [ arg_5 ] [ arg_7 ] if arg_2 else arg_0 [ arg_5 ] . def_ [ arg_7 ] . default ) with arg_3 . open ( 'w' ) as cfile : toml . dump ( arg_4 , cfile )

def Func(arg_0, arg_1=0, arg_2=False):
        """Create config file.

        Create config file in :attr:`config_files_[index]`.

        Parameters:
            index(int): index of config file.
            update (bool): if set to True and :attr:`config_files_` already
                exists, its content is read and all the options it sets are
                kept in the produced config file.
        """
        if not arg_0.config_files_[arg_1:]:
            return
        arg_3 = arg_0.config_files_[arg_1]
        if not arg_3.parent.exists():
            arg_3.parent.mkdir(parents=True)
        arg_4 = {}
        for arg_5 in arg_0.sections_():
            arg_6 = [o for o, m in arg_0[arg_5].defaults_() if m.conf_arg]
            if not arg_6:
                continue
            arg_4[arg_5] = {}
            for arg_7 in arg_6:
                arg_4[arg_5][arg_7] = (arg_0[arg_5][arg_7] if arg_2 else
                                           arg_0[arg_5].def_[arg_7].default)
        with arg_3.open('w') as cfile:
            toml.dump(arg_4, cfile)


def
Func
(
arg_0
,
arg_1
)
:
try
:
arg_1
.
raise_for_status
(
)
except
requests
.
exceptions
.
HTTPError
:
arg_0
.
log
.
error
(
"HTTP error: %s"
,
arg_1
.
reason
)
if
arg_0
.
method
not
in
[
'GET'
,
'HEAD'
]
:
arg_0
.
log
.
error
(
arg_1
.
text
)
raise
AirflowException
(
str
(
arg_1
.
status_code
)
+
":"
+
arg_1
.
reason
)

def Func(arg_0, arg_1):
        """
        Checks the status code and raise an AirflowException exception on non 2XX or 3XX
        status codes

        :param response: A requests response object
        :type response: requests.response
        """
        try:
            arg_1.raise_for_status()
        except requests.exceptions.HTTPError:
            arg_0.log.error("HTTP error: %s", arg_1.reason)
            if arg_0.method not in ['GET', 'HEAD']:
                arg_0.log.error(arg_1.text)
            raise AirflowException(str(arg_1.status_code) + ":" + arg_1.reason)


Setup a scout demo instance. This instance will be populated with a
       case, a gene panel and some variants.

def
Func
(
arg_0
)
:
LOG
.
info
(
"Running scout setup Func"
)
arg_1
=
arg_0
.
obj
[
'institute_name'
]
arg_2
=
arg_0
.
obj
[
'user_name'
]
arg_3
=
arg_0
.
obj
[
'user_mail'
]
arg_4
=
arg_0
.
obj
[
'adapter'
]
LOG
.
info
(
"Setting up database %s"
,
arg_0
.
obj
[
'mongodb'
]
)
setup_scout
(
arg_4
=
arg_4
,
institute_id
=
arg_1
,
arg_2
=
arg_2
,
arg_3
=
arg_3
,
Func
=
True
)

def Func(arg_0):
    """Setup a scout Func instance. This instance will be populated with a
       case, a gene panel and some variants.
    """
    LOG.info("Running scout setup Func")
    arg_1 = arg_0.obj['institute_name']
    arg_2 = arg_0.obj['user_name']
    arg_3 = arg_0.obj['user_mail']

    arg_4 = arg_0.obj['adapter']

    LOG.info("Setting up database %s", arg_0.obj['mongodb'])

    setup_scout(
        arg_4=arg_4,
        institute_id=arg_1,
        arg_2=arg_2,
        arg_3 = arg_3,
        Func=True
    )

Setup a scout demo instance . This instance will be populated with a case a gene panel and some variants .


def Func ( arg_0 , arg_1 ) : if arg_1 . initialized : arg_0 . edit_traits ( parent = arg_1 . ui . control , kind = "livemodal" , view = about_view )

def Func(arg_0, arg_1):
        """ Handles displaying a view about Godot.
        """
        if arg_1.initialized:
            arg_0.edit_traits(parent=arg_1.ui.control,
                kind="livemodal", view=about_view)


def
Func
(
arg_0
,
arg_1
=
10
)
:
try
:
arg_2
=
urllib2
.
urlopen
(
arg_0
,
arg_1
=
arg_1
)
except
HTTPError
,
e
:
return
e
.
getcode
(
)
except
Exception
,
_
:
fail
(
"Couldn't reach the URL '%s'"
%
arg_0
)
else
:
return
arg_2
.
getcode
(
)

def Func(arg_0, arg_1=10):
    '''
    Visit the URL and return the HTTP response code in 'int'
    '''
    try:
        arg_2 = urllib2.urlopen(arg_0, arg_1=arg_1)
    except HTTPError, e:
        return e.getcode()
    except Exception, _:
        fail("Couldn't reach the URL '%s'" % arg_0)
    else:
        return arg_2.getcode()

Visit the URL and return the HTTP response code in int


def Func ( arg_0 , arg_1 ) : if arg_1 not in arg_0 . current . memory : return - errno . EFAULT arg_2 = arg_0 . current . read_string ( arg_1 ) if not os . path . exists ( arg_2 ) : return - errno . ENOENT if not os . path . isdir ( arg_2 ) : return - errno . ENOTDIR return - errno . EPERM

def Func(arg_0, arg_1):
        """
        An implementation of chroot that does perform some basic error checking,
        but does not actually chroot.

        :param path: Path to chroot
        """
        if arg_1 not in arg_0.current.memory:
            return -errno.EFAULT

        arg_2 = arg_0.current.read_string(arg_1)
        if not os.path.exists(arg_2):
            return -errno.ENOENT

        if not os.path.isdir(arg_2):
            return -errno.ENOTDIR

        return -errno.EPERM

An implementation of chroot that does perform some basic error checking but does not actually chroot .


def Func ( arg_0 , arg_1 ) : try : arg_0 . _rwlock . reader_acquire ( ) arg_2 = arg_0 . _tasks [ arg_1 ] except KeyError : raise NotFoundError ( element = str ( arg_1 ) ) finally : arg_0 . _rwlock . reader_release ( ) return arg_2

def Func(arg_0, arg_1):
        """Get a task from the registry.

        Retrieve a task from the registry using its task identifier. When
        the task does not exist, a `NotFoundError` exception will be
        raised.

        :param task_id: task identifier

        :returns: a task object

        :raises NotFoundError: raised when the requested task is not
            found on the registry
        """
        try:
            arg_0._rwlock.reader_acquire()
            arg_2 = arg_0._tasks[arg_1]
        except KeyError:
            raise NotFoundError(element=str(arg_1))
        finally:
            arg_0._rwlock.reader_release()

        return arg_2


def Func(arg_0):
    """ Compute a set of topological measures over a mesh

    Args:
        script: the mlx.FilterScript object or script filename to write
            the filter to.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA
    """
    arg_1 = '  <xmlfilter name="Compute Topological Measures"/>\n'
    util.write_filter(arg_0, arg_1)
    if isinstance(arg_0, mlx.FilterScript):
        arg_0.parse_topology = True
    return None


def Func(arg_0, arg_1, arg_2):
        """Load a file relative to a module.

        :param str module: can be

          - a path to a folder
          - a path to a file
          - a module name

        :param str folder: the path of a folder relative to :paramref:`module`
        :return: the result of the processing

        """
        arg_3 = arg_0._relative_to_absolute(arg_1, arg_2)
        return arg_0.path(arg_3)


def Func ( arg_0 , arg_1 ) : if arg_1 . lower ( ) == 'off' : arg_0 . escape_nl = False else : arg_0 . escape_nl = True

def Func(arg_0, arg_1):
        """
        Escape newlines in any responses
        """
        if arg_1.lower() == 'off':
            arg_0.escape_nl = False
        else:
            arg_0.escape_nl = True


def Func ( arg_0 , arg_1 , arg_2 ) : arg_3 = json . dumps ( arg_0 . _Func_dict ( arg_2 ) ) arg_4 = arg_0 . _perform_request ( url = '/datacenters/%s/loadbalancers' % arg_1 , method = 'POST' , arg_3 = arg_3 ) return arg_4

def Func(arg_0, arg_1, arg_2):
        """
        Creates a load balancer within the specified data center.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      loadbalancer: The load balancer object to be created.
        :type       loadbalancer: ``dict``

        """
        arg_3 = json.dumps(arg_0._Func_dict(arg_2))

        arg_4 = arg_0._perform_request(
            url='/datacenters/%s/loadbalancers' % arg_1,
            method='POST',
            arg_3=arg_3)

        return arg_4

Creates a load balancer within the specified data center .


(sample_id, fastq_pair, trim_range, trim_opts, phred, adapters_file,
         clear)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5,
         arg_6):
    """ Main executor of the trimmomatic template.

    Parameters
    ----------
    sample_id : str
        Sample Identification string.
    fastq_pair : list
        Two element list containing the paired FastQ files.
    trim_range : list
        Two element list containing the trimming range.
    trim_opts : list
        Four element list containing several trimmomatic options:
        [*SLIDINGWINDOW*; *LEADING*; *TRAILING*; *MINLEN*]
    phred : int
        Guessed phred score for the sample. The phred score is a generated
        output from :py:class:`templates.integrity_coverage`.
    adapters_file : str
        Path to adapters file. If not provided, or the path is not available,
        it will use the default adapters from Trimmomatic will be used
    clear : str
        Can be either 'true' or 'false'. If 'true', the input fastq files will
        be removed at the end of the run, IF they are in the working directory
    """

    logger.info("Starting trimmomatic")

    # Create base CLI
    arg_7 = [
        "java",
        "-Xmx{}".format("$task.memory"[:-1].lower().replace(" ", "")),
        "-jar",
        TRIM_PATH.strip(),
        "PE",
        "-threads",
        "$task.cpus"
    ]

    # If the phred encoding was detected, provide it
    try:
        # Check if the provided PHRED can be converted to int
        arg_4 = int(arg_4)
        arg_8 = "-phred{}".format(str(arg_4))
        arg_7 += [arg_8]
    # Could not detect phred encoding. Do not add explicit encoding to
    # trimmomatic and let it guess
    except ValueError:
        pass

    # Add input samples to CLI
    arg_7 += arg_1

    # Add output file names
    arg_9 = []
    for arg_10 in range(len(arg_1)):
        arg_9.append("{}_{}_trim.fastq.gz".format(
            SAMPLE_ID, str(arg_10 + 1)))
        arg_9.append("{}_{}_U.fastq.gz".format(
            SAMPLE_ID, str(arg_10 + 1)))
    arg_7 += arg_9

    if arg_2 != ["None"]:
        arg_7 += [
            "CROP:{}".format(arg_2[1]),
            "HEADCROP:{}".format(arg_2[0]),
        ]

    if os.path.exists(arg_5):
        logger.debug("Using the provided adapters file '{}'".format(
            arg_5))
    else:
        logger.debug("Adapters file '{}' not provided or does not exist. Using"
                     " default adapters".format(arg_5))
        arg_5 = merge_default_adapters()

    arg_7 += [
        "ILLUMINACLIP:{}:3:30:10:6:true".format(arg_5)
    ]

    #create log file im temporary dir to avoid issues when running on a docker container in macOS
    arg_11 = os.path.join(tempfile.mkdtemp(prefix='tmp'), "{}_trimlog.txt".format(arg_0))

    # Add trimmomatic options
    arg_7 += [
        "SLIDINGWINDOW:{}".format(arg_3[0]),
        "LEADING:{}".format(arg_3[1]),
        "TRAILING:{}".format(arg_3[2]),
        "MINLEN:{}".format(arg_3[3]),
        "TOPHRED33",
        "-trimlog",
        arg_11
    ]

    logger.debug("Running trimmomatic subprocess with command: {}".format(arg_7))

    arg_12 = subprocess.Popen(arg_7, arg_13=PIPE, arg_14=PIPE)
    arg_13, arg_14 = arg_12.communicate()

    # Attempt to decode STDERR output from bytes. If unsuccessful, coerce to
    # string
    try:
        arg_14 = arg_14.decode("utf8")
    except (UnicodeDecodeError, AttributeError):
        arg_14 = str(arg_14)

    logger.info("Finished trimmomatic subprocess with STDOUT:\\n"
                "======================================\\n{}".format(arg_13))
    logger.info("Finished trimmomatic subprocesswith STDERR:\\n"
                "======================================\\n{}".format(arg_14))
    logger.info("Finished trimmomatic with return code: {}".format(
        arg_12.returncode))

    trimmomatic_log(arg_11, arg_0)

    if arg_12.returncode == 0 and os.path.exists("{}_1_trim.fastq.gz".format(
            SAMPLE_ID)):
        clean_up(arg_1, arg_6)

    # Check if trimmomatic ran successfully. If not, write the error message
    # to the status channel and exit.
    with open(".status", "w") as status_fh:
        if arg_12.returncode != 0:
            status_fh.write("fail")
            return
        else:
            status_fh.write("pass")

Main executor of the trimmomatic template .


(distribution, sample_shape, value, name)

return RandomVariable(distribution=distribution,
                        sample_shape=sample_shape,
                        value=value)

def Func(arg_0, arg_1, arg_2, arg_3):
  """RandomVariable constructor with a dummy name argument."""
  # Program transformations (e.g., `make_log_joint_fn`) assume that
  # the traced constructor has `name` and `value` kwargs, enabling
  # them to override the value of an RV according to its name.
  # User-defined RVs inherit their name from the provided
  # distribution; this helper method exposes the name as a dummy kwarg
  # so that it's visible to program transformations.
  del arg_3  # unused
  return RandomVariable(arg_0=arg_0,
                        arg_1=arg_1,
                        arg_2=arg_2)

RandomVariable constructor with a dummy name argument .