text:
Lighthouse is the SDK that connects Passworks.io beacons service ([http://beacons.passworks.io](http://beacons.passworks.io)) to your iOS application.
In the Passworks.io dashboard you can add your own beacons, manage your tags (premises/virtual areas) and the events associated with beacon entry or exit.

> Please be advised that the current SDK is in beta so it's not production ready and features my change in the future without notice.

> While in beta if you wish to receive notifications about new builds of the SDK please send an e-mail to support@passworks.io

## Integration

Drag `Lighthouse.bundle` and `Lighthouse.framework` to 'Frameworks' in your workspace. If prompted, check the "Copy items to destination's group folder" checkbox to make sure the framework and the resources are copied to your project.

## Setup

### Step 1 - SDK Setup

To setup the SDK all you are required to do is call `setupWithToken:` on your application's `AppDelegate` subclass on the `application:didFinishLaunchingWithOptions:` method.

Objective-C:
```objective-c
- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [Lighthouse setupWithToken:@"YOUR-APP-TOKEN"];
  // The rest of your code goes here...
}
```

Swift:

```swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  Lighthouse.setupWithToken("YOUR-APP-TOKEN")
  // The rest of your code goes here...
}
```

### Step 2 - Core Location Permission

To make sure your application can scan for beacons when it is on background, you will also be required to add `NSLocationAlwaysUsageDescription` value to your applications's `Info.plist`. The value is the message displayed on the popup prompting the user to give permission.

![Core Location Prompt](documentation/images/core-location-always-authorization.png)

### Step 3 - Background Modes

To make sure your application can trigger events on nearby beacons while it is in background, you need to give it permission for running in the background, the two modes required are `Location updates` and `Uses Bluetooth LE accessories`.

![Background Modes](documentation/images/background-modes.png)

## Beacon Scanning

### Starting

Lighthouse allows your app to be on the lookout for nearby beacons, as such, it requires you to turn on the beacon scanning feature by calling the `lightUp` method on Lighthouse.

Objective-C:

```objective-c
[[Lighthouse sharedInstance] lightUp];
```

Swift:

```swift
Lighthouse.sharedInstance().lightUp()
```

This method call will trigger the Core Location Permission popup in case you have not asked the user for permission beforehand.

### Stopping

In case you want to stop ranging for beacons, you can call the `turnOff` method which will then stop all location based beacon ranging.

```objective-c
[[Lighthouse sharedInstance] turnOff];
```

```swift
Lighthouse.sharedInstance().turnOff()
```

### Updating

Lighthouse updates its database in several cases, when the SDK is setup, when the application returns to foreground or when an explicit call to `refresh` is triggered. This will then refresh all the beacons, events and tags set in the Passworks.io dashboard.

Objective-C:

```objective-c
[[Lighthouse sharedInstance] refresh];
```

Swift:

```swift
Lighthouse.sharedInstance().refresh()
```

### Delegating

Lighthouse will adopt the behavior defined in the Passworks.io dashboard, so any events will be triggered in the background without requiring any aditional code from you. But for a more advanced usage, Lighthouse supports a delegating protocol for more precise control over functionality.

To set a delegate just set the property on the SDK.

Objective-C:

```objective-c
[Lighthouse sharedInstance].delegate = self;
```

Swift:
```swift
Lighthouse.sharedInstance().delegate = self
```

The object being assigned needs to conform to the `LHDelegate` protocol. All the protocol's interface is optional, so not all the methods need to be implemented.

`lighthouseBeaconsRefreshed:` is called when the database is updated from any of the ways mentioned before (see the **Updating** section)

`lighthouseBeaconDidChangeProximity:` is called when a nearby beacon changes it proximity between either 2 of these: `CLProximityImminent`, `CLProximityNear`, `CLProximityFar` or `CLProximityUnknown`.

`lighthouseEventTriggered:onBeacon` is called when an `LHEvent` is triggered by entering or exiting a given proximity of a `LHBeacon`. These events need to be mapped on the Passworks.io dashboard to be triggered.

`lighthouseShouldTriggerEvent:onBeacon:` is a delegate method to allow a better control of how the SDK should function, by default, the SDK triggers on any event occurring, you can return `false` to avoid triggering certain events.

### In App Behavior

By default, Lighthouse only triggers `UILocalNotifications` when the application is in background, because iOS does not support showing notifications when the application is in foreground. To allow better control over this caveat, Lighthouse allows triggering `UIAlertViews` corresponding to the notifications while the application is in foreground. This can be set through the `triggerAlertViewInForeground` property.

```objective-c
[Lighthouse sharedInstance].triggerAlertViewInForeground = YES;
```

```swift
Lighthouse.sharedInstance().triggerAlertViewInForeground = true
```

## Analytics

Lighthouse allows user tracking to get the best out of the analytics on top of the beacons solution. In order to identify the users to the Lighthouse SDK, you can call the `identifyUser`, `identifyUser:`, `identifyUser:attributes:` and `logout` methods.

`identifyUser` will trigger an annonymous identification (in case your application does not require your users to login and signup).

`identifyUser:` will take a `userId` for identification (which can be an e-mail, a username or even an actual id).

`identifyUser:attributes:` allows you to identify a user through a `userId` as well as receiving a dictionary of user attributes which may contain all the user information you want.

`logout` forces a previously identified user to become anonymous again. (same behavior as `identifyUser`)

## Database

Lighthouse allows you to dig into the database which is composed by `LHBeacons`, `LHTags` and `LHEvents`.

The Lighthouse `sharedInstance` contains properties for `beacons`, `beaconsInRange`, `tags` and `events`. These represent arrays of their corresponding object models mentioned above.

### LHTag

The `LHTag` model represents the tags associated with beacons, in order to create **sessions**. It is composed by:

- `identifier`: Int - the tag identifier in Passworks.io.
- `name`: String - the tag name.
- `timeout`: Int - the timeout for closing sessions.
- `lastSeenAt`: NSDate - the timestamp for the last time the tag was found.
- `sessionId`: String - a unique session identifier randomly generated.

### LHBeacon

The `LHBeacon` model represents the physical beacons and is composed by:

- `identifier`: Int - the beacon identifier in Passworks.io.
- `name`: String - the beacon name.
- `uuid`: String - the UUID set in the physical beacon.
- `major`: Int - the major identifier set in the physical beacon.
- `minor`: Int - the minor identifier set in the physical beacon.
- `vendorName`: String - the name of the beacon's vendor.
- `vendorSlug`: String - the slug of the beacon's vendor.
- `tags`: [LHTag] - an array containing all the associated `LHTag` objects.
- `events`: [LHEvent] - an array containing all the associated `LHEvent` objects.
- `proximity`: CLProximity - the current proximity of the beacon.

### LHEvent

The `LHEvent` model represents the behavior of the Lighthouse framework when it encounters a `LHBeacon`. When certain conditions align the `LHEvent` should be triggered and a notification will be shown to the user. The model is composed by:

- `identifier`: Int - the event identifier in Passworks.io.
- `name`: String - the event name.
- `proximity`: CLProximity - the proximity in which the event should be triggered.
- `triggerOn`: LHEventTrigger - a switch between `Enter` or `Exit` in which the event should be triggered.
- `triggerOnce`: Bool - `true` in case the event should only be triggerd if it has passed the maximum `timeout` for all the tags associated with the beacon's tags, `false` in case it should consider its timeout as the `timeout`
- `type`: LHEventType - a switch between `URL`, `Notification`, `Webhook`, `Image` and `Passbook`, which will correspond to the action to take when the user opens up the local notification triggered by the event.
- `triggeredAt`: NSDate - a timestamp for when the event was last triggered.
- `timeout`: Int - the timeout to which the framework should not trigger multiple times the same event.
- `payload`: String - the content to use in the notification action.
- `notificationMessage`: String - the message to be presented to the user on the notification.

## Logging

Lighthouse allows the developer to choose whether to display logs or not, this can be set with the `setVerbose:` call. Verbose mode is enabled by default in debug builds and disabled otherwise.

Objective-C:

```objective-c
[Lighthouse setVerbose:YES];
```

Swift:

```swift
Lighthouse.setVerbose(true)
```

## Help us make it better

Please tell us how we can make the SDK better. If you have a specific feature request or if you found a bug, please use GitHub issues. Fork these docs and send a pull request with improvements.

To talk with us and other developers about the SDK [open a support ticket](https://github.com/passworks/lighthouse-ios-sdk/issues) or mail us at `api at passworks.io` if you need to talk to us.


text:
package com.microsoft.bingads.v10.bulk.entities;

import com.microsoft.bingads.v10.internal.bulk.StringExtensions;
import com.microsoft.bingads.v10.internal.bulk.StringTable;
import com.microsoft.bingads.v10.campaignmanagement.Ad;
import com.microsoft.bingads.v10.campaignmanagement.AdEditorialStatus;
import com.microsoft.bingads.v10.campaignmanagement.AdStatus;
import com.microsoft.bingads.v10.campaignmanagement.ArrayOfstring;
import com.microsoft.bingads.v10.campaignmanagement.TextAd;
import com.microsoft.bingads.v10.internal.bulk.BulkMapping;
import com.microsoft.bingads.v10.internal.bulk.MappingHelpers;
import com.microsoft.bingads.v10.internal.bulk.RowValues;
import com.microsoft.bingads.v10.internal.bulk.SimpleBulkMapping;
import com.microsoft.bingads.v10.internal.bulk.entities.SingleRecordBulkEntity;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.internal.functionalinterfaces.Function;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * This abstract base class provides properties that are shared by all bulk ad classes.
 *
 * @param <T> the type of ad from the {@link com.microsoft.bingads.campaignmanagement} namespace, for example
 *           {@link TextAd} object.
 *
 * @see BulkMobileAd
 * @see BulkProductAd
 * @see BulkTextAd
 */
class BulkAd<T extends Ad> extends SingleRecordBulkEntity {

    private Long adGroupId;

    private String campaignName;

    private String adGroupName;

    protected T ad;

    private PerformanceData performanceData;

    private static final List<BulkMapping<BulkAd>> MAPPINGS;

    static {
        List<BulkMapping<BulkAd>> m = new ArrayList<BulkMapping<BulkAd>>();

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.Status,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return c.getAd().getStatus() != null ? c.getAd().getStatus().value() : null;
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.getAd().setStatus(StringExtensions.<AdStatus>parseOptional(v, new Function<String, AdStatus>() {
                            @Override
                            public AdStatus apply(String value) {
                                return AdStatus.fromValue(value);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, Long>(StringTable.Id,
                new Function<BulkAd, Long>() {
                    @Override
                    public Long apply(BulkAd c) {
                        return c.getAd().getId();
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.getAd().setId(StringExtensions.<Long>parseOptional(v, new Function<String, Long>() {
                            @Override
                            public Long apply(String value) {
                                return Long.parseLong(value);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, Long>(StringTable.ParentId,
                new Function<BulkAd, Long>() {
                    @Override
                    public Long apply(BulkAd c) {
                        return c.getAdGroupId();
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.setAdGroupId(StringExtensions.<Long>parseOptional(v, new Function<String, Long>() {
                            @Override
                            public Long apply(String value) {
                                return Long.parseLong(value);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.Campaign,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return c.getCampaignName();
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.setCampaignName(v);
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.AdGroup,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return c.getAdGroupName();
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.setAdGroupName(v);
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.EditorialStatus,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd t) {
                        return t.getAd().getEditorialStatus() != null ? t.getAd().getEditorialStatus().value() : null;
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.getAd().setEditorialStatus(StringExtensions.<AdEditorialStatus>parseOptional(v, new Function<String, AdEditorialStatus>() {
                            @Override
                            public AdEditorialStatus apply(String value) {
                                return AdEditorialStatus.fromValue(value);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.DevicePreference,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return StringExtensions.toDevicePreferenceBulkString(c.getAd().getDevicePreference());
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.getAd().setDevicePreference(StringExtensions.parseDevicePreference(v));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.FinalUrl,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return StringExtensions.writeUrls("; ", c.getAd().getFinalUrls());
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                    	ArrayOfstring urls = new ArrayOfstring();
                    	List<String> urlArray = StringExtensions.parseUrls(v);
                    	if(urlArray == null) {
                    		urls = null;
                    	} else {
                    		urls.getStrings().addAll(urlArray);
                    	}
                    	c.getAd().setFinalUrls(urls);
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.FinalMobileUrl,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return StringExtensions.writeUrls("; ", c.getAd().getFinalMobileUrls());
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                    	ArrayOfstring urls = new ArrayOfstring();
                    	List<String> urlArray = StringExtensions.parseUrls(v);
                    	if(urlArray == null) {
                    		urls = null;
                    	} else {
                    		urls.getStrings().addAll(urlArray);
                    	}
                		c.getAd().setFinalMobileUrls(urls);
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.TrackingTemplate,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return StringExtensions.toOptionalBulkString(c.getAd().getTrackingUrlTemplate());
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        c.getAd().setTrackingUrlTemplate(StringExtensions.getValueOrEmptyString(v));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkAd, String>(StringTable.CustomParameter,
                new Function<BulkAd, String>() {
                    @Override
                    public String apply(BulkAd c) {
                        return StringExtensions.toCustomParaBulkString(c.getAd().getUrlCustomParameters());
                    }
                },
                new BiConsumer<String, BulkAd>() {
                    @Override
                    public void accept(String v, BulkAd c) {
                        try {
							c.getAd().setUrlCustomParameters(StringExtensions.parseCustomParameters(v));
						} catch (Exception e) {
							e.printStackTrace();
						}
                    }
                }
        ));

        MAPPINGS = Collections.unmodifiableList(m);
    }

    ;

    @Override
    public void processMappingsToRowValues(RowValues values, boolean excludeReadonlyData) {
        MappingHelpers.<BulkAd>convertToValues(this, values, MAPPINGS);

        if (!excludeReadonlyData) {
            PerformanceData.writeToRowValuesIfNotNull(performanceData, values);
        }
    }

    @Override
    public void processMappingsFromRowValues(RowValues values) {
        MappingHelpers.<BulkAd>convertToEntity(values, MAPPINGS, this);

        performanceData = PerformanceData.readFromRowValuesOrNull(values);
    }

    /**
     * Gets the identifier of the ad group that contains the ad.
     *
     *

     *     Corresponds to the 'Parent Id' field in the bulk file.
     *

     */
    public Long getAdGroupId() {
        return adGroupId;
    }

    /**
     * Gets the name of the campaign that contains the ad.
     *
     *

     *     Corresponds to the 'Campaign' field in the bulk file.
     *

     */
    public String getCampaignName() {
        return campaignName;
    }

    /**
     * Gets the name of the ad group that contains the ad.
     *
     *

     *     Corresponds to the 'Ad Group' field in the bulk file.
     *

     */
    public String getAdGroupName() {
        return adGroupName;
    }

    /**
     * Gets the ad from the {@link com.microsoft.bingads.campaignmanagement} namespace,
     */
    public T getAd() {
        return ad;
    }

    /**
     * Gets the historical performance data for the ad.
     */
    public PerformanceData getPerformanceData() {
        return performanceData;
    }

    /**
     * Sets the identifier of the ad group that contains the ad.
     *
     *

     *     Corresponds to the 'Parent Id' field in the bulk file.
     *

     */
    public void setAdGroupId(Long adGroupId) {
        this.adGroupId = adGroupId;
    }

    /**
     * Sets the ad from the {@link com.microsoft.bingads.campaignmanagement} namespace,
     */
    public void setAd(T ad) {
        this.ad = ad;
    }

    /**
     * Sets the name of the campaign that contains the ad.
     *
     *

     *     Corresponds to the 'Campaign' field in the bulk file.
     *

     */
    public void setCampaignName(String campaignName) {
        this.campaignName = campaignName;
    }

    /**
     * Sets the name of the ad group that contains the ad.
     *
     *

     *     Corresponds to the 'Ad Group' field in the bulk file.
     *

     */
    public void setAdGroupName(String adGroupName) {
        this.adGroupName = adGroupName;
    }

}

redpajama_set_name: RedPajamaGithub


text:
// $Id$

#ifndef INC_ERR_Macros_H
#define INC_ERR_Macros_H

/*!
\file ERR_Macros.h
\brief Basic error handler
*/

#include <xlw/port.h>

#ifdef PORT_PRAGMA
    #pragma once
#endif

#include <windows.h>
#ifdef PORT_USE_OLD_IO_HEADERS
    #ifdef PORT_NO_LONG_FILE_NAMES
        #include <strstrea.h>
    #else
        #include <strstream.h>
    #endif
#else
    #include <strstream>
#endif

//! Log a message to the user interface.
/*!
You can customize the output of the error message (currently a message box) and
use your own error handling mechanism.
*/
#if defined(NDEBUG) || !defined(_MSC_VER)
    #define ERR_LOG_INTERNAL(msg) ::MessageBox(0,msg,"C++ Excel32 wrapper Log",MB_OK)
#else
    #define ERR_LOG_INTERNAL(msg) OutputDebugString(msg)
#endif

//! Converts a data stream to a 0-terminated string and passes it the LOG macro.
/*!
\param message Whatever type (or serie of types) that has a stream
operator defined. For instance, you could use it like
\code double f=0.0;
ERR_LOG("Here the value of f is \"" << f << "\"");
\endcode

\warning The buffer has a limited size set to 1024 bytes.
The line might be troncated if it is too long.

The enclosing
\code if (true) { ... } else \endcode
is designed to avoid warning in condition code like the following. See
\ref CppFaqLite.
\code
if (...)
  ERR_LOG();
\endcode
*/
#define ERR_LOG(message) if (true) \
{ \
	char tmp___[1024]; \
	ostrstream os____(tmp___,1024); \
	os____ << __FILE__ << "(" << __LINE__ << "): " << message << '\n' << ends; \
	ERR_LOG_INTERNAL(tmp___); \
} else

//! Wrapper for the try keyword.
#define ERR_TRY try
//! Wrapper for catch keyword.
#define ERR_CATCH catch
//! Wrapper for throw keyword without argument.
/*!
You might use it to forward an exception further up in the call stack
after it's been catched by a catch block.
*/
#define ERR_RETHROW throw
//! Wrapper for cathing an exception and forward it immediately
#define ERR_CATCH_AND_THROW { }
//! Wrapper for a catch of all exceptions.
#define ERR_CATCH_ALL catch (...)
//! Wrapper for the throw of an exception with message.
/*! Adds the name of the exception thrown and calls ERR_LOG() macro
    with the message.
	\sa ERR_LOG()
*/

#define ERR_THROW_MSG(except, message) if (true) \
{ \
	char tmp__[1024]; \
	ostrstream os___(tmp__,1024); \
	os___ << message << ends; \
	ERR_LOG("EXCEPTION (" #except ") : " << message); \
	throw except(tmp__); \
} else

//! Wrapper for throw of an exception without message.
#define ERR_THROW(exception) { throw exception(); }
//! Wrapper for assertion test.
/*!
Checks if \e condition is \c true. If not, calls ERR_THROW_MSG() with
\e exception and \e message as arguments.
These assertions are \e not \e removed for \e release versions.
\sa ERR_THROW_MSG()
\bug In conditional statement, see ERR_LOG().
*/
#define ERR_CHECKX(condition, exception, message) if (!(condition)) \
{ ERR_THROW_MSG(exception, message); }

//! Wrapper for warning message sending.
/*! Forward the message to ERR_LOG() prefixed by the text "WARNING :".
	\sa ERR_LOG()
	\bug In conditional statement, see ERR_LOG().
*/
#define ERR_LOGW(message) { ERR_LOG("WARNING : " << message); }

//! Wrapper for warning test.
/*!
Checks if \e condition is \c true. If not, calls ERR_LOGW() with
\e message as arguments.
These assertions \b still \b hold for \e release versions.
\sa ERR_LOGW().
\bug In conditional statement, see ERR_LOG().
*/
#define ERR_CHECKW(condition, msg) if (!(condition)) \
{ ERR_LOGW(msg); }

#ifndef NDEBUG
//! Same as ERR_CHECKX(), removed from code if NDEBUG is not defined.
#define ERR_CHECKX2(condition, exception, message) ERR_CHECKX(condition, exception, "(DBG) " << message)
//! Same as ERR_CHECKW(), removed from code if NDEBUG is not defined.
#define ERR_CHECKW2(condition, msg) ERR_CHECKW(condition, "(DBG) " << msg)
//! Same as ERR_LOGW(), removed from code if NDEBUG is not defined.
#define ERR_LOGW2(msg) ERR_LOGW("(DBG) " << msg)
//! Same as ERR_LOG(), removed from code if NDEBUG is not defined.
#define ERR_LOG2(msg) ERR_LOG("(DBG) " << msg)
#else
#define ERR_CHECKX2(condition, exception, message)
#define ERR_CHECKW2(condition, message)
#define ERR_LOGW2(msg)
#define ERR_LOG2(msg)
#endif // DEBUG

#endif


text:
import random
from urllib import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
    "class %%%(%%%):":
      "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef __init__(self, ***)" :
      "class %%% has-a __init__ that takes self and *** parameters.",
    "class %%%(object):\n\tdef ***(self, @@@)":
      "class %%% has-a function named *** that takes self and @@@ parameters.",
    "*** = %%%()":
      "Set *** to an instance of class %%%.",
    "***.***(@@@)":
       "From *** get the *** function, and call it with parameters self, @@@.",

}

# do they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST = True

# load up the words from the website
# opens the website and reads text lines striped of spaces
# and appends to the WORDS list
for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())

def convert(snippet, phrase):
    # using list comprehension function capitalize every randomly picked class name from WORDS list
    # the number of words is determined by the "snippet.count()" function from the random module
    class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]

    print class_names # debug statement

    # using random function pick randomly selected WORDS list elements, using "snippet.count()"
    # as the basis for the number picked
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    # generate parameter names based on the random number between 1 and 3
    # and place them in list "param_names" separated by a "," character
    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    # assign the contents or value of snippet and phrase to variable "result"
    """ Run this whole set function for both "snippet and phrase"
        changing the "%%%", "@@@", and "***" string to elements of
        class_names, other_names, and param_names as created above """
    for sentence in snippet, phrase:
        result = sentence[:]

        # fake class names
        for word in class_names:
            result = result.replace("%%%", word, 1) # replace the "%%%" string in snippet with the generated class names

        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)

        # fake paramter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

# keep going until they hit CTRL-D

try:
    while True: # continue this operation until no more data, hence becomes false
        snippets = PHRASES.keys() # set the "key" variable in PHRASES to snippets
        random.shuffle(snippets) # shuffle these "keys"

        for snippet in snippets: # name every snippet(key) snippet
            phrase = PHRASES[snippet] # assign the value of each key(in dictionary PHRASES) as snippet in snippets to phrase
            question, answer = convert(snippet, phrase) # assign "snippet to question" and "phrase to answer"

            # if you enter "english" argument at the commandline, then the if statement runs
            # this interchanges the question making it an answer and vice versa
            if PHRASE_FIRST:
                question, answer = answer, question

            print question

            raw_input("> ")
            print "ANSWER:  %s\n\n" % answer
except EOFError:
    print "\nBye"


text:
package net.ripe.db.whois.api.whois;

import net.ripe.db.whois.update.domain.Origin;

public class InternalJob implements Origin {
    private final String id;

    public InternalJob(final String id) {
        this.id = id;
    }

    @Override
    public boolean isDefaultOverride() {
        return true;
    }

    @Override
    public boolean allowAdminOperations() {
        return true;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getFrom() {
        return id;
    }

    @Override
    public String getResponseHeader() {
        return "Maintenance job: " + getFrom() + "\n";
    }

    @Override
    public String getNotificationHeader() {
        return getResponseHeader();
    }

    @Override
    public String getName() {
        return "maintenance job";
    }

    @Override
    public String toString() {
        return "InternalJob(" + getId() + ")";
    }
}


text:
//
//  KTextView.m
//  kedashixunDemo
//
//  Created by KZL on 16/5/16.
//  Copyright © 2016年 wangbing. All rights reserved.
//

#import "KTextView.h"
#import "UIView+Extension.h"
#import "UIColor+HexColor.h"

@interface KTextView ()

@property (nonatomic , strong) UILabel *placeholderLabel;

@end

@implementation KTextView

- (instancetype)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super initWithCoder:aDecoder]) {
        self.backgroundColor = [UIColor clearColor];

        //添加一个现实提醒文字的label
        UILabel *placehoderLabel = [[UILabel alloc] init];
        placehoderLabel.numberOfLines = 0;
        placehoderLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:placehoderLabel];

        self.placeholderLabel = placehoderLabel;

        //设置默认文字颜色
        self.placeholderColor = [UIColor colorWithHexString:@"#BBBBBB"];

        //设置默认字体
        self.font = [UIFont systemFontOfSize:17];

        //监听内部文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];

        //为textview添加一个手势
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewOnClick)];
        [self addGestureRecognizer:gesture];

    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {

        self.backgroundColor = [UIColor clearColor];

        //添加一个现实提醒文字的label
        UILabel *placehoderLabel = [[UILabel alloc] init];
        placehoderLabel.numberOfLines = 0;
        placehoderLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:placehoderLabel];

        self.placeholderLabel = placehoderLabel;

        //设置默认文字颜色
        self.placeholderColor = [UIColor colorWithHexString:@"#666666"];

        //设置默认字体
        self.font = [UIFont systemFontOfSize:17];

        //监听内部文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];

        //为textview添加一个手势
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewOnClick)];
        [self addGestureRecognizer:gesture];
    }

    return self;
}

- (void)textViewOnClick {

    [self becomeFirstResponder];

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 监听文字改变
- (void)textDidChange{

    self.placeholderLabel.hidden = self.hasText;
}

#pragma mark - 公共方法
- (void)setText:(NSString *)text {

    [super setText:text];
    [self textDidChange];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {

    [super setAttributedText:attributedText];
    [self textDidChange];
}

- (void)setPlaceholder:(NSString *)placeholder {

    _placeholder = placeholder;
    //设置文字
    self.placeholderLabel.text = placeholder;
    //重新计算子控件frame
    [self setNeedsLayout];

}

-(void)setPlaceholderColor:(UIColor *)placeholderColor {

    _placeholderColor = placeholderColor;
    self.placeholderLabel.textColor = placeholderColor;

}

- (void)setFont:(UIFont *)font {
    [super setFont:font];
    self.placeholderLabel.font = font;

    [self setNeedsLayout];
}

- (void)layoutSubviews {

    [super layoutSubviews];

    self.placeholderLabel.y = 8;
    self.placeholderLabel.x = 5;
    self.placeholderLabel.width = self.width - 2 * self.placeholderLabel.x ;

    CGSize maxSize = CGSizeMake(self.placeholderLabel.width, MAXFLOAT);

    NSDictionary *dict = @{NSFontAttributeName: [UIFont systemFontOfSize:17]};
    CGSize textSize = [self.placeholder boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;

    self.placeholderLabel.height = textSize.height;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
from libcloud.utils import deprecated_warning

from libcloud.compute.drivers.cloudsigma import *

deprecated_warning(__name__)


text:
<?php

namespace PHPExiftool\Driver\Tag\Microsoft;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class WMContentID extends AbstractTag
{

    protected $Id = 'WM/WMContentID';

    protected $Name = 'WMContentID';

    protected $FullName = 'Microsoft::Xtra';

    protected $GroupName = 'Microsoft';

    protected $g0 = 'QuickTime';

    protected $g1 = 'Microsoft';

    protected $g2 = 'Video';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'WM Content ID';
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/test_activity"
        android:title="Test"
        app:showAsAction="never"
        tools:ignore="HardcodedText" />
</menu>


text:
<?php
/**
 * SpeechSegmentResponse
 *
 * PHP version 5
 *
 * @category Class
 * @package  Systran\Client
 * @author   http://github.com/Systran-api/Systran-codegen
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link
 */
/**
 *  Copyright 2015 SmartBear Software
 *
 *  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.
 */
/**
 *
 *
 * Do not edit the class manually.
 */

namespace Systran\Client;

use \ArrayAccess;
/**
 * SpeechSegmentResponse Class Doc Comment
 *
 * @category    Class
 * @description Response of a Speech Segment request
 * @package     Systran\Client
 * @author      http://github.com/Systran-api/Systran-codegen
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link
 */
class SpeechSegmentResponse implements ArrayAccess
{
    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    static $SystranTypes = array(
        'error' => '\Systran\Client\ErrorResponse',
        'channels' => '\Systran\Client\SpeechChannel[]',
        'speakers' => '\Systran\Client\SpeechSpeaker[]',
        'segments' => '\Systran\Client\SpeechSegment[]'
    );

    /**
      * Array of attributes where the key is the local name, and the value is the original name
      * @var string[]
      */
    static $attributeMap = array(
        'error' => 'error',
        'channels' => 'channels',
        'speakers' => 'speakers',
        'segments' => 'segments'
    );

    /**
      * Array of attributes to setter functions (for deserialization of responses)
      * @var string[]
      */
    static $setters = array(
        'error' => 'setError',
        'channels' => 'setChannels',
        'speakers' => 'setSpeakers',
        'segments' => 'setSegments'
    );

    /**
      * Array of attributes to getter functions (for serialization of requests)
      * @var string[]
      */
    static $getters = array(
        'error' => 'getError',
        'channels' => 'getChannels',
        'speakers' => 'getSpeakers',
        'segments' => 'getSegments'
    );

    /**
      * $error Error at request level
      * @var \Systran\Client\ErrorResponse
      */
    protected $error;

    /**
      * $channels Array of channels
      * @var \Systran\Client\SpeechChannel[]
      */
    protected $channels;

    /**
      * $speakers Array of speakers
      * @var \Systran\Client\SpeechSpeaker[]
      */
    protected $speakers;

    /**
      * $segments Array of segments
      * @var \Systran\Client\SpeechSegment[]
      */
    protected $segments;

    /**
     * Constructor
     * @param mixed[] $data Associated array of property value initalizing the model
     */
    public function __construct(array $data = null)
    {
        if ($data != null) {
            $this->error = $data["error"];
            $this->channels = $data["channels"];
            $this->speakers = $data["speakers"];
            $this->segments = $data["segments"];
        }
    }

    /**
     * Gets error
     * @return \Systran\Client\ErrorResponse
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * Sets error
     * @param \Systran\Client\ErrorResponse $error Error at request level
     * @return $this
     */
    public function setError($error)
    {

        $this->error = $error;
        return $this;
    }

    /**
     * Gets channels
     * @return \Systran\Client\SpeechChannel[]
     */
    public function getChannels()
    {
        return $this->channels;
    }

    /**
     * Sets channels
     * @param \Systran\Client\SpeechChannel[] $channels Array of channels
     * @return $this
     */
    public function setChannels($channels)
    {

        $this->channels = $channels;
        return $this;
    }

    /**
     * Gets speakers
     * @return \Systran\Client\SpeechSpeaker[]
     */
    public function getSpeakers()
    {
        return $this->speakers;
    }

    /**
     * Sets speakers
     * @param \Systran\Client\SpeechSpeaker[] $speakers Array of speakers
     * @return $this
     */
    public function setSpeakers($speakers)
    {

        $this->speakers = $speakers;
        return $this;
    }

    /**
     * Gets segments
     * @return \Systran\Client\SpeechSegment[]
     */
    public function getSegments()
    {
        return $this->segments;
    }

    /**
     * Sets segments
     * @param \Systran\Client\SpeechSegment[] $segments Array of segments
     * @return $this
     */
    public function setSegments($segments)
    {

        $this->segments = $segments;
        return $this;
    }

    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->$offset);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return $this->$offset;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        $this->$offset = $value;
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->$offset);
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) {
            return json_encode(get_object_vars($this), JSON_PRETTY_PRINT);
        } else {
            return json_encode(get_object_vars($this));
        }
    }
}


text:
<?=Language::invokeOutput('savingDraft');?> <img src="<?=URL;?>img/loader.gif" alt="loader">

            <form action="ajax/sendMessage" method="POST" class="ajax inboxDraft">

<?=Language::invokeOutput('create/message')?>

                    <img src="<?=URL;?>/img/loader.gif" alt="ajax-loader"/>

                    <?php
                        if (!empty($data['user']))
                        {
                            echo '<input type="hidden" name="receiver" id="uniqueReciever" value="'.$data['user']->id.'"/>';
                            echo "id}' class='receiverHolder'>{$data['user']->username}";
                        }
                        else
                        {?>
                            <input type="text" name="receiver" id="getReceiver" placeholder="<?=Language::invokeOutput('placeholder/receiver');?>" class="col-2 draftTrigger" />

                        <?php } ?>

                    <input type="text" name="title" placeholder="<?=Language::invokeOutput('placeholder/message');?>" class="col-12 draftTrigger" />

                    <textarea name="content" class="col-12 bse draftTrigger" rows="17" placeholder="<?=Language::invokeOutput('content/message');?>"></textarea>

                    <input type="hidden" name="token" value="<?=$global['token'];?>" />
                    <input type="hidden" name="draft" value="<?=$data['draft'];?>">
                    <?=Language::invokeOutput('submit/message');?> <i class="icon-<?=DIRECTION;?>">

            </form>

<?php Controller::$GLOBAL['draftVariable'] = true; ?>


text:
<?php

/**
 * Authenticator for Built in Accounts
 * @author  Minh Duc Nguyen <minh.nguyen@ands.org.au>
 */
require_once('engine/models/authenticator.php');
class Built_in_authenticator extends Authenticator {

	public function authenticate() {
		// sleep(2);
		$this->auth_domain = gPIDS_IDENTIFIER_SUFFIX;

		$result = $this->cosi_db->get_where('roles',
			array('role_id' => $this->params['username'])
		);

		if($result->num_rows()==0) throw new Exception('Login failed: Role "'. $this->params['username']. '" is not recognised');

		$result = $this->cosi_db->get_where('authentication_built_in',
			array(
				'role_id' => $this->params['username'],
				'passphrase_sha1' => sha1($this->params['password'])
			)
		);

		if($result->num_rows()==0) throw new Exception('Login failed: Bad credentials');

		$user = $result->row(1);
		$this->return_roles($user);
	}

	public function redirect_hook($to) {}
}


text:
How to install django-cron
==========================

1. Put ``django_cron`` into your python path
2. Add ``django_cron`` to ``INSTALLED_APPS`` in your ``settings.py`` file
3. Add the following code to the beginning of your ``urls.py`` file (just after the imports):

   .. code-block:: python

	    import django_cron
	    django_cron.autodiscover()

4. Create a file called ``cron.py`` inside each installed app that you want to add a recurring job to. The app must be installed via the ``INSTALLED_APPS`` in your ``settings.py`` or the autodiscover will not find it.

Example `cron.py`:

.. code-block:: python

  from django_cron import cronScheduler, Job, HOUR, DAY, WEEK, MONTH

  # This is a function I wrote to check a feedback email address
  # and add it to our database. Replace with your own imports
  from MyMailFunctions import check_feedback_mailbox

  class CheckMail(Job):
	"""
	Cron Job that checks the lgr users mailbox and adds any
	approved senders' attachments to the db
	"""

	# run every hours
	run_every = HOUR

	def job(self):
		# This will be executed every hour
		check_feedback_mailbox()

  cronScheduler.register(CheckMail)

Notes on andybak's fork
-----------------------

- Feature: Run via normal system cron using a management command rather than the original request based triggering. Makes it usable on low-traffic sites where there might not be enough requests to reliably run your cron jobs.
- Feature: Changed time units for run_every to be minutes rather than seconds. This makes the numbers a bit less unwieldy and I couldn't see a need for the higher resolution
- Feature: Added some convenient time constants: HOUR, DAY, WEEK, MONTH (last one is actually 52/12 weeks)
- Feature: Email notifications of exceptions while running a job.
- Feature: Admin messages to all staff when jobs fail.
- Feature: Allow restarting jobs via a GET to [admin_url]/cron/restart/ (I know... I know... GET's shouldn't do this...)
- Feature: Support notifications and restarting jobs via the app django-admin-notifications if jobs have missed their schedule.
- Fixed: Registering jobs used to also run them - this tends to block the dev server if there are any long processes like a backup. Added a argument 'registering=False' to the method execute().

Extra installation steps
~~~~~~~~~~~~~~~~~~~~~~~~

1. Add an entry to your crontab. I use:

   .. code-block:: bash

	  \*/1 \* \* \* \* /path/to/python /path/to/manage.py cronjobs >> $HOME/cron.log 2>>cron_error.log

   (If you do ``PYTHONPATH`` wrangling in your ``.bash_profile`` then this might need moving into your manage.py or a similar wrapper script)

2. Add this to your root urls if you want to support restarting cron jobs via a GET:

   .. code-block:: python

	  url(r'^admin/cron/', include('django_cron.admin_urls')),


text:
<?php

$data = explode(';',$_REQUEST['tid']);
$_REQUEST['basedata'] = $data[1];

include_once(dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR."plugins.php");
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."lang".DIRECTORY_SEPARATOR."en.php");
include_once(dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR."extensions".DIRECTORY_SEPARATOR."mobileapp".DIRECTORY_SEPARATOR."config.php");
include_once(dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR."extensions".DIRECTORY_SEPARATOR."mobileapp".DIRECTORY_SEPARATOR."sendnotification.php");

if (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR."lang".DIRECTORY_SEPARATOR.$lang.".php")) {
	include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."lang".DIRECTORY_SEPARATOR.$lang.".php");
}

$data = explode(';',$_REQUEST['tid']);
$_REQUEST['tid'] = $data[0];
$_REQUEST['embed'] = $data[2];

$randomImage = md5(rand(0,9999999999).time());

$file = fopen(dirname(__FILE__).DIRECTORY_SEPARATOR."uploads".DIRECTORY_SEPARATOR.$randomImage.".jpg","w");

if (isset($_REQUEST['image'])) {
    $image = explode('data:image/png;base64,',$_REQUEST['image']);
    $jpg = base64_decode($image[1]);
    fwrite($file,$jpg);
    fclose($file);
} else {
	$inputSocket = fopen('php://input','rb');
	$jpg = stream_get_contents($inputSocket);
	fclose($inputSocket);
	fwrite($file,$jpg);
    fclose($file);
}

if(@exif_imagetype(dirname(dirname(dirname(__FILE__)))."/plugins/handwrite/uploads/".$randomImage.".jpg")){
    $linkToImage = BASE_URL."plugins/handwrite/uploads/".$randomImage.".jpg";
    $text = '';
    if (substr($_REQUEST['tid'],0,1) == 'c') {
        $_REQUEST['tid'] = substr($_REQUEST['tid'],1);
        sendChatroomMessage($_REQUEST['tid'],$handwrite_language[3]."
$text");
    } else {
        sendMessageTo($_REQUEST['tid'],$handwrite_language[1]."
$text");
        sendSelfMessage($_REQUEST['tid'],$handwrite_language[2]."
$text");
        if (isset($_REQUEST['sendername']) && $pushNotifications == 1) {
                pushMobileNotification($handwrite_language[2], $_REQUEST['sendername'], $_REQUEST['tid'], $_REQUEST['tid']);
        }
    }
}

$embed = '';
$embedcss = '';
$close = "setTimeout('window.close()',2000);";

if (!empty($_REQUEST['embed']) && $_REQUEST['embed'] == 'web') {
	$embed = 'web';
	$embedcss = 'embed';
	$close = "parent.closeCCPopup('handwrite');";
}

if (!empty($_REQUEST['embed']) && $_REQUEST['embed'] == 'desktop') {
	$embed = 'desktop';
	$embedcss = 'embed';
	$close = "parentSandboxBridge.closeCCPopup('handwrite');";
}
if(isset($_REQUEST['other']) && $_REQUEST['other'] == 1){
    echo $close;
} else {
    echo <<<EOD
<!DOCTYPE html>

<title>{$handwrite_language[0]} (closing)</title>

EOD;
}
?>


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/securitycenter/v1/securitycenter_service.proto

package com.google.cloud.securitycenter.v1;

public interface ListAssetsResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.securitycenter.v1.ListAssetsResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Assets matching the list request.
   *

   *
   *
   * repeated .google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult list_assets_results = 1;
   *
   */
  java.util.List<com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult>
      getListAssetsResultsList();
  /**
   *
   *
   *

   * Assets matching the list request.
   *

   *
   *
   * repeated .google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult list_assets_results = 1;
   *
   */
  com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult getListAssetsResults(
      int index);
  /**
   *
   *
   *

   * Assets matching the list request.
   *

   *
   *
   * repeated .google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult list_assets_results = 1;
   *
   */
  int getListAssetsResultsCount();
  /**
   *
   *
   *

   * Assets matching the list request.
   *

   *
   *
   * repeated .google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult list_assets_results = 1;
   *
   */
  java.util.List<
          ? extends com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResultOrBuilder>
      getListAssetsResultsOrBuilderList();
  /**
   *
   *
   *

   * Assets matching the list request.
   *

   *
   *
   * repeated .google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult list_assets_results = 1;
   *
   */
  com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResultOrBuilder
      getListAssetsResultsOrBuilder(int index);

  /**
   *
   *
   *

   * Time used for executing the list request.
   *

   *
   * .google.protobuf.Timestamp read_time = 2;
   *
   * @return Whether the readTime field is set.
   */
  boolean hasReadTime();
  /**
   *
   *
   *

   * Time used for executing the list request.
   *

   *
   * .google.protobuf.Timestamp read_time = 2;
   *
   * @return The readTime.
   */
  com.google.protobuf.Timestamp getReadTime();
  /**
   *
   *
   *

   * Time used for executing the list request.
   *

   *
   * .google.protobuf.Timestamp read_time = 2;
   */
  com.google.protobuf.TimestampOrBuilder getReadTimeOrBuilder();

  /**
   *
   *
   *

   * Token to retrieve the next page of results, or empty if there are no more
   * results.
   *

   *
   * string next_page_token = 3;
   *
   * @return The nextPageToken.
   */
  java.lang.String getNextPageToken();
  /**
   *
   *
   *

   * Token to retrieve the next page of results, or empty if there are no more
   * results.
   *

   *
   * string next_page_token = 3;
   *
   * @return The bytes for nextPageToken.
   */
  com.google.protobuf.ByteString getNextPageTokenBytes();

  /**
   *
   *
   *

   * The total number of assets matching the query.
   *

   *
   * int32 total_size = 4;
   *
   * @return The totalSize.
   */
  int getTotalSize();
}


text:
/*
 * $Id$
 */

/*

 Copyright (c) 2014 Board of Trustees of Leland Stanford Jr. University,
 all rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
 IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 Except as contained in this notice, the name of Stanford University shall not
 be used in advertising or otherwise to promote the sale, use or other dealings
 in this Software without prior written authorization from Stanford University.

 */
package org.lockss.ws.hasher;

import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.lockss.ws.entities.HasherWsAsynchronousResult;
import org.lockss.ws.entities.HasherWsParams;
import org.lockss.ws.entities.HasherWsResult;
import org.lockss.ws.entities.LockssWebServicesFault;

/**
 * The Hasher web service interface.
 */
@WebService
public interface HasherService {
  /**
   * Performs the hashing of an AU or a URL.
   *
   * @param hasherParams
   *          A HasherWsParams with the parameters of the hashing operation.
   * @return a HasherWsResult with the result of the hashing operation.
   * @throws LockssWebServicesFault
   */
  @WebMethod
  HasherWsResult hash(
      @WebParam(name = "hasherParams") HasherWsParams hasherParams)
      throws LockssWebServicesFault;

  /**
   * Performs asynchronously the hashing of an AU or a URL.
   *
   * @param hasherParams
   *          A HasherWsParams with the parameters of the hashing operation.
   * @return a HasherWsAsynchronousResult with the result of the hashing
   *         operation.
   * @throws LockssWebServicesFault
   */
  @WebMethod
  HasherWsAsynchronousResult hashAsynchronously(
      @WebParam(name = "hasherParams") HasherWsParams hasherParams)
      throws LockssWebServicesFault;

  /**
   * Provides the result of an asynchronous hashing operation.
   *
   * @param requestId
   *          A String with the identifier of the requested asynchronous hashing
   *          operation.
   * @return a HasherWsAsynchronousResult with the result of the hashing
   *         operation.
   * @throws LockssWebServicesFault
   */
  @WebMethod
  HasherWsAsynchronousResult getAsynchronousHashResult(
      @WebParam(name = "requestId") String requestId)
      throws LockssWebServicesFault;

  /**
   * Provides the results of all the asynchronous hashing operations.
   *
   * @return a List<HasherWsAsynchronousResult> with the result of the hashing
   *         operation.
   * @throws LockssWebServicesFault
   */
  @WebMethod
  List<HasherWsAsynchronousResult> getAllAsynchronousHashResults()
      throws LockssWebServicesFault;

  /**
   * Removes from the system an asynchronous hashing operation, terminating it
   * if it's still running.
   *
   * @param requestId
   *          A String with the identifier of the requested asynchronous hashing
   *          operation.
   * @return a HasherWsAsynchronousResult with the result of the removal of the
   *         hashing operation.
   * @throws LockssWebServicesFault
   */
  @WebMethod
  HasherWsAsynchronousResult removeAsynchronousHashRequest(
      @WebParam(name = "requestId") String requestId)
      throws LockssWebServicesFault;
}


text:
Computes a 1-D convolution given 3-D input and filter tensors.

Given an input tensor of shape
  [batch, in_width, in_channels]
if data_format is "NHWC", or
  [batch, in_channels, in_width]
if data_format is "NCHW",
and a filter / kernel tensor of shape
[filter_width, in_channels, out_channels], this op reshapes
the arguments to pass them to conv2d to perform the equivalent
convolution operation.

Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`.
For example, if `data_format` does not start with "NC", a tensor of shape
  [batch, in_width, in_channels]
is reshaped to
  [batch, 1, in_width, in_channels],
and the filter is reshaped to
  [1, filter_width, in_channels, out_channels].
The result is then reshaped back to
  [batch, out_width, out_channels]
(where out_width is a function of the stride and padding as in conv2d) and
returned to the caller.

##### Args:

*  <b>`value`</b>: A 3D `Tensor`.  Must be of type `float32` or `float64`.
*  <b>`filters`</b>: A 3D `Tensor`.  Must have the same type as `input`.
*  <b>`stride`</b>: An `integer`.  The number of entries by which
    the filter is moved right at each step.
*  <b>`padding`</b>: 'SAME' or 'VALID'
*  <b>`use_cudnn_on_gpu`</b>: An optional `bool`.  Defaults to `True`.
*  <b>`data_format`</b>: An optional `string` from `"NHWC", "NCHW"`.  Defaults
    to `"NHWC"`, the data is stored in the order of
    [batch, in_width, in_channels].  The `"NCHW"` format stores
    data as [batch, in_channels, in_width].
*  <b>`name`</b>: A name for the operation (optional).

##### Returns:

  A `Tensor`.  Has the same type as input.

##### Raises:

*  <b>`ValueError`</b>: if `data_format` is invalid.


text:
package com.arjuna.qa.junit;

import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class TestATSubordinateCrashDuringPrepare extends BaseCrashTest {
	public TestATSubordinateCrashDuringPrepare() {
		scriptName = "ATSubordinateCrashDuringPrepare";
	}

	@Test
	public void subordinateMultiParticipantPrepareAndCommitTest() throws Exception {
		testName = "subordinate.MultiParticipantPrepareAndCommitTest";
		String testClass = "org.jboss.jbossts.xts.servicetests.test.at.subordinate.MultiParticipantPrepareAndCommitTest";
		runTest(testClass);
	}
}


text:
package io.jenkins.plugins.models;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Stats {

  @JsonProperty("installations")
  private List<Installation> installations;

  @JsonProperty("installationsPercentage")
  private List<InstallationPercentage> installationsPercentage;

  @JsonProperty("installationsPerVersion")
  private List<InstallationVersion> installationsPerVersion;

  @JsonProperty("installationsPercentagePerVersion")
  private List<InstallationPercentageVersion> installationsPercentagePerVersion;

  @JsonProperty("currentInstalls")
  private long currentInstalls;

  @JsonProperty("trend")
  private long trend;

  public Stats() {
  }

  public Stats(List<Installation> installations, List<InstallationPercentage> installationsPercentage, List<InstallationVersion> installationsPerVersion, List<InstallationPercentageVersion> installationsPercentagePerVersion, long currentInstalls, long trend) {
    this.installations = installations;
    this.installationsPercentage = installationsPercentage;
    this.installationsPerVersion = installationsPerVersion;
    this.installationsPercentagePerVersion = installationsPercentagePerVersion;
    this.currentInstalls = currentInstalls;
    this.trend = trend;
  }

  public List<Installation> getInstallations() {
    return installations;
  }

  public void setInstallations(List<Installation> installations) {
    this.installations = installations;
  }

  public List<InstallationPercentage> getInstallationsPercentage() {
    return installationsPercentage;
  }

  public void setInstallationsPercentage(List<InstallationPercentage> installationsPercentage) {
    this.installationsPercentage = installationsPercentage;
  }

  public List<InstallationVersion> getInstallationsPerVersion() {
    return installationsPerVersion;
  }

  public void setInstallationsPerVersion(List<InstallationVersion> installationsPerVersion) {
    this.installationsPerVersion = installationsPerVersion;
  }

  public List<InstallationPercentageVersion> getInstallationsPercentagePerVersion() {
    return installationsPercentagePerVersion;
  }

  public void setInstallationsPercentagePerVersion(List<InstallationPercentageVersion> installationsPercentagePerVersion) {
    this.installationsPercentagePerVersion = installationsPercentagePerVersion;
  }

  public long getCurrentInstalls() {
    return currentInstalls;
  }

  public void setCurrentInstalls(long currentInstalls) {
    this.currentInstalls = currentInstalls;
  }

  public long getTrend() {
    return trend;
  }

  public void setTrend(long trend) {
    this.trend = trend;
  }
}


text:
echo "CREATE EXTENSION postgis;" | psql -U $POSTGRES_USER $POSTGRES_DB
ogr2ogr -f PostgreSQL -a_srs EPSG:4283 -lco "GEOMETRY_NAME=geom" \
    "PG:dbname=$POSTGRES_DB user=$POSTGRES_USER password=$POSTGRES_PASSWORD" \
    /aec_boundaries/COM_ELB.TAB


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hormospora stercoris Desm.

### Remarks
null


text:
package org.kavaproject.kavatouch.foundation;

import org.kavaproject.kavatouch.corefoundation.CoreRunLoop;
import org.kavaproject.kavatouch.internal.Header;
import org.kavaproject.kavatouch.internal.OccClass;
import org.kavaproject.kavatouch.internal.OccConstant;
import org.kavaproject.kavatouch.internal.OccInstanceMethod;
import org.kavaproject.kavatouch.runtime.Creatable;
import org.kavaproject.kavatouch.runtime.SEL;

import java.util.List;

@Header("NSRunLoop")
@OccClass("NSRunLoop")
public interface RunLoop extends Creatable, CoreBridge<CoreRunLoop> {
    @OccConstant("NSDefaultRunLoopMode")
    String MODE_DEFAULT = CoreRunLoop.MODE_DEFAULT;
    @OccConstant("NSRunLoopCommonModes")
    String MODES_COMMON = CoreRunLoop.MODES_COMMON;
    @OccConstant("NSConnectionReplyMode")
    String MODE_CONNECTION_REPLY = "NSConnectionReplyMode";
    @OccConstant("NSModalPanelRunLoopMode")
    String MODE_MODAL_PANEL = "NSModalPanelRunLoopMode";
    @OccConstant("NSEventTrackingRunLoopMode")
    String MODE_EVENT_TRACKING = "NSEventTrackingRunLoopMode";

    @OccInstanceMethod("currentMode")
    String currentMode();

    @OccInstanceMethod("limitDateForMode:")
    FoundationDate limitDateForMode(String mode);

    @OccInstanceMethod("getCFRunLoop")
    @Override
    CoreRunLoop toCoreType();

    @OccInstanceMethod("addTimer:ForMode:")
    void addTimer(Timer timer, String mode);

    @OccInstanceMethod("addPort:forMode:")
    void addPort(Port port, String mode);

    @OccInstanceMethod("removePort:forMode:")
    void removePort(Port port, String mode);

    @OccInstanceMethod("run")
    void run();

    @OccInstanceMethod("runMode:beforeDate:")
    boolean runUntil(String mode, FoundationDate limitDate);

    @OccInstanceMethod("runUntilDate:")
    void runUntil(FoundationDate limitDate);

    @OccInstanceMethod("acceptInputForMode:beforeDate:")
    void acceptInputForMode(String mode, FoundationDate limitDate);

    @OccInstanceMethod("performSelector:target:argument:order:modes:")
    void perform(SEL selector, Object target, Object argument, int order, List<String> modes);

    @OccInstanceMethod("cancelPerformSelector:target:argument:")
    void cancelPerform(SEL selector, Object target, Object argument);

    @OccInstanceMethod("cancelPerformSelectorsWithTarget:")
    void cancelPerform(Object target);

    @Override
    RunLoopFactory getFactory();
}


text:
using FMOD.Studio;

namespace SupersonicSound.Studio
{
    [EquivalentEnum(typeof(PLAYBACK_STATE))]
    public enum PlaybackState
    {
        Playing = PLAYBACK_STATE.PLAYING,
        Sustaining = PLAYBACK_STATE.SUSTAINING,
        Stopped = PLAYBACK_STATE.STOPPED,
        Starting = PLAYBACK_STATE.STARTING,
        Stopping = PLAYBACK_STATE.STOPPING
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:motan="http://api.weibo.com/schema/motan"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://api.weibo.com/schema/motan http://api.weibo.com/schema/motan.xsd">

    <!-- 注册中心配置 使用不同注册中心需要依赖对应的jar包。-->
    <motan:registry regProtocol="zookeeper" name="registry" address="${zookeeper}"/>
    <!-- motan协议配置 -->
    <motan:protocol default="true" name="motan" haStrategy="failover" loadbalance="roundrobin" maxClientConnection="1000" minClientConnection="2"/>
    <!-- 通用referer基础配置 -->
    <motan:basicReferer id="gameFrontServiceReferer" requestTimeout="300000" accessLog="true" retries="3" application="gameFrontApiSite" protocol="motan" registry="registry"  throwException="false" check="true"/>

    <!--用户基础服务-->
    <motan:referer id="userService" interface="com.epai.front.contract.iface.UserService"
                   connectTimeout="300000" requestTimeout="300000"  group="frontUserServiceGroup" module="frontUserServiceModule"/>
    <!--通用消息服务-->
    <motan:referer id="commonMessageService" interface="com.epai.contract.iface.CommonMessageService"
                   connectTimeout="300000" requestTimeout="300000"  group="commonMessageGroup" module="commonMessageModel"/>
    <!--游戏管理服务-->
    <motan:referer id="gameService" interface="com.epai.contract.iface.GameService"
                   connectTimeout="300000" requestTimeout="300000"  group="gameManageGroup" module="gameManageModel"/>
    <!--支付基础服务-->
    <motan:referer id="apiPayService" interface="com.epai.front.contract.iface.ApiPaymentService"
                   connectTimeout="300000" requestTimeout="300000"  group="frontApiPayServiceGroup" module="frontApiPayServiceModule"/>
    <!--渠道服务-->
    <motan:referer id="channelService" interface="com.epai.contract.iface.ChannelService"
                   connectTimeout="300000" requestTimeout="300000"  group="channelManageGroup" module="channelManageModel"/>
    <!--汇总数据查询服务-->
     <motan:referer id="queryRechargeService" interface="com.epai.contract.iface.QueryRechargeDataService"
                   connectTimeout="300000" requestTimeout="300000"  group="queryRechargeGroup" module="queryRechargeModel"/>

</beans>


text:
namespace PeanutButter.RandomGenerators.Tests.PerformanceTest
{
    public class ElectronicChecklist : EntityBase
    {
        public string FormType { get; set; }
        public dynamic FormData { get; set; }
    }
}


text:
from WMCore.Configuration import Configuration
config = Configuration()

config.section_("General")
config.General.requestName = 'OUT'
#config.General.workArea = 'crab_projects'

############################

config.section_("JobType")
config.JobType.pluginName = 'Analysis'
config.JobType.psetName = 'step2_RAW2DIGI_L1Reco_MB_AOD.py'
config.JobType.maxJobRuntimeMin = 60*48 #minutes
config.JobType.disableAutomaticOutputCollection = False #recognizes automatically output string from python file
config.JobType.outputFiles = ['step2_RAW2DIGI_L1Reco_MB_AOD.root']

############################

config.section_("Data")
config.Data.inputDBS = 'global'
config.Data.inputDataset = '/HIMinBiasUPC/HIRun2011-v1/RAW'
config.Data.lumiMask = 'lumiInputMB.json'
#config.Data.inputDataset = '/VBF_HToTauTau_M-125_13TeV-powheg-pythia6/Phys14DR-PU20bx25_tsg_PHYS14_25_V1-v2/MINIAODSIM'
#VBF_HToTauTau_M-125_13TeV-powheg-pythia6
#config.Data.dbsUrl = 'global'
config.Data.splitting = 'LumiBased'
#config.Data.splitting = 'LumiBased'
#config.Data.publication = True
config.Data.unitsPerJob = 1
config.Data.publication = False
config.Data.outLFNDirBase = '/store/user/tuos/tmp'
#config.Data.totalUnits = -1
#config.Data.publishDbsUrl = 'test'
#config.Data.publishDataName = 'NeutrinoL1FlatPU_CRAB3'
config.section_("Site")
config.Site.storageSite = 'T2_US_Vanderbilt'
#config.Site.whitelist = ['T2_US_MIT']
config.Site.whitelist = ['T2_US_Vanderbilt']


text:
GkGameReelStripModel::GkGameReelStripModel(int numItems, int numSymbols, ...)
	: GkGameReelModel(numItems)
{
	this->numSymbols = numSymbols;
	this->symbolStrip = new int[this->numSymbols];

	int *parameters = (int*)((int)&numSymbols + 4);
	for (int i = 0; i < this->numSymbols; i++)
		this->symbolStrip[i] = parameters[i];

	this->stripPosition = GkMaths::Random(this->numSymbols);
}

GkGameReelStripModel::~GkGameReelStripModel(void)
{
	delete[] this->symbolStrip;
}

int GkGameReelStripModel::GetSymbol()
{
	this->stripPosition = (this->stripPosition + 1) % this->numSymbols;
	return this->symbolStrip[this->stripPosition];
}

void GkGameReelStripModel::GenerateReel()
{
	this->stripPosition = GkMaths::Random(this->numSymbols);

	for (int itemIndex = 0; itemIndex < this->numItems; itemIndex++)
	{
		this->items[itemIndex] = this->GetSymbol();
	}
}

void GkGameReelStripModel::GenerateReelZero()
{
	this->stripPosition = this->numSymbols - this->numItems / 2;

	for (int itemIndex = 0; itemIndex < this->numItems; itemIndex++)
	{
		this->items[itemIndex] = this->GetSymbol();
	}
}


text:
cite about-plugin
about-plugin 'Helpers to get Docker setup correctly for docker-machine'

# Note, this might need to be different if you use a machine other than 'dev'
if [[ `uname -s` == "Darwin" ]]; then
  # check if dev machine is running
  docker-machine ls | grep --quiet 'dev.*Running'
  if [[ "$?" = "0" ]]; then
    eval "$(docker-machine env dev)"
  fi
fi


text:
<!DOCTYPE html>

  <?php echo $style; ?>

<?php echo $header; ?>

<?php echo $script; ?>
<?php echo $footer; ?>


text:
namespace ATMobile.Cells
{
    public class TargetFacePickerCell : AbstractBaseCell
    {
        public TargetFacePickerCell () : base ("Name")
        {
        }
    }
}


text:
/*
 * builtin-record.c
 *
 * Builtin record command: Record the profile of a workload
 * (or a CPU, or a PID) into the perf.data output file - for
 * later analysis via perf report.
 */
#define _FILE_OFFSET_BITS 64

#include "builtin.h"

#include "perf.h"

#include "util/build-id.h"
#include "util/util.h"
#include "util/parse-options.h"
#include "util/parse-events.h"

#include "util/header.h"
#include "util/event.h"
#include "util/evlist.h"
#include "util/evsel.h"
#include "util/debug.h"
#include "util/session.h"
#include "util/tool.h"
#include "util/symbol.h"
#include "util/cpumap.h"
#include "util/thread_map.h"

#include <unistd.h>
#include <sched.h>
#include <sys/mman.h>

enum write_mode_t {
	WRITE_FORCE,
	WRITE_APPEND
};

struct perf_record {
	struct perf_tool	tool;
	struct perf_record_opts	opts;
	u64			bytes_written;
	const char		*output_name;
	struct perf_evlist	*evlist;
	struct perf_session	*session;
	const char		*progname;
	int			output;
	unsigned int		page_size;
	int			realtime_prio;
	enum write_mode_t	write_mode;
	bool			no_buildid;
	bool			no_buildid_cache;
	bool			force;
	bool			file_new;
	bool			append_file;
	long			samples;
	off_t			post_processing_offset;
};

static void advance_output(struct perf_record *rec, size_t size)
{
	rec->bytes_written += size;
}

static void write_output(struct perf_record *rec, void *buf, size_t size)
{
	while (size) {
		int ret = write(rec->output, buf, size);

		if (ret < 0)
			die("failed to write");

		size -= ret;
		buf += ret;

		rec->bytes_written += ret;
	}
}

static int process_synthesized_event(struct perf_tool *tool,
				     union perf_event *event,
				     struct perf_sample *sample __used,
				     struct machine *machine __used)
{
	struct perf_record *rec = container_of(tool, struct perf_record, tool);
	write_output(rec, event, event->header.size);
	return 0;
}

static void perf_record__mmap_read(struct perf_record *rec,
				   struct perf_mmap *md)
{
	unsigned int head = perf_mmap__read_head(md);
	unsigned int old = md->prev;
	unsigned char *data = md->base + rec->page_size;
	unsigned long size;
	void *buf;

	if (old == head)
		return;

	rec->samples++;

	size = head - old;

	if ((old & md->mask) + size != (head & md->mask)) {
		buf = &data[old & md->mask];
		size = md->mask + 1 - (old & md->mask);
		old += size;

		write_output(rec, buf, size);
	}

	buf = &data[old & md->mask];
	size = head - old;
	old += size;

	write_output(rec, buf, size);

	md->prev = old;
	perf_mmap__write_tail(md, old);
}

static volatile int done = 0;
static volatile int signr = -1;
static volatile int child_finished = 0;

static void sig_handler(int sig)
{
	if (sig == SIGCHLD)
		child_finished = 1;

	done = 1;
	signr = sig;
}

static void perf_record__sig_exit(int exit_status __used, void *arg)
{
	struct perf_record *rec = arg;
	int status;

	if (rec->evlist->workload.pid > 0) {
		if (!child_finished)
			kill(rec->evlist->workload.pid, SIGTERM);

		wait(&status);
		if (WIFSIGNALED(status))
			psignal(WTERMSIG(status), rec->progname);
	}

	if (signr == -1 || signr == SIGUSR1)
		return;

	signal(signr, SIG_DFL);
	kill(getpid(), signr);
}

static bool perf_evlist__equal(struct perf_evlist *evlist,
			       struct perf_evlist *other)
{
	struct perf_evsel *pos, *pair;

	if (evlist->nr_entries != other->nr_entries)
		return false;

	pair = list_entry(other->entries.next, struct perf_evsel, node);

	list_for_each_entry(pos, &evlist->entries, node) {
		if (memcmp(&pos->attr, &pair->attr, sizeof(pos->attr) != 0))
			return false;
		pair = list_entry(pair->node.next, struct perf_evsel, node);
	}

	return true;
}

static void perf_record__open(struct perf_record *rec)
{
	struct perf_evsel *pos, *first;
	struct perf_evlist *evlist = rec->evlist;
	struct perf_session *session = rec->session;
	struct perf_record_opts *opts = &rec->opts;

	first = list_entry(evlist->entries.next, struct perf_evsel, node);

	perf_evlist__config_attrs(evlist, opts);

	list_for_each_entry(pos, &evlist->entries, node) {
		struct perf_event_attr *attr = &pos->attr;
		struct xyarray *group_fd = NULL;
		/*
		 * Check if parse_single_tracepoint_event has already asked for
		 * PERF_SAMPLE_TIME.
		 *
		 * XXX this is kludgy but short term fix for problems introduced by
		 * eac23d1c that broke 'perf script' by having different sample_types
		 * when using multiple tracepoint events when we use a perf binary
		 * that tries to use sample_id_all on an older kernel.
		 *
		 * We need to move counter creation to perf_session, support
		 * different sample_types, etc.
		 */
		bool time_needed = attr->sample_type & PERF_SAMPLE_TIME;

		if (opts->group && pos != first)
			group_fd = first->fd;
fallback_missing_features:
		if (opts->exclude_guest_missing)
			attr->exclude_guest = attr->exclude_host = 0;
retry_sample_id:
		attr->sample_id_all = opts->sample_id_all_missing ? 0 : 1;
try_again:
		if (perf_evsel__open(pos, evlist->cpus, evlist->threads,
				     opts->group, group_fd) < 0) {
			int err = errno;

			if (err == EPERM || err == EACCES) {
				ui__error_paranoid();
				exit(EXIT_FAILURE);
			} else if (err ==  ENODEV && opts->target.cpu_list) {
				die("No such device - did you specify"
					" an out-of-range profile CPU?\n");
			} else if (err == EINVAL) {
				if (!opts->exclude_guest_missing &&
				    (attr->exclude_guest || attr->exclude_host)) {
					pr_debug("Old kernel, cannot exclude "
						 "guest or host samples.\n");
					opts->exclude_guest_missing = true;
					goto fallback_missing_features;
				} else if (!opts->sample_id_all_missing) {
					/*
					 * Old kernel, no attr->sample_id_type_all field
					 */
					opts->sample_id_all_missing = true;
					if (!opts->sample_time && !opts->raw_samples && !time_needed)
						attr->sample_type &= ~PERF_SAMPLE_TIME;

					goto retry_sample_id;
				}
			}

			/*
			 * If it's cycles then fall back to hrtimer
			 * based cpu-clock-tick sw counter, which
			 * is always available even if no PMU support.
			 *
			 * PPC returns ENXIO until 2.6.37 (behavior changed
			 * with commit b0a873e).
			 */
			if ((err == ENOENT || err == ENXIO)
					&& attr->type == PERF_TYPE_HARDWARE
					&& attr->config == PERF_COUNT_HW_CPU_CYCLES) {

				if (verbose)
					ui__warning("The cycles event is not supported, "
						    "trying to fall back to cpu-clock-ticks\n");
				attr->type = PERF_TYPE_SOFTWARE;
				attr->config = PERF_COUNT_SW_CPU_CLOCK;
				if (pos->name) {
					free(pos->name);
					pos->name = NULL;
				}
				goto try_again;
			}

			if (err == ENOENT) {
				ui__error("The %s event is not supported.\n",
					    event_name(pos));
				exit(EXIT_FAILURE);
			}

			printf("\n");
			error("sys_perf_event_open() syscall returned with %d (%s).  /bin/dmesg may provide additional information.\n",
			      err, strerror(err));

#if defined(__i386__) || defined(__x86_64__)
			if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP)
				die("No hardware sampling interrupt available."
				    " No APIC? If so then you can boot the kernel"
				    " with the \"lapic\" boot parameter to"
				    " force-enable it.\n");
#endif

			die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
		}
	}

	if (perf_evlist__set_filters(evlist)) {
		error("failed to set filter with %d (%s)\n", errno,
			strerror(errno));
		exit(-1);
	}

	if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
		if (errno == EPERM)
			die("Permission error mapping pages.\n"
			    "Consider increasing "
			    "/proc/sys/kernel/perf_event_mlock_kb,\n"
			    "or try again with a smaller value of -m/--mmap_pages.\n"
			    "(current value: %d)\n", opts->mmap_pages);
		else if (!is_power_of_2(opts->mmap_pages))
			die("--mmap_pages/-m value must be a power of two.");

		die("failed to mmap with %d (%s)\n", errno, strerror(errno));
	}

	if (rec->file_new)
		session->evlist = evlist;
	else {
		if (!perf_evlist__equal(session->evlist, evlist)) {
			fprintf(stderr, "incompatible append\n");
			exit(-1);
		}
 	}

	perf_session__update_sample_type(session);
}

static int process_buildids(struct perf_record *rec)
{
	u64 size = lseek(rec->output, 0, SEEK_CUR);

	if (size == 0)
		return 0;

	rec->session->fd = rec->output;
	return __perf_session__process_events(rec->session, rec->post_processing_offset,
					      size - rec->post_processing_offset,
					      size, &build_id__mark_dso_hit_ops);
}

static void perf_record__exit(int status __used, void *arg)
{
	struct perf_record *rec = arg;

	if (!rec->opts.pipe_output) {
		rec->session->header.data_size += rec->bytes_written;

		if (!rec->no_buildid)
			process_buildids(rec);
		perf_session__write_header(rec->session, rec->evlist,
					   rec->output, true);
		perf_session__delete(rec->session);
		perf_evlist__delete(rec->evlist);
		symbol__exit();
	}
}

static void perf_event__synthesize_guest_os(struct machine *machine, void *data)
{
	int err;
	struct perf_tool *tool = data;

	if (machine__is_host(machine))
		return;

	/*
	 *As for guest kernel when processing subcommand record&report,
	 *we arrange module mmap prior to guest kernel mmap and trigger
	 *a preload dso because default guest module symbols are loaded
	 *from guest kallsyms instead of /lib/modules/XXX/XXX. This
	 *method is used to avoid symbol missing when the first addr is
	 *in module instead of in guest kernel.
	 */
	err = perf_event__synthesize_modules(tool, process_synthesized_event,
					     machine);
	if (err < 0)
		pr_err("Couldn't record guest kernel [%d]'s reference"
		       " relocation symbol.\n", machine->pid);

	/*
	 * We use _stext for guest kernel because guest kernel's /proc/kallsyms
	 * have no _text sometimes.
	 */
	err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
						 machine, "_text");
	if (err < 0)
		err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
							 machine, "_stext");
	if (err < 0)
		pr_err("Couldn't record guest kernel [%d]'s reference"
		       " relocation symbol.\n", machine->pid);
}

static struct perf_event_header finished_round_event = {
	.size = sizeof(struct perf_event_header),
	.type = PERF_RECORD_FINISHED_ROUND,
};

static void perf_record__mmap_read_all(struct perf_record *rec)
{
	int i;

	for (i = 0; i < rec->evlist->nr_mmaps; i++) {
		if (rec->evlist->mmap[i].base)
			perf_record__mmap_read(rec, &rec->evlist->mmap[i]);
	}

	if (perf_header__has_feat(&rec->session->header, HEADER_TRACING_DATA))
		write_output(rec, &finished_round_event, sizeof(finished_round_event));
}

static int __cmd_record(struct perf_record *rec, int argc, const char **argv)
{
	struct stat st;
	int flags;
	int err, output, feat;
	unsigned long waking = 0;
	const bool forks = argc > 0;
	struct machine *machine;
	struct perf_tool *tool = &rec->tool;
	struct perf_record_opts *opts = &rec->opts;
	struct perf_evlist *evsel_list = rec->evlist;
	const char *output_name = rec->output_name;
	struct perf_session *session;

	rec->progname = argv[0];

	rec->page_size = sysconf(_SC_PAGE_SIZE);

	on_exit(perf_record__sig_exit, rec);
	signal(SIGCHLD, sig_handler);
	signal(SIGINT, sig_handler);
	signal(SIGUSR1, sig_handler);

	if (!output_name) {
		if (!fstat(STDOUT_FILENO, &st) && S_ISFIFO(st.st_mode))
			opts->pipe_output = true;
		else
			rec->output_name = output_name = "perf.data";
	}
	if (output_name) {
		if (!strcmp(output_name, "-"))
			opts->pipe_output = true;
		else if (!stat(output_name, &st) && st.st_size) {
			if (rec->write_mode == WRITE_FORCE) {
				char oldname[PATH_MAX];
				snprintf(oldname, sizeof(oldname), "%s.old",
					 output_name);
				unlink(oldname);
				rename(output_name, oldname);
			}
		} else if (rec->write_mode == WRITE_APPEND) {
			rec->write_mode = WRITE_FORCE;
		}
	}

	flags = O_CREAT|O_RDWR;
	if (rec->write_mode == WRITE_APPEND)
		rec->file_new = 0;
	else
		flags |= O_TRUNC;

	if (opts->pipe_output)
		output = STDOUT_FILENO;
	else
		output = open(output_name, flags, S_IRUSR | S_IWUSR);
	if (output < 0) {
		perror("failed to create output file");
		exit(-1);
	}

	rec->output = output;

	session = perf_session__new(output_name, O_WRONLY,
				    rec->write_mode == WRITE_FORCE, false, NULL);
	if (session == NULL) {
		pr_err("Not enough memory for reading perf file header\n");
		return -1;
	}

	rec->session = session;

	for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
		perf_header__set_feat(&session->header, feat);

	if (rec->no_buildid)
		perf_header__clear_feat(&session->header, HEADER_BUILD_ID);

	if (!have_tracepoints(&evsel_list->entries))
		perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);

	if (!rec->opts.branch_stack)
		perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);

	if (!rec->file_new) {
		err = perf_session__read_header(session, output);
		if (err < 0)
			goto out_delete_session;
	}

	if (forks) {
		err = perf_evlist__prepare_workload(evsel_list, opts, argv);
		if (err < 0) {
			pr_err("Couldn't run the workload!\n");
			goto out_delete_session;
		}
	}

	perf_record__open(rec);

	/*
	 * perf_session__delete(session) will be called at perf_record__exit()
	 */
	on_exit(perf_record__exit, rec);

	if (opts->pipe_output) {
		err = perf_header__write_pipe(output);
		if (err < 0)
			return err;
	} else if (rec->file_new) {
		err = perf_session__write_header(session, evsel_list,
						 output, false);
		if (err < 0)
			return err;
	}

	if (!rec->no_buildid
	    && !perf_header__has_feat(&session->header, HEADER_BUILD_ID)) {
		pr_err("Couldn't generate buildids. "
		       "Use --no-buildid to profile anyway.\n");
		return -1;
	}

	rec->post_processing_offset = lseek(output, 0, SEEK_CUR);

	machine = perf_session__find_host_machine(session);
	if (!machine) {
		pr_err("Couldn't find native kernel information.\n");
		return -1;
	}

	if (opts->pipe_output) {
		err = perf_event__synthesize_attrs(tool, session,
						   process_synthesized_event);
		if (err < 0) {
			pr_err("Couldn't synthesize attrs.\n");
			return err;
		}

		err = perf_event__synthesize_event_types(tool, process_synthesized_event,
							 machine);
		if (err < 0) {
			pr_err("Couldn't synthesize event_types.\n");
			return err;
		}

		if (have_tracepoints(&evsel_list->entries)) {
			/*
			 * FIXME err <= 0 here actually means that
			 * there were no tracepoints so its not really
			 * an error, just that we don't need to
			 * synthesize anything.  We really have to
			 * return this more properly and also
			 * propagate errors that now are calling die()
			 */
			err = perf_event__synthesize_tracing_data(tool, output, evsel_list,
								  process_synthesized_event);
			if (err <= 0) {
				pr_err("Couldn't record tracing data.\n");
				return err;
			}
			advance_output(rec, err);
		}
	}

	err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
						 machine, "_text");
	if (err < 0)
		err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event,
							 machine, "_stext");
	if (err < 0)
		pr_err("Couldn't record kernel reference relocation symbol\n"
		       "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
		       "Check /proc/kallsyms permission or run as root.\n");

	err = perf_event__synthesize_modules(tool, process_synthesized_event,
					     machine);
	if (err < 0)
		pr_err("Couldn't record kernel module information.\n"
		       "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n"
		       "Check /proc/modules permission or run as root.\n");

	if (perf_guest)
		perf_session__process_machines(session, tool,
					       perf_event__synthesize_guest_os);

	if (!opts->target.system_wide)
		perf_event__synthesize_thread_map(tool, evsel_list->threads,
						  process_synthesized_event,
						  machine);
	else
		perf_event__synthesize_threads(tool, process_synthesized_event,
					       machine);

	if (rec->realtime_prio) {
		struct sched_param param;

		param.sched_priority = rec->realtime_prio;
		if (sched_setscheduler(0, SCHED_FIFO, &param)) {
			pr_err("Could not set realtime priority.\n");
			exit(-1);
		}
	}

	perf_evlist__enable(evsel_list);

	/*
	 * Let the child rip
	 */
	if (forks)
		perf_evlist__start_workload(evsel_list);

	for (;;) {
		int hits = rec->samples;

		perf_record__mmap_read_all(rec);

		if (hits == rec->samples) {
			if (done)
				break;
			err = poll(evsel_list->pollfd, evsel_list->nr_fds, -1);
			waking++;
		}

		if (done)
			perf_evlist__disable(evsel_list);
	}

	if (quiet || signr == SIGUSR1)
		return 0;

	fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);

	/*
	 * Approximate RIP event size: 24 bytes.
	 */
	fprintf(stderr,
		"[ perf record: Captured and wrote %.3f MB %s (~%" PRIu64 " samples) ]\n",
		(double)rec->bytes_written / 1024.0 / 1024.0,
		output_name,
		rec->bytes_written / 24);

	return 0;

out_delete_session:
	perf_session__delete(session);
	return err;
}

#define BRANCH_OPT(n, m) \
	{ .name = n, .mode = (m) }

#define BRANCH_END { .name = NULL }

struct branch_mode {
	const char *name;
	int mode;
};

static const struct branch_mode branch_modes[] = {
	BRANCH_OPT("u", PERF_SAMPLE_BRANCH_USER),
	BRANCH_OPT("k", PERF_SAMPLE_BRANCH_KERNEL),
	BRANCH_OPT("hv", PERF_SAMPLE_BRANCH_HV),
	BRANCH_OPT("any", PERF_SAMPLE_BRANCH_ANY),
	BRANCH_OPT("any_call", PERF_SAMPLE_BRANCH_ANY_CALL),
	BRANCH_OPT("any_ret", PERF_SAMPLE_BRANCH_ANY_RETURN),
	BRANCH_OPT("ind_call", PERF_SAMPLE_BRANCH_IND_CALL),
	BRANCH_END
};

static int
parse_branch_stack(const struct option *opt, const char *str, int unset)
{
#define ONLY_PLM \
	(PERF_SAMPLE_BRANCH_USER	|\
	 PERF_SAMPLE_BRANCH_KERNEL	|\
	 PERF_SAMPLE_BRANCH_HV)

	uint64_t *mode = (uint64_t *)opt->value;
	const struct branch_mode *br;
	char *s, *os = NULL, *p;
	int ret = -1;

	if (unset)
		return 0;

	/*
	 * cannot set it twice, -b + --branch-filter for instance
	 */
	if (*mode)
		return -1;

	/* str may be NULL in case no arg is passed to -b */
	if (str) {
		/* because str is read-only */
		s = os = strdup(str);
		if (!s)
			return -1;

		for (;;) {
			p = strchr(s, ',');
			if (p)
				*p = '\0';

			for (br = branch_modes; br->name; br++) {
				if (!strcasecmp(s, br->name))
					break;
			}
			if (!br->name) {
				ui__warning("unknown branch filter %s,"
					    " check man page\n", s);
				goto error;
			}

			*mode |= br->mode;

			if (!p)
				break;

			s = p + 1;
		}
	}
	ret = 0;

	/* default to any branch */
	if ((*mode & ~ONLY_PLM) == 0) {
		*mode = PERF_SAMPLE_BRANCH_ANY;
	}
error:
	free(os);
	return ret;
}

static const char * const record_usage[] = {
	"perf record [<options>] [<command>]",
	"perf record [<options>] -- <command> [<options>]",
	NULL
};

/*
 * XXX Ideally would be local to cmd_record() and passed to a perf_record__new
 * because we need to have access to it in perf_record__exit, that is called
 * after cmd_record() exits, but since record_options need to be accessible to
 * builtin-script, leave it here.
 *
 * At least we don't ouch it in all the other functions here directly.
 *
 * Just say no to tons of global variables, sigh.
 */
static struct perf_record record = {
	.opts = {
		.mmap_pages	     = UINT_MAX,
		.user_freq	     = UINT_MAX,
		.user_interval	     = ULLONG_MAX,
		.freq		     = 4000,
		.target		     = {
			.uses_mmap   = true,
		},
	},
	.write_mode = WRITE_FORCE,
	.file_new   = true,
};

/*
 * XXX Will stay a global variable till we fix builtin-script.c to stop messing
 * with it and switch to use the library functions in perf_evlist that came
 * from builtin-record.c, i.e. use perf_record_opts,
 * perf_evlist__prepare_workload, etc instead of fork+exec'in 'perf record',
 * using pipes, etc.
 */
const struct option record_options[] = {
	OPT_CALLBACK('e', "event", &record.evlist, "event",
		     "event selector. use 'perf list' to list available events",
		     parse_events_option),
	OPT_CALLBACK(0, "filter", &record.evlist, "filter",
		     "event filter", parse_filter),
	OPT_STRING('p', "pid", &record.opts.target.pid, "pid",
		    "record events on existing process id"),
	OPT_STRING('t', "tid", &record.opts.target.tid, "tid",
		    "record events on existing thread id"),
	OPT_INTEGER('r', "realtime", &record.realtime_prio,
		    "collect data with this RT SCHED_FIFO priority"),
	OPT_BOOLEAN('D', "no-delay", &record.opts.no_delay,
		    "collect data without buffering"),
	OPT_BOOLEAN('R', "raw-samples", &record.opts.raw_samples,
		    "collect raw sample records from all opened counters"),
	OPT_BOOLEAN('a', "all-cpus", &record.opts.target.system_wide,
			    "system-wide collection from all CPUs"),
	OPT_BOOLEAN('A', "append", &record.append_file,
			    "append to the output file to do incremental profiling"),
	OPT_STRING('C', "cpu", &record.opts.target.cpu_list, "cpu",
		    "list of cpus to monitor"),
	OPT_BOOLEAN('f', "force", &record.force,
			"overwrite existing data file (deprecated)"),
	OPT_U64('c', "count", &record.opts.user_interval, "event period to sample"),
	OPT_STRING('o', "output", &record.output_name, "file",
		    "output file name"),
	OPT_BOOLEAN('i', "no-inherit", &record.opts.no_inherit,
		    "child tasks do not inherit counters"),
	OPT_UINTEGER('F', "freq", &record.opts.user_freq, "profile at this frequency"),
	OPT_UINTEGER('m', "mmap-pages", &record.opts.mmap_pages,
		     "number of mmap data pages"),
	OPT_BOOLEAN(0, "group", &record.opts.group,
		    "put the counters into a counter group"),
	OPT_BOOLEAN('g', "call-graph", &record.opts.call_graph,
		    "do call-graph (stack chain/backtrace) recording"),
	OPT_INCR('v', "verbose", &verbose,
		    "be more verbose (show counter open errors, etc)"),
	OPT_BOOLEAN('q', "quiet", &quiet, "don't print any message"),
	OPT_BOOLEAN('s', "stat", &record.opts.inherit_stat,
		    "per thread counts"),
	OPT_BOOLEAN('d', "data", &record.opts.sample_address,
		    "Sample addresses"),
	OPT_BOOLEAN('T', "timestamp", &record.opts.sample_time, "Sample timestamps"),
	OPT_BOOLEAN('P', "period", &record.opts.period, "Sample period"),
	OPT_BOOLEAN('n', "no-samples", &record.opts.no_samples,
		    "don't sample"),
	OPT_BOOLEAN('N', "no-buildid-cache", &record.no_buildid_cache,
		    "do not update the buildid cache"),
	OPT_BOOLEAN('B', "no-buildid", &record.no_buildid,
		    "do not collect buildids in perf.data"),
	OPT_CALLBACK('G', "cgroup", &record.evlist, "name",
		     "monitor event in cgroup name only",
		     parse_cgroups),
	OPT_STRING('u', "uid", &record.opts.target.uid_str, "user",
		   "user to profile"),

	OPT_CALLBACK_NOOPT('b', "branch-any", &record.opts.branch_stack,
		     "branch any", "sample any taken branches",
		     parse_branch_stack),

	OPT_CALLBACK('j', "branch-filter", &record.opts.branch_stack,
		     "branch filter mask", "branch stack filter modes",
		     parse_branch_stack),
	OPT_END()
};

int cmd_record(int argc, const char **argv, const char *prefix __used)
{
	int err = -ENOMEM;
	struct perf_evsel *pos;
	struct perf_evlist *evsel_list;
	struct perf_record *rec = &record;
	char errbuf[BUFSIZ];

	perf_header__set_cmdline(argc, argv);

	evsel_list = perf_evlist__new(NULL, NULL);
	if (evsel_list == NULL)
		return -ENOMEM;

	rec->evlist = evsel_list;

	argc = parse_options(argc, argv, record_options, record_usage,
			    PARSE_OPT_STOP_AT_NON_OPTION);
	if (!argc && perf_target__none(&rec->opts.target))
		usage_with_options(record_usage, record_options);

	if (rec->force && rec->append_file) {
		ui__error("Can't overwrite and append at the same time."
			  " You need to choose between -f and -A");
		usage_with_options(record_usage, record_options);
	} else if (rec->append_file) {
		rec->write_mode = WRITE_APPEND;
	} else {
		rec->write_mode = WRITE_FORCE;
	}

	if (nr_cgroups && !rec->opts.target.system_wide) {
		ui__error("cgroup monitoring only available in"
			  " system-wide mode\n");
		usage_with_options(record_usage, record_options);
	}

	symbol__init();

	if (symbol_conf.kptr_restrict)
		pr_warning(
"WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,\n"
"check /proc/sys/kernel/kptr_restrict.\n\n"
"Samples in kernel functions may not be resolved if a suitable vmlinux\n"
"file is not found in the buildid cache or in the vmlinux path.\n\n"
"Samples in kernel modules won't be resolved at all.\n\n"
"If some relocation was applied (e.g. kexec) symbols may be misresolved\n"
"even with a suitable vmlinux or kallsyms file.\n\n");

	if (rec->no_buildid_cache || rec->no_buildid)
		disable_buildid_cache();

	if (evsel_list->nr_entries == 0 &&
	    perf_evlist__add_default(evsel_list) < 0) {
		pr_err("Not enough memory for event selector list\n");
		goto out_symbol_exit;
	}

	err = perf_target__validate(&rec->opts.target);
	if (err) {
		perf_target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
		ui__warning("%s", errbuf);
	}

	err = perf_target__parse_uid(&rec->opts.target);
	if (err) {
		int saved_errno = errno;

		perf_target__strerror(&rec->opts.target, err, errbuf, BUFSIZ);
		ui__error("%s", errbuf);

		err = -saved_errno;
		goto out_free_fd;
	}

	err = -ENOMEM;
	if (perf_evlist__create_maps(evsel_list, &rec->opts.target) < 0)
		usage_with_options(record_usage, record_options);

	list_for_each_entry(pos, &evsel_list->entries, node) {
		if (perf_header__push_event(pos->attr.config, event_name(pos)))
			goto out_free_fd;
	}

	if (rec->opts.user_interval != ULLONG_MAX)
		rec->opts.default_interval = rec->opts.user_interval;
	if (rec->opts.user_freq != UINT_MAX)
		rec->opts.freq = rec->opts.user_freq;

	/*
	 * User specified count overrides default frequency.
	 */
	if (rec->opts.default_interval)
		rec->opts.freq = 0;
	else if (rec->opts.freq) {
		rec->opts.default_interval = rec->opts.freq;
	} else {
		ui__error("frequency and count are zero, aborting\n");
		err = -EINVAL;
		goto out_free_fd;
	}

	err = __cmd_record(&record, argc, argv);
out_free_fd:
	perf_evlist__delete_maps(evsel_list);
out_symbol_exit:
	symbol__exit();
	return err;
}


text:
```php
use Google\Cloud\SecurityCenter\V1p1beta1\SecurityCenterClient;
use Google\Cloud\SecurityCenter\V1p1beta1\Source;

$security = new SecurityCenterClient();
$parent = SecurityCenterClient::organizationName('[YOUR ORGANIZATION]');
$source = new Source([
    'name' => SecurityCenterClient::sourceName('[YOUR ORGANIZATION]', '[YOUR SOURCE]'),
    'displayName' => '[YOUR SOURCE]'
]);

$res = $security->createSource($parent, $source);
```


text:
from django.db import models

class Member(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100, null=True)
    logoff_ts = models.DateTimeField(null=True)
    join_ts = models.DateTimeField(null=True)
    ship = models.ForeignKey('main.Ship', null=True)
    location = models.ForeignKey('main.Location', null=True)

    def __unicode__(self):
        return self.name

class Ship(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100, null=True)

    def __unicode__(self):
        return self.name

class Location(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100, null=True)

    def __unicode__(self):
        return self.name