text:
import datetime
import json
import six

from mixpanel_query import exceptions
from mixpanel_query.connection import Connection
from mixpanel_query.utils import _totext
from mixpanel_query.auth import SignatureAuth

class MixpanelQueryClient(object):
    """
    Connects to the `Mixpanel Data Export API`
    and provides an interface to query data based on the project
    specified with your api credentials.

    Full API Docs: https://mixpanel.com/docs/api-documentation/data-export-api
    """
    ENDPOINT = 'http://mixpanel.com/api'
    VERSION = '2.0'

    UNIT_MINUTE = 'minute'
    UNIT_HOUR = 'hour'
    UNIT_DAY = 'day'
    UNIT_WEEK = 'week'
    UNIT_MONTH = 'month'
    VALID_UNITS = (UNIT_MINUTE, UNIT_HOUR, UNIT_DAY, UNIT_WEEK, UNIT_MONTH)

    FORMAT_JSON = 'json'
    FORMAT_CSV = 'csv'
    VALID_RESPONSE_FORMATS = (FORMAT_JSON, FORMAT_CSV)

    DATA_TYPE_GENERAL = 'general'
    DATA_TYPE_AVERAGE = 'average'
    DATA_TYPE_UNIQUE = 'unique'
    VALID_DATA_TYPES = (DATA_TYPE_GENERAL, DATA_TYPE_AVERAGE, DATA_TYPE_UNIQUE)

    def __init__(self, api_key, api_secret, timeout=None, auth_class=SignatureAuth):
        self.api_key = _totext(api_key)
        self.api_secret = _totext(api_secret)
        self.timeout = timeout
        self.connection = Connection(self)
        self.auth = auth_class(self)

    # Annotation methods ##############
    def annotations_list(self, start_date, end_date, response_format=FORMAT_JSON):
        """
        List the annotations for the given date range.

        Args:
            `start_date`: [str] The beginning of the date range to get annotations for in yyyy-mm-dd
                                format. This date is inclusive.
                          [sample]: "2014-04-01"
            `end_date`: [str] The end of the date range to get annotations for in yyyy-mm-dd format.
                              This date is inclusive.
                        [sample]: "2014-04-01"
            `response_format`: [string (optional)]: The data return format.
                               [sample]: "json" or "csv"

        Response format:
        {
            'annotations': [
                {'date': '2014-05-23 00:00:00', 'project_id': 23880, 'id': 148, 'description': 'Launched v2.0 of product'},
                {'date': '2014-05-29 00:00:00', 'project_id': 23880, 'id': 150, 'description': 'Streamlined registration process'}
            ],
            'error': false
        }
        """
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')

        return self.connection.request(
            'annotations',
            {
                'from_date': start_date,
                'to_date': end_date,
            },
            response_format=response_format
        )

    def annotation_create(self, date, description, response_format=FORMAT_JSON):
        """
        Create a new annotation at the specified time.

        Args:
            `date`: [str] The time in yyyy-mm-hh HH:MM:SS when you want to create the annotation at.
                    [sample]: "2014-04-01 02:12:44"
            `description`: [str] The annotation description.
                           [sample]: "Something happened on this date."
            `response_format`: [string (optional)]: The data return format.
                               [sample]: "json" or "csv"

        Response format:
            {
                'error': false
            }
        """
        date_obj = self._validate_date(date)
        return self.connection.request(
            'annotations/create',
            {
                'date': date_obj.strftime('%Y-%m-%d %H:%M:%S'),
                'description': description,
            },
            response_format=response_format
        )

    def annotation_update(self, annotation_id, date, description, response_format=FORMAT_JSON):
        """
        Update an existing annotation with a new description.

        Args:
            `annotation_id`: [int] The id of the annotation you wish to update.
                             [sample]: 1
            `date`: [str] The time in yyyy-mm-hh HH:MM:SS when you want to create the annotation at.
                    [sample]: "2014-04-01 02:12:44"
            `description`: [str] The annotation description.
                           [sample]: "Something happened on this date."
            `response_format`: [string (optional)]: The data return format.
                               [sample]: "json" or "csv"

        Response format:
            {
                'error': false
            }
        """
        date_obj = self._validate_date(date)
        return self.connection.request(
            'annotations/update',
            {
                'id': annotation_id,
                'date': date_obj.strftime('%Y-%m-%d %H:%M:%S'),
                'description': description,
            },
            response_format=response_format
        )

    def annotation_delete(self, annotation_id, response_format=FORMAT_JSON):
        """
        Delete an existing annotation.

        Args:
            `annotation_id`: [int] The id of the annotation you wish to delete.
                             [sample]: 1
            `response_format`: [string (optional)]: The data return format.
                               [sample]: "json" or "csv"

        Response format:
            {
                'error': false
            }
        """
        return self.connection.request(
            'annotations/delete',
            {
                'id': annotation_id,
            },
            response_format=response_format
        )

    # Event methods ###################
    def get_events(self, event_names, unit, interval, data_type=DATA_TYPE_UNIQUE, response_format=FORMAT_JSON):
        """
        Get unique, total, or average data for a set of events over the last N days,
        weeks, or months.

        Args:
            - See `get_unique_events()` docstring.
        Reponse format:
            - See `get_unique_events()` docstring.
        """
        self._validate_unit(unit)
        self._validate_response_format(response_format)
        self._validate_data_type(data_type)
        return self.connection.request(
            'events',
            {
                'event': event_names,
                'unit': unit,
                'interval': interval,
                'type': data_type,
            },
            response_format=response_format
        )

    def get_events_top(self, event_name, limit=10, response_format=FORMAT_JSON):
        """
        Get the top property names for an event.

        Args:
            `event_name`: [str] Te event that you wish to get data for. Note: this is a single event name, not a list.
                          [sample]: "play song" or "log in"
            `limit`: [int (optional)] The maximum number of properties to return. Defaults to 10.
            `response_format`: [string (optional)]: The data return format.
                               [sample]: "json" or "csv"

        Response format:
        {
            'ad version': {
                'count': 295
            },
            'user type': {
                'count': 91
            }
        }
        """
        self._validate_response_format(response_format)
        return self.connection.request(
            'events/properties/top',
            {
                'event': event_name,
                'limit': limit,
            },
            response_format=response_format
        )

    def get_event_top_names(self, data_type='general', limit=255, response_format=FORMAT_JSON):
        """
        Get a list of the most common events over the last 31 days; ordered by volume, descending

        Args:
            `event_type`: [str] The analysis type you would like to get data for.
                          [sample]: Valid values: 'general', 'unique', or 'average'
            `limit`: [int (optional)] The maximum number of properties to return. Defaults to 10.
            `response_format`: [string (optional)]: The data return format.
                               [sample]: "json" or "csv"

        Response format:
        {
            'ad version': {
                'count': 295
            },
            'user type': {
                'count': 91
            }
        }
        """
        self._validate_response_format(response_format)
        return self.connection.request(
            'events/names',
            {
                'type': data_type,
                'limit': limit,
            },
            response_format=response_format
        )

    # Event properties methods ########
    def get_event_properties(
            self, event_name, property_name, filter_values, unit,
            interval, data_type='general', limit=255,
            response_format=FORMAT_JSON):
        """
        Get unique, total, or average data for of a single event and property
        over the last N days, weeks, or months.

        Response format:
        {
            'data': {
                'series': ['2010-05-29', '2010-05-30', '2010-05-31'],
                'values': {
                    'splash features': {
                        '2010-05-29': 6,
                        '2010-05-30': 4,
                        '2010-05-31': 5,

                    }
                }
            },
            'legend_size': 2
        }
        """
        self._validate_response_format(response_format)
        return self.connection.request(
            'events/properties',
            {
                'event': event_name,
                'name': property_name,
                'values': filter_values,
                'unit': unit,
                'interval': interval,
                'type': data_type,
                'limit': limit,
            },
            response_format=response_format
        )

    def get_event_properties_top(self, event_name, limit=10, response_format=FORMAT_JSON):
        """
        Get the top property names for an event.

        Response format:
        {
            'ad version': {
                'count': 295
            },
            'user type': {
                'count': 91
            }
        }
        """
        self._validate_response_format(response_format)
        return self.connection.request(
            'events/properties/top',
            {
                'event': event_name,
                'limit': limit,
            },
            response_format=response_format
        )

    def get_event_properties_values(self, event_name, property_name, limit=255, bucket_id=None, response_format=FORMAT_JSON):
        """
        Get the top values for a property ordered by volume, descending.

        Response format:
            ['male', 'female', 'unknown']
        """
        self._validate_response_format(response_format)

        params = {
            'event': event_name,
            'name': property_name,
            'limit': limit,
        }
        if bucket_id:
            params.update({'bucket': bucket_id})

        return self.connection.request(
            'events/properties/values',
            params,
            response_format=response_format
        )

    # Funnel methods ##################
    def get_funnel_list(self, response_format=FORMAT_JSON):
        """
        Get the names and funnel_ids of your funnels. This method takes no parameters.

        Response format:
        [
            {"funnel_id": 7509, "name": "Signup funnel"},
            {"funnel_id": 9070, "name": "Funnel tutorial"}
        ]
        """
        self._validate_response_format(response_format)
        return self.connection.request(
            'funnels/list',
            {},
            response_format=response_format
        )

    def get_funnel_detail(
            self, funnel_id, start_date=None, end_date=None,
            length=14, interval=1, unit=UNIT_DAY, on=None, where=None, limit=None,
            response_format=FORMAT_JSON):
        """
        Get data for a specified funnel.

        Response format:
        {
            'Signup flow': {
                'data': {
                    '2010-05-24': {
                        'analysis': {
                            'completion': 0.064679359580052493,
                            'starting_amount': 762,
                            'steps': 3,
                            'worst': 2
                        },
                        'steps': [
                            {
                                'count': 762,
                                'goal': 'pages',
                                'overall_conv_ratio': 1.0,
                                'step_conv_ratio': 1.0
                            },
                            {
                                'count': 69,
                                'goal': 'View signup',
                                'overall_conv_ratio': 0.09055118110236221,
                                'step_conv_ratio': 0.09055118110236221
                            },
                            {
                                'count': 10,
                                'goal': 'View docs',
                                'overall_conv_ratio': 0.064679359580052493,
                                'step_conv_ratio': 0.7142857142857143
                            }
                        ]
                    },
                    '2010-05-31': {
                        'analysis': {
                            'completion': 0.12362030905077263,
                            'starting_amount': 906,
                            'steps': 2,
                            'worst': 2
                        },
                        'steps': [
                            {
                                'count': 906,
                                'goal': 'homepage',
                                'overall_conv_ratio': 1.0,
                                'step_conv_ratio': 1.0
                            },
                            {
                                'count': 112,
                                'goal': 'View signup',
                                'overall_conv_ratio': 0.12362030905077263,
                                'step_conv_ratio': 0.12362030905077263
                            }
                        ]
                    }
                },
            'meta': {'dates': ['2010-05-24', '2010-05-31']}
            }
        }
        """
        self._validate_response_format(response_format)
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)
        # self._validate_expression(on, where)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')

        return self.connection.request(
            'funnels',
            {
                'funnel_id': funnel_id,
                'from_date': start_date,
                'to_date': end_date,
                'length': length,
                'interval': interval,
                'unit': unit,
                'on': on,
                'where': where,
            },
            response_format=response_format
        )

    # Segmentation methods ############
    def get_segmentation(
            self, event_name, start_date, end_date,
            unit=UNIT_DAY, on=None, where=None, limit=None,
            data_type=DATA_TYPE_UNIQUE, response_format=FORMAT_JSON):
        """
        Get data for an event, segmented and filtered by properties.

        # Example 1
        Suppose Kevin Wood has a website named guidebook.com. He has an event named
        signed up, sent whenever a user signs up to example.com. It has a string
        property named `mp_country_code` that stores the country code of the
        user signing up.

        > user_client.get_segmentation('signed up', '2011-08-06', ' 2011-08-16')
        {
            'data': {
                'series': ['2011-08-08', '2011-08-09', '2011-08-06', '2011-08-07'],
                'values': {
                    'signed up': {
                        '2011-08-06': 147,
                        '2011-08-07': 146,
                        '2011-08-08': 776,
                        '2011-08-09': 1376
                    }
                }
            },
            'legend_size': 1
        }

        # Example 2
        Suppose Kevin is impressed with the number of signups on 2011-08-09, and now
        wants to know the top five countries his signups came from on that day. He
        can make the following query:

        > user_client.get_segmentation('signed up', '2011-08-09', ' 2011-08-09', limit=5, on='properties["mp_country_code"]')
        {
            'data': {
                'series': ['2011-08-09'],
                'values': {
                    'CA': {'2011-08-09': 277},
                    'FR': {'2011-08-09': 8},
                    'GB': {'2011-08-09': 19},
                    'IN': {'2011-08-09': 19},
                    'US': {'2011-08-09': 1036}
                }
            },
            'legend_size': 5
        }

        # Example 3
        Kevin now wants to zero in on the US and Canada. He is tracking a property
        named mp_keyword, which tells him the search keyword that users used to
        get to example.com. Now he wants to determine how many signups from the US
        and Canada came about as a result of a search that contained the word 'guidebook.'
        He can do that with the following query:

        > user_client.get_segmentation(
            'signed up',
            '2011-08-09',
            '2011-08-09',
            on='properties["mp_country_code"]',
            where='"guidebook" in properties["mp_keyword"] and ("CA" == properties["mp_country_code"] or "US" == properties["mp_country_code"])'
        )
        {
            'data': {
                'series': ['2011-08-09'],
                'values': {
                    'CA': {'2011-08-09': 31},
                    'US': {'2011-08-09': 312}
                }
            },
            'legend_size': 2
        }
        """
        self._validate_response_format(response_format)
        #self._validate_expression(on, where)
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')

        return self.connection.request(
            'segmentation',
            {
                'event': event_name,
                'from_date': start_date,
                'to_date': end_date,
                'unit': unit,
                'on': on,
                'where': where,
                'limit': limit,
                'type': data_type,
            },
            response_format=response_format
        )

    def get_segmentation_numeric(
            self, event_name, start_date, end_date, on,
            unit=UNIT_DAY, where=None,
            buckets=None, data_type=DATA_TYPE_UNIQUE,
            response_format=FORMAT_JSON):
        """
        Get data for an event, segmented and filtered by properties, with values placed into numeric buckets.

        # Example 1
        Kevin also has an event named page loaded. It has a property named time
        that represents the time in milliseconds it took to load the page. Kevin
        wants to see the distribution of page load times that are greater than
        2000 milliseconds. But suppose Harry accidentally was sending the time
        property to Mixpanel as a string, so its the incorrect type. He can make
        the following query involving an explicit typecast to number to get the
        results he wants:

        > user_client.get_segmentation_numeric(
            'page loaded',
            '2011-08-06',
            '2011-08-16',
            on='number(properties["time"])',
            where='number(properties["time"]) >= 2000',
            buckets=5
        )
        {
            'data': {
                'series': ['2011-08-08', '2011-08-09', '2011-08-06', '2011-08-07'],
                'values': {
                    '2,000 - 2,100': {
                        '2011-08-06': 1,
                        '2011-08-07': 5,
                        '2011-08-08': 4,
                        '2011-08-09': 15
                    },
                    '2,100 - 2,200': {
                        '2011-08-07': 2,
                        '2011-08-08': 7,
                        '2011-08-09': 15
                    },
                    '2,200 - 2,300': {
                        '2011-08-06': 1,
                        '2011-08-08': 6,
                        '2011-08-09': 5
                    },
                    '2,300 - 2,400': {
                        '2011-08-06': 4,
                        '2011-08-08': 1,
                        '2011-08-09': 12
                    },
                    '2,400 - 2,500': {
                        '2011-08-08': 2,
                        '2011-08-09': 5
                    }
                }
            },
            'legend_size': 5
        }
        """
        self._validate_response_format(response_format)
        #self._validate_expression(on, where)
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')

        return self.connection.request(
            'segmentation/numeric',
            {
                'event': event_name,
                'from_date': start_date,
                'to_date': end_date,
                'unit': unit,
                'on': on,
                'where': where,
                'buckets': buckets,
                'type': data_type,
            },
            response_format=response_format
        )

    def get_segmentation_sum(
            self, event_name, start_date, end_date, on,
            unit=UNIT_DAY, where=None,
            response_format=FORMAT_JSON):
        """
        Sums an expression for events per unit time.

        # Example 1
        Kevin also sells things from example.com. He has an event named item sold
        that tracks each item that gets sold from his website. It has a number property
        named price that records the value of the item being sold. He has another number
        property named overhead that represents the overhead cost of the item. Kevin
        can find out how much profit he is making each day with the following query:

        > user_client.get_segmentation_sum(
            'item sold',
            '2011-08-06',
            '2011-08-16',
            on='properties["price"] - properties["overhead"]',
        )
        {   'results': {
                '2011-08-06': 376.0,
                '2011-08-07': 634.0,
                '2011-08-08': 474.0,
                '2011-08-09': 483.0
        },
            'status': 'ok'
        }
        """
        self._validate_response_format(response_format)
        #self._validate_expression(on, where)
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')

        return self.connection.request(
            'segmentation/sum',
            {
                'event': event_name,
                'from_date': start_date,
                'to_date': end_date,
                'unit': unit,
                'on': on,
                'where': where
            },
            response_format=response_format
        )

    def get_segmentation_average(
            self, event_name, start_date, end_date,
            unit=UNIT_DAY, on=None, where=None,
            response_format=FORMAT_JSON):
        """
        Averages an expression for events per unit time.

        # Example 1
        Instead of finding out the total profit he is making per day by selling things
        from his website, Kevin can also find out the average price of an item being
        sold with the following query:

        > user_client.get_segmentation_average(
            'item sold',
            '2011-08-06',
            '2011-08-16',
            on='properties["price"] - properties["overhead"]',
        )
        {
            'results': {
                '2011-08-06': 8.64705882352939,
                '2011-08-07': 4.640625,
                '2011-08-08': 3.6230899830221,
                '2011-08-09': 7.3353658536585
            },
            'status': 'ok'
        }
        """
        self._validate_response_format(response_format)
        #self._validate_expression(on, where)
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')

        return self.connection.request(
            'segmentation/average',
            {
                'event': event_name,
                'from_date': start_date,
                'to_date': end_date,
                'unit': unit,
                'on': on,
                'where': where,
                'unit': unit,
            },
            response_format=response_format
        )

    def get_segmentation_multiseg(
            self, event_name, start_date, end_date,
            unit=UNIT_DAY, inner=None, outer=None,
            data_type=DATA_TYPE_GENERAL, where=None,
            limit=None, response_format=FORMAT_JSON):
        """
        WARNING THIS IS AN UNDOCUMENTED API ENDPOINT
        USE AT YOUR OWN RISK, MIXPANEL MAY CHANGE THIS

        This allows a user to segment on two properties rather
        just one. Example:

        > user_client.get_segmentation_multiseg(
            'item sold',
            '2011-08-06',
            '2011-08-16',
            inner='properties["$city"]',
            outer='properties["$region"]',
        )
        {
        u'data': {
            u'series': [u'2015-06-01', u'2015-06-02', u'2015-06-03'],
            u'values': {
                u'North Carolina': {
                    u'Charlotte': {
                        u'2015-06-01': 300,
                        u'2015-06-02': 111,
                        u'2015-06-03': 171
                    },
                    u'Austin': {
                        u'2015-06-01': 0,
                        u'2015-06-02': 0,
                        u'2015-06-03': 0
                    }
                },
                u'Texas': {
                    u'Charlotte': {
                        u'2015-06-01': 0,
                        u'2015-06-02': 0,
                        u'2015-06-03': 0},
                    u'Austin': {
                        u'2015-06-01': 3181,
                        u'2015-06-02': 3219,
                        u'2015-06-03': 3484
                    }
                }
            }
        },
        u'legend_size': 4
        }

        Note the way this works. Limit defines the range for both the inner
        outer properties. The top <limit> outer segments are matched against
        the top <limit> inner segments. In the case of region ond city
        this results in many nested segments with zero results. At this time
        you do not get the top inner segments per outer segment.
        """
        self._validate_response_format(response_format)
        #self._validate_expression(inner, outer, where)
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')

        return self.connection.request(
            'segmentation/multiseg',
            {
                'event': event_name,
                'from_date': start_date,
                'to_date': end_date,
                'unit': unit,
                'inner': inner,
                'outer': outer,
                'where': where,
                'type': data_type,
                'limit': limit,
            },
            response_format=response_format
        )

    # Retention methods ###############

    # People methods ##################
    def get_engage(self, where=None, session_id=None, page=None, response_format=FORMAT_JSON):
        """
        Query People Data.

        Reponse format:
            {'page': 0,
             'page_size': 1000,
             'results': [{'$distinct_id': 4,
                          '$properties': {'$created': '2008-12-12T11:20:47',
                                          '$email': 'example@mixpanel.com',
                                          '$first_name': 'Example',
                                          '$last_name': 'Name',
                                          '$last_seen': '2008-06-09T23:08:40',}}],
             'session_id': '1234567890-EXAMPL',
             'status': 'ok',
             'total': 1}
        """
        return self.connection.request(
            'engage',
            {
                'where': where,
                'session_id': session_id,
                'page': page,
            },
            response_format=response_format
        )

    # Export methods ##################
    def get_export(self, start_date, end_date, event=None, where=None, bucket_id=None, response_format=FORMAT_JSON):
        """
        Get a "raw dump" of tracked events over a time period.

        Yields events as they are returned (matching the format shown below).

        Args:
            `start_date`: [str] The date in yyyy-mm-dd format from which to begin querying for the
                                event from. This date is inclusive.
                          [sample]: "2014-04-01"
            `end_date`: [str] The date in yyyy-mm-dd format from which to stop querying for the
                              event from. This date is inclusive.
                        [sample]: "2014-04-01"
            `event`: [array (optional)]: The event or events that you wish to get data for.
                               [sample]: ["play song", "log in", "add playlist"]
            `where`: [str] An expression to filter events by.
            `bucket_id`: [str] The specific data bucket you would like to query.

        Event format:
            {"event":"Viewed report","properties":{"distinct_id":"foo","time":1329263748,"origin":"invite",
            "origin_referrer":"http://mixpanel.com/projects/","$initial_referring_domain":"mixpanel.com",
            "$referrer":"https://mixpanel.com/report/3/stream/","$initial_referrer":"http://mixpanel.com/",
            "$referring_domain":"mixpanel.com","$os":"Linux","origin_domain":"mixpanel.com","tab":"stream",
            "$browser":"Chrome","Project ID":"3","mp_country_code":"US"}}
        """
        start_date_obj = self._validate_date(start_date)
        end_date_obj = self._validate_date(end_date)

        # Check the actual dates
        if start_date_obj > end_date_obj:
            raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any events.')

        # the provided event should be an array even when a singleton
        # if a singleton string/unicode is provided, put it into an array
        if isinstance(event, six.string_types):
            event = [event]

        response = self.connection.raw_request(
            Connection.DATA_ENDPOINT,
            'export',
            {
                'from_date': start_date,
                'to_date': end_date,
                'event': event,
                'where': where,
                'bucket': bucket_id,
            },
            response_format
        )
        # per mixpanel documentation it is necessary to load
        # the response in it's entirety before processing:
        #     > This endpoint uses gzip to compress the transfer;
        #     > as a result, raw exports should not be processed until
        #     > the file is received in its entirety.
        # https://mixpanel.com/docs/api-documentation/exporting-raw-data-you-inserted-into-mixpanel
        response_data = response.read()
        lines = _totext(response_data).split('\n')

        for line in lines:
            if line:
                yield json.loads(line)

    # Util methods ####################
    def _validate_unit(self, unit):
        " Utility method used to validate a `unit` param. "
        if unit not in self.VALID_UNITS:
            raise exceptions.InvalidUnitException('The `unit` specified is invalid. Must be: {0}'.format(self.VALID_UNITS))

    def _validate_response_format(self, response_format):
        " Utility method used to validate a `response_format` param. "
        if response_format not in self.VALID_RESPONSE_FORMATS:
            raise exceptions.InvalidFormatException('The `response_format` specified is invalid. Must be {0}.'.format(self.VALID_RESPONSE_FORMATS))

    def _validate_date(self, date):
        " Utility method used to validate a `response_format` param. "
        try:
            return datetime.datetime.strptime(date, '%Y-%m-%d')
        except ValueError:
            try:
                return datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                raise exceptions.InvalidDateException('The `date` specified is invalid. Must be in `YYYY-MM-DD` format.')

    def _validate_data_type(self, data_type):
        " Utility method used to validate a `data_type` param. "
        if data_type not in self.VALID_DATA_TYPES:
            raise exceptions.InvalidDataType('The `data_type` specified is invalid.  Must be {0}'.format(self.VALID_DATA_TYPES))

    def _validate_expression(self, on, where):
        " Validate the expression by these rules: https://mixpanel.com/docs/api-documentation/data-export-api#segmentation-expressions ."
        raise NotImplementedError('This is not yet complete.')


text:
@implementation HMUnreadCountParam

@end

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto;

import com.facebook.presto.common.Page;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.PageIndexer;
import com.facebook.presto.spi.PageIndexerFactory;
import com.facebook.presto.sql.gen.JoinCompiler;

import javax.inject.Inject;

import java.util.List;

import static java.util.Objects.requireNonNull;

public class GroupByHashPageIndexerFactory
        implements PageIndexerFactory
{
    private final JoinCompiler joinCompiler;

    @Inject
    public GroupByHashPageIndexerFactory(JoinCompiler joinCompiler)
    {
        this.joinCompiler = requireNonNull(joinCompiler, "joinCompiler is null");
    }

    @Override
    public PageIndexer createPageIndexer(List<? extends Type> types)
    {
        if (types.isEmpty()) {
            return new NoHashPageIndexer();
        }
        return new GroupByHashPageIndexer(types, joinCompiler);
    }

    private static class NoHashPageIndexer
            implements PageIndexer
    {
        @Override
        public int[] indexPage(Page page)
        {
            return new int[page.getPositionCount()];
        }

        @Override
        public int getMaxIndex()
        {
            return 0;
        }
    }
}


text:
package org.apache.camel.model.rest;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;

import org.apache.camel.spi.Metadata;

/**
 * To specify the rest security definitions using Swagger.
 */
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class RestSecurityDefinition {

    @XmlTransient
    RestDefinition rest;

    @XmlAttribute(required = true) @Metadata(required = true)
    private String key;

    @XmlAttribute
    private String description;

    public RestSecurityDefinition() {
    }

    public RestSecurityDefinition(RestDefinition rest) {
        this.rest = rest;
    }

    /**
     * Ends the configuration of this security
     */
    public RestDefinition endSecurityDefinition() {
        rest.getSecurityDefinitions().getSecurityDefinitions().add(this);
        return rest;
    }

    public String getKey() {
        return key;
    }

    /**
     * Key used to refer to this security definition
     */
    public void setKey(String key) {
        this.key = key;
    }

    public String getDescription() {
        return description;
    }

    /**
     * A short description for security scheme.
     */
    public void setDescription(String description) {
        this.description = description;
    }

}


text:
function DatabaseConnection(_username, _password){
	this.conn = null;
	this.username = _username;
	this.password = _password;
}

DatabaseConnection.prototype.connect = function(callback){
	if(this.conn){
		callback(this.conn);
		return;
	}
	var sql = require('msnodesql');
	var conn_str = "Driver={SQL Server Native Client 10.0};Server=192.168.1.221;Database=AxManagement;Uid=" + this.username + ";Pwd=" + this.password + ";";
	var t = this;
	sql.open(conn_str, function(err, conn){
		if(err){
			console.log(err);
			callback({error: err.toString()});
			return;
		}
		t.conn = conn;
		console.log("Connected");
		callback(conn);
	});
}

DatabaseConnection.prototype.query = function(q, args, callback){
	if(typeof(args) == "function"){
		callback = args;
		args = [];
	}

	this.connect(function(conn){
		if(conn.error !== undefined) {
			callback(conn);
			return;
		}

		conn.query(q, args, function (err, results) {
			if (err) {
				console.log("Error running query!");
				console.log(err);
				if(typeof(callback) === "function")
					callback({error: err.toString(), query: q});
				return;
			}
			if(typeof(callback) === "function")
				callback(results, args);
		});
	});
}
exports = module.exports = DatabaseConnection;


text:
module ReleaseNotes
  VERSION = "0.0.1"
end


text:
package org.camelcookbook.parallelprocessing.endpointconsumers;

import org.apache.camel.builder.RouteBuilder;

/**
 * Route that demonstrates increasing the number of consumers on a SEDA endpoint.
 */
public class EndpointConsumersSedaRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("seda:in?concurrentConsumers=10")
            .delay(200)
            .log("Processing ${body}:${threadName}")
            .to("mock:out");
    }
}


text:
/*  Transforms YACC (Yet Another Compiler Compiler, or GNU Bison) grammar files
    @(#) $Id: YACCTransformer.java 566 2010-10-19 16:32:04Z gfis $
    2007-05-14, Georg Fischer: copied from ExtraTransformer
*/
/*
 * Copyright 2006 Dr. Georg Fischer <punctum at punctum dot kom>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.teherba.xtrans.grammar;
import  org.teherba.xtrans.grammar.ExtraTransformer;
import  java.io.BufferedReader;
import  org.xml.sax.Attributes;
import  org.apache.logging.log4j.Logger;
import  org.apache.logging.log4j.LogManager;

/** Transforms YACC (Yet Another Compiler Compiler, or GNU Bison) grammar files.
 *  Example for a YACC grammar:

%token NAME NUMBER
%%
statement: NAME '=' expression
	| expression					{ printf ("= %d\n", $1); }
	;
expression: expression '+' NUMBER	{ $$ = $1 + $3; }
	|	    expression '-' NUMBER	{ $$ = $1 - $3; }
	|		NUMBER					{ $$ = $1; }
	;
%%

 *  @author Dr. Georg Fischer
 */
public class YACCTransformer extends ExtraTransformer {
    public final static String CVSID = "@(#) $Id: YACCTransformer.java 566 2010-10-19 16:32:04Z gfis $";

    /** log4j logger (category) */
    private static Logger log = LogManager.getLogger(YACCTransformer.class.getName());;

    /** No-args Constructor.
     */
    public YACCTransformer() {
        super();
        setFormatCodes("yacc");
        setDescription("Yet Another Compiler Compiler");
        setFileExtensions("y");
    } // Constructor()

	/** Initializes the (quasi-constant) global structures and variables.
	 *  This method is called by the {@link org.teherba.xtrans.XtransFactory} once for the
	 *  selected generator and serializer.
	 */
	public void initialize() {
		super.initialize();
        putEntityReplacements();
	} // initialize

    //////////////////////
    // SAX event generator
    //////////////////////

    /** state of finite automaton */
    private int  state;
    /** values for state */
    private static final int IN_APOS     =  1; // after 1st apostrophe
    private static final int IN_COMMENT  =  2;
    private static final int IN_NAME     =  3;
    private static final int IN_PUNCT    =  4;
    private static final int IN_SEMA     =  5;
    private static final int IN_STRING   =  6; // after 1st double quote
    private static final int IN_BACKSLASH=  7; // after 1st "\\"
    private static final int IN_HEX      =  8;
    private static final int IN_PERCENT  =  9; // after 1st "%"
    private static final int IN_BRACE    = 10; // after 1st "{"

    /** Transforms from the specified format to XML
     *  @return whether the transformation was successful
     */
    public boolean generate() {
    	int noPcPc = 0; // number of "%%" tokens read so far
    	int braceLevel = 0; // nesting level of "{ ... }" inside semantic actions
        boolean result  = true;
        StringBuffer elementBuffer = new StringBuffer(64); // current XML element built during scanning process
        int hexBuffer = 0; // buffer for hex digits behind x or u
        try {
        	putEntityReplacements();
            fireStartDocument();
            fireStartRoot(ROOT_TAG);
            fireLineBreak();
            int state = IN_PUNCT;
            boolean inLHS    = false; // whether in left hand side of a rule
            boolean inString = false; // whether in string (enclosed in single quotes)
            boolean inTrans  = false; // whether in translation part
            boolean readOff  = true;  // whether current character should be consumed
            int grammarState = 0; // 0 = in prelude, 1 = in grammar, 2 = in postlude
            String line;
            BufferedReader buffReader = new BufferedReader(charReader);
            lineNo = 0;
            while ((line = buffReader.readLine()) != null) {
                lineNo ++;
                int linePos = 0;
                if (line.startsWith("%%")) {
                	grammarState ++;
                	linePos = 2;
	                switch (grammarState) {
	                	case 0: // cannot occur
	                	    break;
	                	case 1:
	                	    break;
	                	case 2:
                            if (inTrans) {
                                fireEndElement(TRANS_TAG);
                            }
                            fireEndElement(PROD_TAG);
                            fireEndElement(RULE_TAG);
                            fireStartElement(POSTLUDE_TAG);
	                	    break;
	                	default: // cannot occur
	                	    break;
	                } // switch grammarState
                } // leading "%%"

	            switch (grammarState) {
	            	case 0: // cannot occur
	            		fireCharacters(replaceNoSource(line));
	            		fireLineBreak();
	            	    break;

	            	case 1:
                        char ch; // current character to be processed
                        int trap = line.length();

                        while (linePos < trap) { // process all characters
                            readOff = true;
                            ch = line.charAt(linePos);
                            switch (state) {

                                case IN_PUNCT:
                                    switch (ch) {
                                        case ' ':
                                        case '\t':
                                            // ignore whitespace
                                            break;
                                        case '/':
                                            if (line.substring(linePos).startsWith("/*")) {
                                                state = IN_COMMENT;
                                                elementBuffer.setLength(0);
                                                linePos ++;
                                            } else {
                                            /*
                                                fireStartElement(ERROR_TAG);
                                                fireCharacters(replaceNoSource(line.substring(linePos)));
                                                fireEndElement(ERROR_TAG);
                                            */
                                                state = IN_PUNCT;
                                            }
                                            break;
                                        case '\'':
                                            inString = true;
                                            elementBuffer.setLength(0);
                                            state = IN_STRING;
                                            break;
                                        case '%':
                                            inLHS = true;
				        					state = IN_PERCENT;
                                            break;
                                        case '#':
                                            state = IN_SEMA;
                                            elementBuffer.setLength(0);
                                            break;
                                        case ';': // end of rule, start new one
                                            if (inTrans) {
                                                fireEndElement(TRANS_TAG);
                                            }
                                            fireEndElement(PROD_TAG);
                                            fireEndElement(RULE_TAG);
                                            inLHS = true;
                                            break;
                                        case ':': // end of left hand side, start of 1st production
                                            {
                                                fireStartElement(PROD_TAG);
                                                inTrans = false;
                                                inLHS = false;
                                            }
                                            break;
                                        case '|': // start of another production
                                            if (inTrans) {
                                                fireEndElement(TRANS_TAG);
                                            }
                                            fireEndElement(PROD_TAG);
                                            fireStartElement(PROD_TAG);
                                            inTrans = false;
                                            break;
                                        case '{': // start of semantic action(s)
                                            state = IN_BRACE;
                                            break;
                                        default:
                                            if (Character.isLetter(ch)) {
                                                elementBuffer.setLength(0);
                                                elementBuffer.append(ch);
                                                state = IN_NAME;
                                            }
                                            break;
                                    } // switch ch
                                    break;

                                case IN_PERCENT:
                                    if (ch == '%') {
                                    	noPcPc ++;
                                    	inLHS = true;
                                        if (noPcPc == 2 && ! inLHS) {
                                        } else if (noPcPc == 1) {
                                            elementBuffer.setLength(0);
                                            elementBuffer.append(ch);
                                            fireSimpleElement(SYM_TAG, replaceNoSource(elementBuffer.toString()));
                                            break;
                                        }
                                    } else {
                                    }
                                	state = IN_PUNCT;
                                	break;

                                case IN_BRACE:
                                    switch (ch) {
                                        case '}':
		                                	state = IN_PUNCT;
		                                	break;
				        				default:
				        					break;
				        			} // switch ch
                                	break;

                                case IN_COMMENT:
                                    if (line.substring(linePos).startsWith("*/")) {
                                        state = IN_PUNCT;
                                        fireSimpleElement(COMMENT_TAG, replaceNoSource(elementBuffer.toString()));
                                        linePos ++;
                                    } else {
                                        elementBuffer.append(ch);
                                    }
                                    break;

                                case IN_NAME:
                                    if (Character.isLetterOrDigit(ch) || ch == '_') {
                                        elementBuffer.append(ch);
                                    } else {
                                        readOff = false;
                                        state = IN_PUNCT;
                                        if (inLHS) {
                                            fireStartElement(RULE_TAG);
                                            fireSimpleElement(LEFT_TAG, elementBuffer.toString());
                                        } else {
                                            fireSimpleElement(SYM_TAG,  elementBuffer.toString());
                                        }
                                    }
                                    break;

                                case IN_SEMA:
                                    if (Character.isDigit(ch)) {
                                        elementBuffer.append(ch);
                                    } else {
                                        readOff = false;
                                        state = IN_PUNCT;
                                        fireSimpleElement(SEMA_TAG, elementBuffer.toString());
                                    }
                                    break;

                                case IN_STRING:
                                    switch (ch) {
                                        case '\'': // 2nd apostrophe
                                            state = IN_APOS;
                                            break;
                                        case '\\':
                                            state = IN_BACKSLASH;
                                            break;
                                        default:
                                            elementBuffer.append(ch);
                                            break;
                                    }
                                    break; // IN_STRING

                                case IN_BACKSLASH:
                                    state = IN_STRING;
                                    switch (ch) {
                                        case '\\':
                                            elementBuffer.append('\\');
                                            break;
                                        case 'f':
                                            elementBuffer.append('\f');
                                            break;
                                        case 'n':
                                            elementBuffer.append('\n');
                                            break;
                                        case 'r':
                                            elementBuffer.append('\r');
                                            break;
                                        case 't':
                                            elementBuffer.append('\t');
                                            break;
                                        case 'u':
                                        case 'x':
                                            hexBuffer = 0;
                                            state = IN_HEX;
                                            break;
                                        default:
                                            elementBuffer.append(ch);
                                            break;
                                    }
                                    break;

                                case IN_HEX:
                                    int dig = Character.digit(ch, 16);
                                    if (dig >= 0) {
                                        hexBuffer = hexBuffer * 16 + dig;
                                    } else {
                                        state = IN_STRING;
                                        readOff = false;
                                        elementBuffer.append((char) (hexBuffer & 0xffff));
                                    }
                                    break;

                                case IN_APOS:
                                    switch (ch) {
                                        case '\'':
                                            elementBuffer.append(ch); // append 2nd apostrophe only
                                            state = IN_STRING;
                                            break;
                                        default: // no 2nd apostrophe followed - end of string
                                            readOff = false;
                                            fireSimpleElement(TERM_TAG, elementBuffer.toString());
                                            state = IN_PUNCT;
                                            break;
                                    }
                                    break; // IN_APOS

                                default:
                                    log.error("invalid state " + state);
                                    break;
                            } // switch state */
                            if (readOff) {
                                linePos ++;
                            }
                        } // while processing characters
                        fireLineBreak();
	            	    break;

	            	case 2:
	            		fireCharacters(replaceNoSource(line));
	            		fireLineBreak();
	            	    break;
	            	default: // cannot occur
	            	    break;
	            } // switch grammarState

            } // while not EOF
            buffReader.close();
            fireEndElement(POSTLUDE_TAG);
            fireEndElement(ROOT_TAG);
            fireLineBreak();
            fireEndDocument();
        } catch (Exception exc) {
            log.error(exc.getMessage(), exc);
        }
        return  result;
    }

    //////////////////////
    // SAX content handler
    //////////////////////

    /** Receive notification of the beginning of the document.
     */
    public void startDocument() {
        lineBuffer  = new StringBuffer(MAX_BUF); // a rather long line
        String nl = System.getProperty("line.separator");
        openElement = "";
        ruleCount   = 0;
		startGrammarToken = nl + "%%";
		endGrammarToken   = "%%" + nl;
		startRuleToken    = " : ";
		endRuleToken      = nl + ";";
		startProdToken    = "\t| ";
		endProdToken      = "";
		startTransToken   = " { ";
		endTransToken     = " } ";
        charWriter.print("%token ");
    }

    /** Receive notification of the start of an element.
     *  Looks for the element which contains raw lines.
     *  @param uri The Namespace URI, or the empty string if the element has no Namespace URI
     *  or if Namespace processing is not being performed.
     *  @param localName the local name (without prefix),
     *  or the empty string if namespace processing is not being performed.
     *  @param qName the qualified name (with prefix),
     *  or the empty string if qualified names are not available.
     *  @param attrs the attributes attached to the element.
     *  If there are no attributes, it shall be an empty Attributes object.
     */
    public void startElement(String uri, String localName, String qName, Attributes attrs) {
        if (namespace.length() > 0 && qName.startsWith(namespace)) {
            qName = qName.substring(namespace.length());
        }
        openElement = qName;
        if (false) {
        } else if (qName.equals(ROOT_TAG   )) {
            lineBuffer.setLength(0);
        } else if (qName.equals(COMMENT_TAG)) {
            lineBuffer.setLength(0);
            lineBuffer.append("/*");
        } else if (qName.equals(RULE_TAG   )) {
            charWriter.print(lineBuffer.toString());
            if (ruleCount <= 0) {
                lineBuffer.setLength(0);
                lineBuffer.append(startGrammarToken);
            } else {
            }
            ruleCount ++;
            prodCount = 0;
        } else if (qName.equals(LEFT_TAG   )) {
        } else if (qName.equals(SEMA_TAG   )) {
            lineBuffer.append("#");
        } else if (qName.equals(SYM_TAG    )) {
        } else if (qName.equals(TRANS_TAG  )) {
            lineBuffer.append(startTransToken);
        } else if (qName.equals(PROD_TAG   )) {
            if (prodCount <= 0) {
                lineBuffer.append(startRuleToken);
            } else {
                charWriter.println(lineBuffer.toString());
                lineBuffer.setLength(0);
                lineBuffer.append(startProdToken);
            }
            prodCount ++;
        } else if (qName.equals(TERM_TAG   )) {
            lineBuffer.append('\'');
        } // else ignore unknown elements
    }

    /** Receive notification of the end of an element.
     *  Looks for the element which contains raw lines.
     *  Terminates the line.
     *  @param uri the Namespace URI, or the empty string if the element has no Namespace URI
     *  or if Namespace processing is not being performed.
     *  @param localName the local name (without prefix),
     *  or the empty string if Namespace processing is not being performed.
     *  @param qName the qualified name (with prefix),
     *  or the empty string if qualified names are not available.
     */
    public void endElement(String uri, String localName, String qName) {
        if (namespace.length() > 0 && qName.startsWith(namespace)) {
            qName = qName.substring(namespace.length());
        }
        openElement = "";
        if (false) {
        } else if (qName.equals(ROOT_TAG   )) {
            charWriter.println(lineBuffer.toString());
            lineBuffer.setLength(0);
            charWriter.print(endGrammarToken);
        } else if (qName.equals(COMMENT_TAG)) {
            lineBuffer.append("*/");
            charWriter.println(lineBuffer.toString());
            lineBuffer.setLength(0);
        } else if (qName.equals(RULE_TAG   )) {
            lineBuffer.append(endRuleToken);
            charWriter.print(lineBuffer.toString());
            lineBuffer.setLength(0);
        } else if (qName.equals(LEFT_TAG   )) {
        } else if (qName.equals(SEMA_TAG   )) {
            lineBuffer.append(" ");
        } else if (qName.equals(SYM_TAG    )) {
            lineBuffer.append(" ");
        } else if (qName.equals(TRANS_TAG  )) {
        	lineBuffer.append(endTransToken);
        } else if (qName.equals(PROD_TAG   )) {
        	lineBuffer.append(endProdToken);
            charWriter.print(lineBuffer.toString());
            lineBuffer.setLength(0);
        } else if (qName.equals(TERM_TAG   )) {
            lineBuffer.append("\' ");
            charWriter.print(lineBuffer.toString());
            lineBuffer.setLength(0);
        } // else ignore unknown elements
    }

    /** Receive notification of character data inside an element.
     *  @param ch the characters.
     *  @param start the start position in the character array.
     *  @param len the number of characters to use from the character array.
     */
    public void characters(char[] ch, int start, int len) {
        if  (false) {
        } else if ( openElement.equals(COMMENT_TAG)
                ||  openElement.equals(SYM_TAG    )
                ||  openElement.equals(LEFT_TAG   )
                ||  openElement.equals(SEMA_TAG   )
                ) {
            String text = new String(ch, start, len);
            lineBuffer.append(new String(ch, start, len));
        } else if ( openElement.equals(TERM_TAG   )) {
            String text = replaceInResult(new String(ch, start, len));
            lineBuffer.append(text.replaceAll("\'","\'\'"));
        } // else ignore whitespace around unknown elements
    }
}


text:
extern "C" {
#endif
#include <lmuseflg.h>
#define USE_LOCAL_PARMNUM 1
#define USE_REMOTE_PARMNUM 2
#define USE_PASSWORD_PARMNUM 3
#define USE_ASGTYPE_PARMNUM 4
#define USE_USERNAME_PARMNUM 5
#define USE_DOMAINNAME_PARMNUM 6
#define USE_OK 0
#define USE_PAUSED 1
#define USE_SESSLOST 2
#define USE_DISCONN 2
#define USE_NETERR 3
#define USE_CONN 4
#define USE_RECONN 5
#define USE_WILDCARD ((DWORD)-1)
#define USE_DISKDEV 0
#define USE_SPOOLDEV 1
#define USE_CHARDEV 2
#define USE_IPC 3
typedef struct _USE_INFO_0 {
	LPWSTR ui0_local;
	LPWSTR ui0_remote;
}USE_INFO_0,*PUSE_INFO_0,*LPUSE_INFO_0;
typedef struct _USE_INFO_1 {
	LPWSTR ui1_local;
	LPWSTR ui1_remote;
	LPWSTR ui1_password;
	DWORD ui1_status;
	DWORD ui1_asg_type;
	DWORD ui1_refcount;
	DWORD ui1_usecount;
}USE_INFO_1,*PUSE_INFO_1,*LPUSE_INFO_1;
typedef struct _USE_INFO_2 {
	LPWSTR ui2_local;
	LPWSTR ui2_remote;
	LPWSTR ui2_password;
	DWORD ui2_status;
	DWORD ui2_asg_type;
	DWORD ui2_refcount;
	DWORD ui2_usecount;
	LPWSTR ui2_username;
	LPWSTR ui2_domainname;
}USE_INFO_2,*PUSE_INFO_2,*LPUSE_INFO_2;
NET_API_STATUS WINAPI NetUseAdd(LPWSTR,DWORD,PBYTE,PDWORD);
NET_API_STATUS WINAPI NetUseDel(LPWSTR,LPWSTR,DWORD);
NET_API_STATUS WINAPI NetUseEnum(LPWSTR,DWORD,PBYTE*,DWORD,PDWORD,PDWORD,PDWORD);
NET_API_STATUS WINAPI NetUseGetInfo(LPWSTR,LPWSTR,DWORD,PBYTE*);
#ifdef __cplusplus
}
#endif
#endif


text:
/** Embedded content
===========================================================================
Images, videos, iframes.*/

._embed {
    height: auto;
    max-width: 100%;
}
._embed img {
    border: 0;
    max-width: 100%;
    /* Fix for [disappearing images in IE 8](http://www.456bereastreet.com/archive/201202/using_max-width_on_images_can_make_them_disappear_in_ie8/). */
    width: auto\9;
    /* Remove the gap between image and container. */
    vertical-align: middle;
}
._embed-circle {
    overflow: hidden;
    border-radius: 999px;
}


text:
require 'spec_helper'
require 'whois/record/parser/whois.nic.gd.rb'

describe Whois::Record::Parser::WhoisNicGd, "status_restricted.expected" do

  subject do
    file = fixture("responses", "whois.nic.gd/status_restricted.txt")
    part = Whois::Record::Part.new(body: File.read(file))
    described_class.new(part)
  end

  describe "#status" do
    it do
      expect(subject.status).to eq(:reserved)
    end
  end
  describe "#available?" do
    it do
      expect(subject.available?).to eq(false)
    end
  end
end


text:
@interface CroppingController (){
    __block void(^cropCompleteBlock)(UIImage*img);
    UIView *contentView;
    CGFloat imageScale;//default zoomscale
    UIImage *originImage;
    UIImageView *originImageView;//原图view
    UIImageView *reviewImageView;//预览view
    CGRect originImageViewFrame;//默认的图片frame
    UIImageView *dashedBoxView;//裁剪框
    UIImageView *errView;//选择竖屏图片的时候错误提示
    UIButton *confirmButton;//确定按钮
    UIButton *cancelButton;//取消裁剪
}

@end

@implementation CroppingController

- (void)dealloc{
    contentView = nil;
    originImage = nil;
    originImageView = nil;
    dashedBoxView = nil;
}

- (id)initWithCompleteBlock:(void (^)(UIImage *img))block{
    self = [super init];
    if (self) {
        cropCompleteBlock = block;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    // 从相册选图片
    [self startMediaBrowserFromViewController:self];
}

// 图片选择后准备工作
- (void)albumImageChoosed:(UIImage*)img{
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    // 非横屏照片不处理,提示错误
    if (img.size.width < img.size.height) {
        [self portraitImageCase];
        return;
    }

    switch (img.imageOrientation) {
        case UIImageOrientationLeft:{//90 deg CCW
            img = [self image:img rotatedByDegrees:-90];
            img = [self scaleImage:img toSize:CGSizeMake(img.size.height, img.size.width)];
            break;
        }
        case UIImageOrientationRight:{//90 deg CW
            img = [self image:img rotatedByDegrees:90];
            img = [self scaleImage:img toSize:CGSizeMake(img.size.height, img.size.width)];
            break;
        }
        case UIImageOrientationDown:{// 180 deg rotation
            // 180 deg rotation
            img = [self image:img rotatedByDegrees:180];
            break;
        }
        default:
            break;
    }
    // 原图片
    originImage = img;//[UIImage imageNamed:@"test.jpg"];
    NSLog(@"image size:%@",[NSValue valueWithCGSize:originImage.size]);

    // 所有ui的容器
    contentView = [[UIView alloc] init];
    contentView.transform = CGAffineTransformMakeRotation(M_PI/2.0);
    contentView.frame = self.view.bounds;
    contentView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:contentView];

    originImageView = [[UIImageView alloc] init];
    originImageView.image = originImage;
    originImageView.clipsToBounds = NO;
    originImageView.userInteractionEnabled = YES;
    imageScale = contentView.frame.size.height/originImage.size.height;
    originImageView.frame = CGRectMake(0, 0, originImage.size.width*imageScale, originImage.size.height*imageScale);
    originImageView.center = CGPointMake(contentView.frame.size.height/2.0, contentView.frame.size.width/2.0);
    [contentView addSubview:originImageView];
    [self addUserGustrue];
    originImageViewFrame = originImageView.frame;

    // 虚线框
    CGFloat cropWithd = 300;
    CGFloat cropHeight = 200;
    dashedBoxView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cropWithd, cropHeight)];
    dashedBoxView.userInteractionEnabled = NO;
    dashedBoxView.image = ImageWithName(@"caijian_bg@2x");
    dashedBoxView.center = originImageView.center;

    // 预览view
    reviewImageView = [[UIImageView alloc] initWithFrame:dashedBoxView.frame];
    reviewImageView.userInteractionEnabled = NO;
    [contentView addSubview:reviewImageView];
    [contentView addSubview:dashedBoxView];

    // 确定按钮
    confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmButton.hidden = YES;
    confirmButton.frame = CGRectMake(CGRectGetHeight(contentView.frame)-65, (320-72)/2, 65, 72);
    [confirmButton addTarget:self action:@selector(confirmButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton setImage:ImageWithName(@"caijian_queding@2x") forState:UIControlStateNormal];
    [contentView addSubview:confirmButton];

    // 裁剪按钮
    UIButton *cropButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cropButton.frame = CGRectMake(CGRectGetMinX(dashedBoxView.frame)-25, CGRectGetMaxY(dashedBoxView.frame)-25, 50, 50);
    [cropButton addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [cropButton setImage:ImageWithName(@"caijian_caijian@2x") forState:UIControlStateNormal];
    [contentView addSubview:cropButton];

    // 取消按钮
    cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.hidden = YES;
    cancelButton.frame = CGRectMake(CGRectGetMinX(cropButton.frame)-60, CGRectGetMinY(cropButton.frame), 50, 50);
    [cancelButton addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setImage:ImageWithName(@"caijian_guanbi@2x") forState:UIControlStateNormal];
    [contentView addSubview:cancelButton];

    // 返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 51, 63);
    [backButton addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:ImageWithName(@"caijian_fanhui@2x") forState:UIControlStateNormal];
    [contentView addSubview:backButton];

    [self addUserGustrue];
}

// 照片竖屏处理
- (void)portraitImageCase{
    UIImage *image = [UIImage imageNamed:@"xiangce_tishi"];
    UIEdgeInsets edge = UIEdgeInsetsMake(1, 160, image.size.height-2, 159);
    image = [image resizableImageWithCapInsets:edge];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imgView.image = image;
    imgView.backgroundColor = [UIColor blackColor];
    imgView.userInteractionEnabled = YES;
    [self.view addSubview:imgView];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backButtonAction)];
    [tapGesture setNumberOfTapsRequired:1];
    [imgView addGestureRecognizer:tapGesture];
}

// 添加手势
- (void)addUserGustrue{
    UIPinchGestureRecognizer *scaleGes = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scaleImage:)];
    [originImageView addGestureRecognizer:scaleGes];

    UIPanGestureRecognizer *moveGes = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveImage:)];
    [moveGes setMinimumNumberOfTouches:1];
    [moveGes setMaximumNumberOfTouches:1];
    [originImageView addGestureRecognizer:moveGes];
}

// 取消裁剪
- (void) cancelButtonAction{
    // 显示裁剪结果
    reviewImageView.image = nil;
    // 隐藏原图
    originImageView.hidden = NO;
    // 置空裁剪结果
    self.croppedImage = nil;
    // 隐藏确定按钮
    confirmButton.hidden = YES;
    // 隐藏取消按钮
    cancelButton.hidden = YES;
}

// 返回
- (void)backButtonAction{
    [self.navigationController  popViewControllerAnimated:YES];
}

// 确定按钮
- (void)confirmButtonAction{
    //回调
    if (self.croppedImage != nil) {
        cropCompleteBlock(self.croppedImage);
    }

    [self backButtonAction];
}

// 裁剪
- (void)buttonAction{
    float zoomScale = originImageView.frame.size.height/originImage.size.height;
    CGFloat originX = dashedBoxView.frame.origin.x-originImageView.frame.origin.x;
    CGFloat originY = dashedBoxView.frame.origin.y-originImageView.frame.origin.y;
    CGSize cropSize = CGSizeMake(dashedBoxView.frame.size.width/zoomScale, dashedBoxView.frame.size.height/zoomScale);

    CGRect cropRect = CGRectMake(originX/zoomScale, originY/zoomScale, cropSize.width, cropSize.height);
    NSLog(@"originX:%lf originY:%lf,corpRect:%@",originX,originY,[NSValue valueWithCGRect:cropRect]);

    CGImageRef tmp = CGImageCreateWithImageInRect([originImage CGImage], cropRect);
    self.croppedImage = [UIImage imageWithCGImage:tmp scale:originImage.scale orientation:originImage.imageOrientation];
    NSLog(@"image size:%@",[NSValue valueWithCGSize:self.croppedImage.size]);
    if (self.croppedImage.size.width > 720) {
        self.croppedImage = [self scaleImage:self.croppedImage toSize:CGSizeMake(720, 480)];
    }

    // 显示裁剪结果
    reviewImageView.image = self.croppedImage;
    // 隐藏原图
    originImageView.hidden = YES;
    // 显示确定按钮
    confirmButton.hidden = NO;
    // 显示取消按钮
    cancelButton.hidden = NO;
}

// 处理缩放
float _lastScale = 1.0;
- (void)scaleImage:(UIPinchGestureRecognizer *)sender
{
    if([sender state] == UIGestureRecognizerStateBegan) {
        _lastScale = 1.0;
        return;
    }

    CGFloat scale = [sender scale]/_lastScale;

    if([sender state] == UIGestureRecognizerStateEnded) {
        // 裁剪框必须在图片内部
        if (![self dashebBoxInsideOriginImageView]) {
            return;
        }
    }

    CGAffineTransform currentTransform = originImageView.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    [originImageView setTransform:newTransform];

    _lastScale = [sender scale];
}

// 处理移动
float _lastTransX = 0.0, _lastTransY = 0.0;
- (void)moveImage:(UIPanGestureRecognizer *)sender
{
    CGPoint translatedPoint = [sender translationInView:contentView];

    if([sender state] == UIGestureRecognizerStateBegan) {
        _lastTransX = 0.0;
        _lastTransY = 0.0;
    }

    if([sender state] == UIGestureRecognizerStateEnded) {
        if (![self dashebBoxInsideOriginImageView]) {
            return;
        }
    }

    CGAffineTransform trans = CGAffineTransformMakeTranslation(translatedPoint.x - _lastTransX, translatedPoint.y - _lastTransY);
    CGAffineTransform newTransform = CGAffineTransformConcat(originImageView.transform, trans);
    _lastTransX = translatedPoint.x;
    _lastTransY = translatedPoint.y;

    originImageView.transform = newTransform;
}

// 检查裁剪框是否还在图片矩形内部,不在还原
- (BOOL)dashebBoxInsideOriginImageView{
    if(!CGRectContainsRect(originImageView.frame, dashedBoxView.frame)){
        [self recoverOriginImageviewStatus];
        return NO;
    }
    return YES;
}

// 恢复originImageview的默认状态
- (void)recoverOriginImageviewStatus{
    [UIView animateWithDuration:0.3
                     animations:^{
                         originImageView.frame = originImageViewFrame;
                     }
                     completion:^(BOOL finished){}];
}

#pragma mark - Navigationbar delegate
- (void)navgationBar:(id)bar leftButtonAction:(UIButton *)button{
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - CroppingController private
CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;};

- (UIImage *)image:(UIImage*)image rotatedByRadians:(CGFloat)radians{
    return [self image:image rotatedByDegrees:RadiansToDegrees(radians)];
}

- (UIImage *)image:(UIImage*)image rotatedByDegrees:(CGFloat)degrees{
    UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,image.size.width, image.size.height)];
    CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;

    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

    CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-image.size.width / 2, -image.size.height / 2, image.size.width, image.size.height), [image CGImage]);

    UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resImage;
}

//等比例缩放
-(UIImage*)scaleImage:(UIImage*)image toSize:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);

    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];

    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    // 使当前的context出堆栈
    UIGraphicsEndImageContext();

    // 返回新的改变大小后的图片
    return scaledImage;
}
@end


text:
module TmdbRexx
  class Client
    module Job
      RESOURCE = "job".freeze

      # Get the list of valid jobs
      #
      # @see # http://docs.themoviedb.apiary.io/#reference/movies/joblist
      #
      # @return [Hashie::Mash] response
      #
      # @example Get the jobs api response
      #   client.jobs
      def jobs(options = {})
        get([RESOURCE, "list"].join("/"), options)['jobs']
      end
    end
  end
end


text:
module.exports = {
    resultsReporter: function(results) {
        console.log(results);
    },

    benchmarkReporter: function(benchmark) {
        console.log(benchmark);
    }
};


text:
require_relative '../config/environment'

#MONKEY PATCHING WUT
class String
  def strip_ingredient_list
    #[2, 6, 13, 99, 27].any? { |i| [6, 13].include? i }
    #possibly use regex to combine this query
    self.split(/[\s,()]/).reject do |string|
      string.include?("tablespoon")  || string.include?("teaspoon") || string.include?("cup") || /\A\d+\z/.match(string) ||  string.include?("(") || string.include?(")") || string.include?(",") || string.include?("/") || string.include?("-") || string.include?("about")
    end.join(' ')
  end
end

#ingredient string wrapper class, initialize with a string instead of monkey patching

SEARCH_TERMS = ["chicken" , "eggs", "beef","pork", "carribean", "greek", "mexican", "italian", "vegetarian", "vegan",]
#https://api.edamam.com/search?q=chicken&app_id=${81a71c4e}&app_key=${52085f9209f9d0b19ee7a21fb9f0cdd6}
SEARCH_TERMS.each do |term|

  response = RestClient.get("https://api.edamam.com/search?q=#{term}&app_id=81a71c4e&app_key=52085f9209f9d0b19ee7a21fb9f0cdd6")
  data = JSON.parse(response)
  #binding.pry
  #puts "EOF"

  #data["hits"][0]["ingredients"]

  #ingredient list
  #data["hits"][0]["recipe"]["ingredients"]
  #individual ingredients
  #data["hits"][0]["recipe"]["ingredients"].collect{|ingredient| ingredient["text"]}
  #recipe title
  #data["hits"][0]["recipe"]["label"]

  #filling db with data
  data["hits"].each do |hit|

    r = Recipe.find_or_create_by(title: hit["recipe"]["label"])
    r.directions = hit["recipe"]["url"]
    r.save
    #binding.pry
    hit["recipe"]["ingredients"].each do |ingredient|
      ingredient_var = Ingredient.where("name LIKE ?", "%#{ingredient["text"].strip_ingredient_list}%").first
      if !!ingredient_var
        r.ingredients << ingredient_var
        r.save
      else
        #binding.pry
        r.ingredients.build(name: ingredient["text"].strip_ingredient_list)
      end
    end
    r.save
  end#end of data["hits"].each
end#end of SEARCH_TERMS.each

binding.pry
puts "EOF"

#filling a sample array to test our regex to extract ingredient names
# sample_array = []
# data["hits"].each do |hit|
#
#   sample_array += hit["recipe"]["ingredients"].collect{|ingredient| ingredient["text"]}
# end
# puts sample_array
# binding.pry
# puts "EOF"
#
# single_test = sample_array[1].split(/[\s,()]/)
# single_test = single_test.reject do |string|
#   string.include?("tablespoon")  || /\A\d+\z/.match(string) ||  string.include?("(") || string.include?(")") || string.include?(",")
# end
#
# puts sample_array.collect{|ingredient_list| ingredient_list.strip_ingredient_list}


text:
<?php

namespace spec\Http\Client\Utils;

trait StreamFactoryBehavior
{
    function it_is_a_stream_factory()
    {
        $this->shouldImplement('Http\Message\StreamFactory');
    }

    function it_creates_a_stream_from_string()
    {
        $this->createStream('foo')->shouldHaveType('Psr\Http\Message\StreamInterface');
    }

    function it_creates_a_stream_from_resource()
    {
        $this->createStream(fopen('php://memory', 'rw'))
            ->shouldHaveType('Psr\Http\Message\StreamInterface');
    }

    function it_creates_a_stream_from_null()
    {
        $this->createStream(null)->shouldHaveType('Psr\Http\Message\StreamInterface');
    }
}


text:
package playground.spring.propertyinjection.profiles;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SimpleApplication implements CommandLineRunner {

    private final CommandLineLoop commandLineLoop;

    @Autowired
    public SimpleApplication(CommandLineLoop commandLineLoop) {

        this.commandLineLoop = commandLineLoop;
    }

    public static void main(String[] args) {
        SpringApplication.run(SimpleApplication.class, args);
    }

    @Override
    public void run(String... args) {

        commandLineLoop.run(args);
    }
}


text:
using System.Collections.Specialized;
using System.Linq;

namespace Platform.VirtualFileSystem.Providers.Zip
{
	public class ZipNodeProvider
		: AbstractMultiFileSystemNodeProvider
	{
		public override string[] SupportedUriSchemas => new[] { "zip" };

		public ZipNodeProvider(IFileSystemManager manager)
			: base(manager)
		{
		}

		protected override INodeAddress ParseUri(string uri)
		{
			return LayeredNodeAddress.Parse(uri);
		}

		protected override IFileSystem NewFileSystem(INodeAddress rootAddress, FileSystemOptions options, out bool cache)
		{
			var backingFile = this.Manager.ResolveFile(((LayeredNodeAddress)rootAddress).InnerUri);

			cache = true;

			return new ZipFileSystem(rootAddress, backingFile, this.AmmendOptionsFromAddress(backingFile.Address, options));
		}
	}
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class RemoveActiveColumn extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::table('servers', function (Blueprint $table) {
            $table->dropColumn('active');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::table('servers', function (Blueprint $table) {
            $table->tinyInteger('active')->after('name')->unsigned()->default(0);
        });
    }
}


text:
<?php
  $page_title = 'Edit Category';
  require_once('use/load.php');
  // Requires Admin Level Access
  checkUserAccessLevel(1);
?>
<?php
  //Display all categories.
  $category = find_by_id('categories',(int)$_GET['id']);
  if(!$category){
    $session->message("d","Missing parameter or category id");
    goToPage('category.php');
  }
?>

<?php

   //$checkCategoryExists = $db->query("select name FROM categories where name={'$category_name'}");
if(isset($_POST['edit_cat'])){
  $req_field = array('category_name');
  isBlank($req_field);
  $category_name = cleanseHTML($db->cleanse_SQL($_POST['category_name']));
  if(empty($errors)){
        $sql = "UPDATE categories SET name='{$category_name}'";
       $sql .= " WHERE id='{$category['id']}'";
     $result = $db->query($sql);
     if($result && $db->affected_rows() === 1) {
       $session->message("s", "Successfully updated ".$category_name);
       goToPage('category.php',false);
     } else {
       $session->message("d", "Failed to update ".$category_name);
       goToPage('category.php',false);
     }
  } else {
    $session->message("d", $errors);
    goToPage('category.php',false);
  }
}
?>
<?php include_once('webpage_full_layout/header.php'); ?>

     <?php echo displayMessage($msg); ?>

           Editing <?php echo cleanseHTML(ucfirst($category['name']));?>

         <form method="post" action="editCategory.php?id=<?php echo (int)$category['id'];?>">

               <input type="text" class="form-control" name="category_name" value="<?php echo cleanseHTML(ucfirst($category['name']));?>">

           <button type="submit" name="edit_cat" class="btn btn-primary">Update Category</button>
       </form>

<?php include_once('webpage_full_layout/footer.php'); ?>


text:
NSString *const kOCLoggerSettings_keepLogSavedTimeKey              = @"OCLogService.KeepLogAvailableTime";
NSString *const kOCLoggerSettings_logToConsoleKey                  = @"OCLogService.LogToConsole";
NSString *const kOCLoggerSettings_logToFileKey                     = @"OCLogService.LogToFile";
NSString *const kOCLoggerSettings_lotToService                     = @"OCLogService.LogToService";
NSString *const kOCLoggerSettings_flushToServerAutomaticallyKey    = @"OCLogService.FlushToServerAutomatically";
NSString *const kOCLoggerSettings_serverUrlKey                     = @"OCLogService.ServerURL";

@interface OCLoggerSettings()
{
    NSTimeInterval keepLogSavedTimeInterval;
    BOOL logToConsole;
    BOOL logToFile;
    BOOL logToService;
    BOOL flushToServerAutomatically;
    NSString *serverUrl;
}

@end

@implementation OCLoggerSettings

#pragma mark - Instantiation

+ (instancetype)initWithFile:(NSString *)fileName
{
    NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:fileName];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfURL:[NSURL fileURLWithPath:path]];
    if (!dict) return nil;

    return [[self alloc] initWithDictionary:dict];;
}

#pragma mark - Instantiating with dictionary

- (id)initWithDictionary:(NSDictionary *)aDict;
{
    if (self = [super init])
    {
        NSNumber *keepLogSavedNumber                = [aDict objectForKey:kOCLoggerSettings_keepLogSavedTimeKey];
        NSNumber *logToConsoleNumber                = [aDict objectForKey:kOCLoggerSettings_logToConsoleKey];
        NSNumber *logToFileNumber                   = [aDict objectForKey:kOCLoggerSettings_logToFileKey];
        NSNumber *logToServiceNumber                = [aDict objectForKey:kOCLoggerSettings_lotToService];
        NSNumber *flushToServerAutomaticallyNumber  = [aDict objectForKey:kOCLoggerSettings_flushToServerAutomaticallyKey];
        NSString *serverUrlString                   = [aDict objectForKey:kOCLoggerSettings_serverUrlKey];

        NSAssert2(keepLogSavedNumber,               @"Settings should contain key: |%@| as |%@|", kOCLoggerSettings_keepLogSavedTimeKey, @"double");
        NSAssert2(logToConsoleNumber,               @"Settings should contain key: |%@| as |%@|", kOCLoggerSettings_logToConsoleKey, @"bool");
        NSAssert2(logToFileNumber,                  @"Settings should contain key: |%@| as |%@|", kOCLoggerSettings_logToFileKey, @"bool");
        NSAssert2(logToServiceNumber,               @"Settings should contain key: |%@| as |%@|", kOCLoggerSettings_lotToService, @"bool");
        NSAssert2(flushToServerAutomaticallyNumber, @"Settings should contain key: |%@| as |%@|", kOCLoggerSettings_flushToServerAutomaticallyKey, @"bool");
        NSAssert2(serverUrlString,                  @"Settings should contain key: |%@| as |%@|", kOCLoggerSettings_serverUrlKey, @"string");

        keepLogSavedTimeInterval    = [keepLogSavedNumber boolValue];
        logToConsole                = [logToConsoleNumber boolValue];
        logToFile                   = [logToFileNumber boolValue];
        logToService                = [logToServiceNumber boolValue];
        flushToServerAutomatically  = [flushToServerAutomaticallyNumber boolValue];
        serverUrl                   = serverUrlString;
    }

    return self;
}

#pragma mark - Public getters

- (NSTimeInterval)keepLogAvailableInterval
{
    return keepLogSavedTimeInterval;
}

- (BOOL)logToFile
{
    return logToFile;
}

- (BOOL)logToConsole
{
    return logToConsole;
}

- (BOOL)logToService
{
    return logToService;
}

- (BOOL)flushLogsToServerAutomatically
{
    return flushToServerAutomatically;
}

- (NSString *)url
{
    return serverUrl;
}

@end


text:
#import "EC2SpotPriceUnmarshaller.h"

@implementation EC2SpotPriceUnmarshaller

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    [super parser:parser didStartElement:elementName namespaceURI:namespaceURI qualifiedName:qName attributes:attributeDict];

    if ([elementName isEqualToString:@"Error"]) {
        [parser setDelegate:[[[AmazonServiceExceptionUnmarshaller alloc] initWithCaller:self withParentObject:self.response withSetter:@selector(setException:)] autorelease]];
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    [super parser:parser didEndElement:elementName namespaceURI:namespaceURI qualifiedName:qName];

    if ([[elementName lowercaseString] isEqualToString:@"requestid"]) {
        if (parentObject != nil && [parentObject respondsToSelector:@selector(setRequestId:)]) {
            [parentObject performSelector:@selector(setRequestId:) withObject:self.currentText];
        }
    }

    if ([elementName isEqualToString:@"instanceType"]) {
        self.response.instanceType = self.currentText;
        return;
    }

    if ([elementName isEqualToString:@"productDescription"]) {
        self.response.productDescription = self.currentText;
        return;
    }

    if ([elementName isEqualToString:@"spotPrice"]) {
        self.response.spotPrice = self.currentText;
        return;
    }

    if ([elementName isEqualToString:@"timestamp"]) {
        self.response.timestamp = [AmazonSDKUtil convertStringToDate:self.currentText];
        return;
    }

    if ([elementName isEqualToString:@"availabilityZone"]) {
        self.response.availabilityZone = self.currentText;
        return;
    }

    if ([elementName isEqualToString:@"spotPrice"]) {
        if (caller != nil) {
            [parser setDelegate:caller];
        }

        if (parentObject != nil && [parentObject respondsToSelector:parentSetter]) {
            [parentObject performSelector:parentSetter withObject:self.response];
        }

        return;
    }
}

-(EC2SpotPrice *)response
{
    if (nil == response) {
        response = [[EC2SpotPrice alloc] init];
    }
    return response;
}

-(void)dealloc
{
    [response release];
    [super dealloc];
}

@end


text: > merely a small vpn sharer, not intended for others' use


text:
import sublime, sublime_plugin
import re

def transform_selection_regions(view, f, **kwargs):
    sel = view.sel()
    new_sel = [f(r, **kwargs) for r in sel]
    sel.clear()
    for r in new_sel:
        sel.add(r)

def remove_inner_parenthesis(s):
    ''' removes any inner parenthesis and also cuts off the string at the
        right hand side when the first non-matched ')' is reached '''
    characters = []
    num_lparen = 0
    for c in s:
        if c == '(':
            num_lparen += 1
        elif c == ')':
            num_lparen -= 1
            # stop if end of parameter list reached
            if num_lparen < 0:
                break
        if num_lparen:
            characters.append('_')
        else:
            characters.append(c)
    return ''.join(characters)

def remove_tail(s):
    # remove all characters after semicolon
    s = re.sub(r'(?s);.*', '', s)

    # if there are two adjacent identifiers with only whitespace containing
    # a newline inbetween, assume a right parenthesis is missing after
    # the first identifier and insert one (while preserving character offsets)
    def repl_func(m):
        non_identifiers = [
            'mod', 'div', 'and', 'or', 'xor', 'not', 'if',
            'unless', 'else', 'const',
        ]
        if (m.group(1) not in non_identifiers and m.group(3) not in non_identifiers
              and '\n' in m.group(2) or '\n' in m.group(2)):
            return ''.join([m.group(1), ')', m.group(2)[1:], m.group(3)])
        else:
            return m.group(0)
    s = re.sub(r'([a-zA-Z_0-9]+)(\s+)([a-zA-Z_0-9])', repl_func, s)

    return s

class ViExpandToArguments(sublime_plugin.TextCommand):

    def run(self, edit, outer=False, repeat=1, multiline=True):
        for i in range(repeat):
            transform_selection_regions(
                self.view, self.expand_region_to_argument,
                outer=outer, multiline=multiline
            )

    def expand_region_to_argument(self, region, outer=False, multiline=True):
        # determine where the cursor is placed and what surrounding
        # text fragment region to consider
        pt = region.a
        r = self.view.line(pt)
        if multiline:
            last_line = self.view.rowcol(self.view.size()-1)[0]
            line_no = self.view.rowcol(pt)[0]
            # make the region of interest span 10 lines backwards and forwards
            l_beg, l_end = (max(0,         line_no-10),
                            min(last_line, line_no+10))
            r = self.view.line(self.view.text_point(l_beg, 0)).cover(
                self.view.line(self.view.text_point(l_end, 0)))
            # limit the region just in case the lines are very long
            r = r.intersection(sublime.Region(pt - 4000, pt + 4000))

        # extract the surrounding text and determine the offset
        # from the start of it where the cursor is placed
        s = self.view.substr(r)
        cursor_offset = pt - r.a

        # replace literal strings by placeholders so that offsets are
        # preserved but parenthesis and commmas within strings do not
        # affect the later steps
        s = s.replace("\\'", '_').replace('\\"', '!')  # remove string escape codes
        s = re.sub(r'(?s)""".*?"""', lambda m: '!' * len(m.group(0)), s)
        s = re.sub(r"(?s)'''.*?'''", lambda m: '!' * len(m.group(0)), s)
        s = re.sub(r'".*?"', lambda m: '!' * len(m.group(0)), s)
        s = re.sub(r"'.*?'", lambda m: '!' * len(m.group(0)), s)

        # find offsets to the start of all non-empty argument lists that
        # precede the cursor
        offsets = [m.start(1) for m in re.finditer(
            r'(?x)[a-zA-Z0-9_]+[!?]? \s* \( ( (?!\s*\))[^)] )', s)
            if m.start(1) <= cursor_offset]
        if offsets:
            # pick the last argument list offset
            offset = offsets[-1]
            args_str = s[offset:]

            # trim the right part of the string at semicolons and at suspected
            # missing right parenthesis in order to decrease the risk that we
            # we go too far to the right.
            args_str = remove_tail(args_str)

            # remove any inner parenthesis: "a*min(b, c), d" ==> "a*min______, d"
            args_str = remove_inner_parenthesis(args_str)

            # find arguments by splitting at commas
            args = re.findall(r'[^,]+,?\s*|,\s*', args_str)

            # find the argument that matches the cursor offset
            i = offset
            for arg_i, arg in enumerate(args):
                if cursor_offset <= i + len(arg.rstrip(', ')):
                    # create a region that covers this argument
                    if not outer:
                        arg = arg.rstrip(', \t\r\n')
                    a = region.a - (cursor_offset - i)
                    b = a + len(arg)

                    # if the argument is the last one and outer mode is on,
                    # expand to the left to cover any whitespace or commas
                    if outer and arg_i == len(args)-1: #self.view.substr(b) == ')':
                        while self.view.substr(a - 1) in ', \t\r\n':
                            a -= 1

                    return sublime.Region(a, b)
                else:
                    i += len(arg)

        return region


text:
function solve(args){
'use strict';
let numbers = args[0].split(' ').map(Number);
let best = -1, current = 0;

    numbers.forEach((number,index,all) =>{
        current += number;//agregation
        // def: start is the end
        if(index === 0) {return ;}
        //def: reached end
        else if(index === all.length - 1){
            best = Math.max(best,current);
            return;
        }
        //def: dependancy :neighbours
        let prev = all[index-1],
            next = all[index+1];
        //def: main condition :reached condition for re-eval
        if(number>prev && number>next){//peak reached
            best = Math.max(best,current);
            current = number; // reset of agregation
        }
    });

    console.log(best);

}

solve([
    "5 1 7 4 8"
]);

function checker(args){
    for(let a of args){
        console.log(a);
    }
}
// Solutions :
//https://github.com/TelerikAcademy/JavaScript-Fundamentals/blob/master/Exams/2015-06-11-Variant-2/1.%20Hills/solution.js

//NB:
// abstract
    // defragment the logic
        // end conditions
            // mark dependancies
        // main conditions
    // look for the reseters in each condition

/// relax and keep asking Structured(main logic ? main condition ? edge conditions ? dependencies ? what is needed in each ?) Question