text:
@interface DMTypeConversion : NSObject

- (FREResult) FREGetObject:(FREObject)object asString:(NSString**)value;

- (FREResult) FREGetString:(NSString*)string asObject:(FREObject*)asString;
- (FREResult) FREGetDate:(NSDate*)date asObject:(FREObject*)asDate;

- (FREResult) FRESetObject:(FREObject)asObject property:(const uint8_t*)propertyName toString:(NSString*)value;
- (FREResult) FRESetObject:(FREObject)asObject property:(const uint8_t*)propertyName toBool:(uint32_t)value;
- (FREResult) FRESetObject:(FREObject)asObject property:(const uint8_t*)propertyName toInt:(int32_t)value;
- (FREResult) FRESetObject:(FREObject)asObject property:(const uint8_t*)propertyName toDouble:(double)value;
- (FREResult) FRESetObject:(FREObject)asObject property:(const uint8_t*)propertyName toDate:(NSDate*)value;
- (FREResult)FREGetImage:(UIImage**)value asObject:(FREObject*)asImage;

- (UIImage*)thumbnailOfImage:(UIImage*)image withMaxSize:(float)maxsize;

- (FREObject)getFREBool:(BOOL) value;

@end


text:
import xmllib
import string

import ElementTree

##
# ElementTree builder for XML source data.
#
# @see elementtree.ElementTree

class TreeBuilder(xmllib.XMLParser):

    def __init__(self, html=0):
        self.__builder = ElementTree.TreeBuilder()
        if html:
            import htmlentitydefs
            self.entitydefs.update(htmlentitydefs.entitydefs)
        xmllib.XMLParser.__init__(self)

    ##
    # Feeds data to the parser.
    #
    # @param data Encoded data.

    def feed(self, data):
        xmllib.XMLParser.feed(self, data)

    ##
    # Finishes feeding data to the parser.
    #
    # @return An element structure.
    # @defreturn Element

    def close(self):
        xmllib.XMLParser.close(self)
        return self.__builder.close()

    def handle_data(self, data):
        self.__builder.data(data)

    handle_cdata = handle_data

    def unknown_starttag(self, tag, attrs):
        attrib = {}
        for key, value in attrs.items():
            attrib[fixname(key)] = value
        self.__builder.start(fixname(tag), attrib)

    def unknown_endtag(self, tag):
        self.__builder.end(fixname(tag))

def fixname(name, split=string.split):
    # xmllib in 2.0 and later provides limited (and slightly broken)
    # support for XML namespaces.
    if " " not in name:
        return name
    return "{%s}%s" % tuple(split(name, " ", 1))

if __name__ == "__main__":
    import sys
    # sanity check: look for known namespace bugs in xmllib
    p = TreeBuilder()
    text = """\
    <root xmlns='default'>
       <tag attribute='value' />
    </root>
    """
    p.feed(text)
    tree = p.close()
    status = []
    # check for bugs in the xmllib implementation
    tag = tree.find("{default}tag")
    if tag is None:
        status.append("namespaces not supported")
    if tag is not None and tag.get("{default}attribute"):
        status.append("default namespace applied to unqualified attribute")
    # report bugs
    if status:
        print "xmllib doesn't work properly in this Python version:"
        for bug in status:
            print "-", bug
    else:
        print "congratulations; no problems found in xmllib"

redpajama_set_name: RedPajamaGithub


text:
FOUNDATION_EXPORT double Pods_BackendServiceAdapter_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_BackendServiceAdapter_ExampleVersionString[];


text:
/**
 *
 */
package org.flowninja.security.oauth2.components;

import org.flowninja.persistence.generic.services.ICollectorPersistenceService;
import org.flowninja.persistence.generic.types.CollectorRecord;
import org.flowninja.security.oauth2.annotations.OAuth2LoggedIn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * This advise handles the evaluation of the {@link LoggedIn} annotation. It evaluates model bindings for {@link AdminUserDetails}
 *
 * @author rainer
 *
 * @see LoggedIn
 * @see AdminUserDetails
 */
@ControllerAdvice(annotations=OAuth2LoggedIn.class)
public class OAuth2LoggedInControllerAdvice {
	private static final Logger logger = LoggerFactory.getLogger(OAuth2LoggedInControllerAdvice.class);

	@Autowired
	private ICollectorPersistenceService collectorService;

    /**
     *
     * @return
     */
	@ModelAttribute
    public OAuth2Authentication authenticationForCurrentRequest() {
            OAuth2Authentication auth = null;

            SecurityContext ctx = SecurityContextHolder.getContext();

            if(ctx != null && ctx.getAuthentication() != null && (ctx.getAuthentication() instanceof OAuth2Authentication))
                    auth = (OAuth2Authentication)ctx.getAuthentication();

            logger.info("returning current request authentication {}", auth);

            return auth;
    }

    @ModelAttribute
	public CollectorRecord bindCallingCollector() {
    	CollectorRecord collector = null;

		OAuth2Authentication auth = authenticationForCurrentRequest();

		if(auth != null) {
			collector = collectorService.findCollectoryByClientID(auth.getOAuth2Request().getClientId());
		}

		logger.info("resolved calling client to collector {}", collector);

		return collector;
	}

}


text:
/* Code adapted from: https://scotch.io/tutorials/easy-node-authentication-setup-and-local */
const fs = require('fs');
const User = require('./models/user');
const UserValues = require('./models/user-values');
const sanitizeMongo = require('mongo-sanitize');
const sanitizeHtml = require('sanitize-html');
const shOptions = { allowedTags: [], allowedAttributes: [] };
const nodemailer = require('nodemailer'); // Send emails.
const moment = require('moment'); // Format dates.
const ejs = require('ejs'); // HTML javascript template engine.
const juice = require('juice'); // CSS inliner tool.
const juiceClient = require('juice/client');

// Standard settings for juice CSS inlining.
var juiceOptions = {
    preserveFontFaces: false,
    webResources: {
        scripts: false,
        relativeTo: "public/css"
    }
};
// Exclude these CSS properties from any juice inlining.
juiceClient.excludedProperties = [
    '-moz-box-sizing',
    '-webkit-box-sizing',
    'font-style',
    'line-height',
    '-webkit-font-smoothing',
    '-moz-osx-font-smoothing',
    'margin-left',
    'margin-right',
    'padding-left',
    'padding-right',
    '-webkit-box-shadow',
    'box-shadow',
    'position'
];

module.exports = function(app, auth, passport) {

    // Create reusable transporter object using the default SMTP transport for sending emails.
    var transporter = nodemailer.createTransport(auth.nodemailerTransport);

    // Load home page.
    app.get('/', (req, res) => {
        // Get locations.
        var locations = JSON.parse(fs.readFileSync('public/data/locations.json', 'utf8')).locations;
        // Minimum age users are allowed to be.
        var minUserAge = 18;
        // Generate new tokens on every page load.
        req.session.registerToken = genNewToken(); // used for registration and profile edits
        if(req.session.deleteToken)
            req.session.deleteToken = genNewToken();
        if (req.user) {
            req.session.searchToken = genNewToken(); // used for searching for roommates
            req.session.toggleToken = genNewToken(); // used for toggling profile visibility
        }
        // Add formatted date of birth and age to user object.
        if(req.user) {
            var userDOB = moment(req.user.dateOfBirth).utc();
            req.user.dateOfBirthFormatted = userDOB.format('YYYY-MM-DD');
        }
        // Assemble page data.
        var pageData = {
            locations: locations,
            user: req.user,
            allowedAccess: req.session ? req.session.allowedAccess : false,
            deleteToken: req.session ? req.session.deleteToken : null,
            registerToken: req.session ? req.session.registerToken : null,
            searchToken: req.session ? req.session.searchToken : null,
            toggleToken: req.session ? req.session.toggleToken : null,
            errors: req.flash('error'),
            success: req.flash('success'),
            maxDateOfBirth: moment().utc().subtract(minUserAge, 'years').format('YYYY-MM-DD')
        };
        res.render('pages/index', pageData);
    });

    // Handle registration/profile form submission.
    app.post('/', isLoggedIn, isValidRegistrationForm, (req, res) => {
        var isUpdate = req.user.completedRegistration ? true : false;
        var errorMessage = 'Registration failed. Please try again.';
        var successMessage = 'Welcome to roomM8!';
        if (isUpdate) {
            errorMessage = 'Failed to update profile. Please try again.';
            successMessage = 'Profile was successfully updated!';
        }
        // Make sure session token is valid before proceeding.
        if(!req.session.registerToken || parseInt(req.body.registerToken) !== req.session.registerToken) {
            req.flash('error', errorMessage);
            return res.redirect('/');
        }
        var query = { 'googleId' : sanitizeMongo(req.user.googleId) };
        var newData = sanitizeMongo(parseUserData(req.body));
        // Make sure newData is valid before proceeding.
        if(typeof newData === "string") {
            console.error("Data submitted was invalid: "+newData);
            req.flash('error', errorMessage);
            return res.redirect("/");
        }
        User.findOneAndUpdate(query, newData, {upsert:false}, (err, doc) => {
            if (err) {
                console.error(err.message);
                req.flash('error', errorMessage);
                return res.redirect("/");
            }
            if (isUpdate) {
                req.flash('success', successMessage);
                return res.redirect("/");
            } else {
                // Send confirmation email after new user registration.
                // Parse email address from transport string.
                var email = auth.nodemailerTransport.split(':')[1]
                            .replace('//', '').replace('%40', '@');
                // Get locations.
                var locations = JSON.parse(fs.readFileSync('public/data/locations.json', 'utf8')).locations;
                // Create user object for email.
                var user = newData;
                user.name = req.user.name;
                user.email = req.user.email;
                user.photoUrl = req.user.photoUrl;
                // Add age to user object.
                var userDOB = moment(user.dateOfBirth).utc();
                user.age = moment().utc().diff(userDOB, 'years');
                // Setup html email
                var emailPageData = {
                    email: true,
                    locations: locations,
                    user: user,
                    startDate: formatDateNumToWords(newData.startDate),
                    urlDate: moment().format('YYYY-MM-DD')
                };
                // Render email using EJS.
                ejs.renderFile('views/emails/new-user.ejs', emailPageData, (err, result) => {
                    if(err) {
                        req.flash('error', 'Unable to render email. Please try again.');
                        return res.redirect("/");
                    }
                    var initialHTML = result;
                    // Convert all CSS rules to inline.
                    juice.juiceResources(initialHTML, juiceOptions, (err, htmlPage) => {
                        if(err) {
                            req.flash('error', 'Unable to set inline CSS in email. Please try again.');
                            return res.redirect("/");
                        }
                        // Setup message.
                        var mailOptions = {
                            from: '"roomM8" <'+email+'>',
                            replyTo: '"roomM8" <'+email+'>',
                            to: '"'+user.name+'" <'+user.email+'>',
                            subject: "Welcome to roomM8!",
                            text: "Thank you for signing up for roomM8.",
                            html: htmlPage
                        };
                        // Send mail with defined transport object.
                        transporter.sendMail(mailOptions, (error, info) => {
                            if(error)
                                req.flash('error', 'Email failed to send.');
                            else
                                req.flash('success', successMessage);
                            return res.redirect("/");
                        });
                    });
                });
            }
        });
    });

    // Handle submission of secret code.
    app.post('/access', (req, res) => {
        if (typeof req.body.key === "undefined")
            return res.json({ error: 'Invalid passcode.' });
        var sess = req.session;
        if(!sess)
            return res.json({ error: 'Unknown error occurred.' });
        // Only allow 5 incorrect attempts per session.
        if(sess.accessAttempts && sess.accessAttempts >= 5)
            return res.json({ error: 'Too many attempts.' });
        var key_given = req.body.key;
        if (key_given === auth.secretKey) {
            sess.allowedAccess = true;
            sess.accessAttempts = 0;
            res.json({success: true});
        } else {
            // Incorrect keyphrase!
            if(sess.accessAttempts) {
                sess.accessAttempts++;
            } else {
                sess.accessAttempts = 1;
            }
            res.json({ error: 'Incorrect passcode. '+(5-sess.accessAttempts)+' more attempts allowed.' });
        }
    });

    // Handle submission of a new Message to another user.
    app.post('/message', isLoggedIn, isRegistered, (req, res) => {
        if (!isset(req.body.recipientID) ||
                !isset(req.body.subject) ||
                !isset(req.body.message))
            return res.json({ error: 'Please complete all required fields and try again.' });
        // Find user from recipientID.
        User.findById(sanitizeMongo(req.body.recipientID), (err, recipient) => {
            if(err)
                return res.json({ error: 'That user does not exist.' });
            // Make sure this is a new recipient (enforce single message policy).
            if(req.user.mailRecipients.includes(req.body.recipientID))
                return res.json({ error: 'You have already messaged this user. '+
                                'Please wait for them to respond via email.' });
            // Parse email address from transport string.
            var email = auth.nodemailerTransport.split(':')[1]
                        .replace('//', '').replace('%40', '@');
            // Get locations.
            var locations = JSON.parse(fs.readFileSync('public/data/locations.json', 'utf8')).locations;
            // Add age to user object.
            var userDOB = moment(req.user.dateOfBirth).utc();
            req.user.age = moment().utc().diff(userDOB, 'years');
            // Setup html email
            var emailPageData = {
                email: true,
                locations: locations,
                user: req.user,
                recipientName: recipient.name,
                subject: sanitizeInput(req.body.subject),
                message: sanitizeInput(req.body.message, 1000),
                startDate: formatDateNumToWords(req.user.startDate),
                urlDate: moment().format('YYYY-MM-DD')
            };
            // Render email using EJS.
            ejs.renderFile('views/emails/user-message.ejs', emailPageData, (err, result) => {
                if(err)
                    return res.json({ error: 'Unable to render email. Please try again.' });
                var initialHTML = result;
                // Convert all CSS rules to inline.
                juice.juiceResources(initialHTML, juiceOptions, (err, htmlPage) => {
                    if(err)
                        return res.json({ error: 'Unable to set inline CSS in email. Please try again.' });
                    // Setup message.
                    var mailOptions = {
                        from: '"roomM8" <'+email+'>',
                        replyTo: '"'+req.user.name+'" <'+req.user.email+'>',
                        to: '"'+recipient.name+'" <'+recipient.email+'>',
                        subject: "New message from " + req.user.name + ": " + sanitizeInput(req.body.subject),
                        text: sanitizeInput(req.body.message, 1000),
                        html: htmlPage
                    };
                    // Send mail with defined transport object.
                    transporter.sendMail(mailOptions, (error, info) => {
                        if(error)
                            return res.json({ error: 'Email failed to send.' });
                        // Now update the current user's list of recipients.
                        User.addMailRecipient(req.user._id, req.body.recipientID, (err) => {
                            return res.json({ success: true });
                        });
                    });
                });
            });
        });
    });

    // Preview an email message sent from the current user.
    app.get('/preview/email/message', isLoggedIn, isRegistered, (req, res) => {
        // Get locations.
        var locations = JSON.parse(fs.readFileSync('public/data/locations.json', 'utf8')).locations;
        // Add age to user object.
        var userDOB = moment(req.user.dateOfBirth).utc();
        req.user.age = moment().utc().diff(userDOB, 'years');
        var emailPageData = {
            email: true,
            locations: locations,
            user: req.user,
            recipientName: "[Recipient]",
            subject: "[Subject]",
            message: "[Your message goes here]",
            startDate: formatDateNumToWords(req.user.startDate),
            urlDate: moment().format('YYYY-MM-DD')
        };
        // Render email using EJS.
        ejs.renderFile('views/emails/user-message.ejs', emailPageData, (err, result) => {
            if(err)
                return res.json({ error: 'Unable to render email. Please try again.' });
            var initialHTML = result;
            // Convert all CSS rules to inline.
            juice.juiceResources(initialHTML, juiceOptions, (err, htmlPage) => {
                if(err)
                    return res.json({ error: 'Unable to set inline CSS in email. Please try again.' });
                res.send(htmlPage);
            });
        });
    });

    // Preview the email sent upon first sign in.
    app.get('/preview/email/first-sign-in', isLoggedIn, isRegistered, (req, res) => {
        var emailPageData = {
            email: true,
            user: req.user
        };
        // Render email using EJS.
        ejs.renderFile('views/emails/first-sign-in.ejs', emailPageData, (err, result) => {
            if(err)
                return res.json({ error: 'Unable to render email. Please try again.' });
            var initialHTML = result;
            // Convert all CSS rules to inline.
            juice.juiceResources(initialHTML, juiceOptions, (err, htmlPage) => {
                if(err)
                    return res.json({ error: 'Unable to set inline CSS in email. Please try again.' });
                res.send(htmlPage);
            });
        });
    });

    // Preview an email sent to a newly registered user.
    app.get('/preview/email/new-user', isLoggedIn, isRegistered, (req, res) => {
        // Get locations.
        var locations = JSON.parse(fs.readFileSync('public/data/locations.json', 'utf8')).locations;
        // Add age to user object.
        var userDOB = moment(req.user.dateOfBirth).utc();
        req.user.age = moment().utc().diff(userDOB, 'years');
        var emailPageData = {
            email: true,
            locations: locations,
            user: req.user,
            startDate: formatDateNumToWords(req.user.startDate),
            urlDate: moment().format('YYYY-MM-DD')
        };
        // Render email using EJS.
        ejs.renderFile('views/emails/new-user.ejs', emailPageData, (err, result) => {
            if(err)
                return res.json({ error: 'Unable to render email. Please try again.' });
            var initialHTML = result;
            // Convert all CSS rules to inline.
            juice.juiceResources(initialHTML, juiceOptions, (err, htmlPage) => {
                if(err)
                    return res.json({ error: 'Unable to set inline CSS in email. Please try again.' });
                res.send(htmlPage);
            });
        });
    });

    // Logout the current user.
    app.get('/logout', isLoggedIn, (req, res) => {
        req.logout();
        req.session.regenerate(function(err) {
            if(err)
                console.error(err);
        });
        req.flash('success', 'You have successfully signed out.');
        res.redirect('/');
    });

    // Delete the current user permanently!
    app.post('/deleteMe', isLoggedIn, isRegistered, (req, res) => {
        // Make sure user has agreed to delete and the session delete token
        // is the same as the posted delete token. Since a delete token can
        // only be given to the session after google authentication, this
        // will help ensure attackers cannot maliciously delete users.
        if(!isset(req.body.agreeToDelete) || !isset(req.body.deleteToken) ||
                !req.session.deleteToken || parseInt(req.body.deleteToken) !== req.session.deleteToken) {
            req.flash('error', 'Your account was not deleted. Please indicate that you understand the consequences and try again.');
            return res.redirect('/');
        }
        User.removeByGoogleId(req.user, (err) => {
            if(err) {
                req.flash('error', 'Your account was not deleted. Please try again.');
                return res.redirect('/');;
            }
            // Deletion successful. Logout.
            req.logout();
            req.flash('success', 'Your account was successfully deleted.');
            res.redirect('/');
        });
    });

    // Toggle profile visibility in public listing.
    app.post('/profile/toggle/visibility', isLoggedIn, isRegistered, (req, res) => {
        if(!req.session.toggleToken || parseInt(req.body.toggleToken) !== req.session.toggleToken) {
            req.flash('error', 'Failed to update profile visibility. Please try again.');
            return res.redirect('/');
        }
        var user = req.user;
        var message = user.displayProfile ? "hidden from" : "displayed in";
        var query = { 'googleId' : sanitizeMongo(user.googleId) };
        var newData = { displayProfile: !user.displayProfile };
        User.findOneAndUpdate(query, newData, {upsert:false}, (err, doc) => {
            if (err) {
                console.error(err.message);
                req.flash('error', 'Failed to update profile visibility. Please try again.');
                return res.redirect("/");
            }
            req.flash('success', 'Your profile will now be '
                        +message+' public search results.');
            return res.redirect("/");
        });
    });

    // Handle submission of a new search query for roommates.
    app.post('/api/search', (req, res) => {
        if (!req.isAuthenticated() || !req.user.completedRegistration)
            return res.json({ error: 'Not authenticated.' });
        if (!req.body.query)
            return res.json({ error: 'Invalid query.' });
        if (!req.session.searchToken || parseInt(req.body.query.searchToken) !== req.session.searchToken)
            return res.json({ error: 'Invalid session token.' });
        var query = sanitizeMongo(req.body.query);
        User.findPotentialRoommates(query, req.user, (err, roomies) => {
            if(err)
                return res.json({ error: err });
            res.json(roomies);
        });
    });

    // Send to Google to do the authentication.
    // 'Profile' scope gets basic info including name.
    app.get('/auth/google',
        passport.authenticate('google', {
            scope: ['profile', 'email']
        })
    );

    // Callback after Google has authenticated the user.
    app.get('/auth/google/callback', (req, res, next) => {
        passport.authenticate('google', (err, user, info) => {
            if (err)
                return next(err);
            if (!user)
                return res.redirect('/');
            if (info.new_user === true) {
                if (req.session && req.session.allowedAccess) {
                    // User is allowed access. Save the new user!
                    user.save((err) => {
                        if (err)
                            return next(err);
                        // Log the user in.
                        req.logIn(user, function(err) {
                            if (err)
                                return next(err);
                            // Create random token to use to confirm deletion.
                            req.session.deleteToken = genNewToken();
                            // Finally, send 'not done yet' email after signing in for the first time.
                            // Parse email address from transport string.
                            var email = auth.nodemailerTransport.split(':')[1]
                                        .replace('//', '').replace('%40', '@');
                            // Setup html email.
                            var emailPageData = {
                                email: true,
                                user: user
                            };
                            // Render email using EJS.
                            ejs.renderFile('views/emails/first-sign-in.ejs', emailPageData, (err, result) => {
                                if(err) {
                                    req.flash('error', 'Unable to render email. Please try again.');
                                    return res.redirect("/");
                                }
                                var initialHTML = result;
                                // Convert all CSS rules to inline.
                                juice.juiceResources(initialHTML, juiceOptions, (err, htmlPage) => {
                                    if(err) {
                                        req.flash('error', 'Unable to set inline CSS in email. Please try again.');
                                        return res.redirect("/");
                                    }
                                    // Setup message.
                                    var mailOptions = {
                                        from: '"roomM8" <'+email+'>',
                                        replyTo: '"roomM8" <'+email+'>',
                                        to: '"'+user.name+'" <'+user.email+'>',
                                        subject: "You're almost done, "+user.name.split(' ')[0]+"!",
                                        text: "Please complete your profile to continue using roomM8.",
                                        html: htmlPage
                                    };
                                    // Send mail with defined transport object.
                                    transporter.sendMail(mailOptions, (error, info) => {
                                        if(error) {
                                            req.flash('error', 'Email failed to send.');
                                            return res.redirect("/");
                                        }
                                        return res.redirect('/#success');
                                    });
                                });
                            });
                        });
                    });
                } else {
                    // User is not allowed access!
                    if(req.session)
                        req.flash('error', 'You cannot sign up until you enter the correct keyphrase!');
                    return res.redirect('/');
                }
            } else {
                // Old user that already exists.
                req.logIn(user, function(err) {
                    if (err)
                        return next(err);
                    // Create random token to use to confirm deletion.
                    req.session.deleteToken = genNewToken();
                    // If the user has completed registration, redirect to browsing page.
                    if(user.completedRegistration) {
                        req.flash('success', 'Welcome back!');
                        return res.redirect('/');
                    }
                    // Otherwise, prompt to complete registration.
                    return res.redirect('/#success');
                });
            }
        })(req, res, next);
    });

};

// Check if a variable is valid.
function isset(a) {
    return typeof a !== "undefined" && a !== null && a !== "";
}

// Route middleware to make sure user has entered keyphrase.
function hasEnteredKey(req, res, next) {
    if (req.session && req.session.allowedAccess)
        return next();
    res.redirect('/');
}

// Route middleware to make sure a user is logged in.
function isLoggedIn(req, res, next) {
    // If user is authenticated in the session, carry on.
    if (req.isAuthenticated())
        return next();
    // If they aren't, redirect them to the home page.
    req.flash('error', 'You are not signed in. Please sign in and try again.');
    res.redirect('/');
}

// Route middleware to make sure a user has fully completed their registration.
function isRegistered(req, res, next) {
    if (req.user.completedRegistration)
        return next();
    // If user has not registered, redirect them to the home page.
    req.flash('error', 'You have not completed your registration. Please finish signing up and try again.');
    res.redirect('/');
}

// Route middleware to make sure registration form is valid.
function isValidRegistrationForm(req, res, next) {
    if(isset(req.body.dateOfBirth) &&
            isset(req.body.gender) &&
            isset(req.body.field) &&
            isset(req.body.role) &&
            isset(req.body.position) &&
            isset(req.body.startDate) &&
            isset(req.body.startLocation) &&
            isset(req.body.hasPlace) &&
            isset(req.body.factorCleanliness) &&
            isset(req.body.factorQuietTime) &&
            isset(req.body.factorSubstanceFree) &&
            isset(req.body.factorSameGender) &&
            isset(req.body.factorSameAge) &&
            isset(req.body.factorSameField) &&
            isset(req.body.agree1) &&
            // Either preferences or current residence.
            (isset(req.body.prefLocations) ||
                isset(req.body.resLocation))) {
        return next();
    }
    req.flash('error', 'You did not fill in all the required fields. Please try again.');
    res.redirect('/');
}

// Parse form data into user object, making sure to sanitize it first.
function parseUserData(body) {
    // Make sure date of birth is valid.
    var dateOfBirth = moment(sanitizeInput(body.dateOfBirth));
    if(!dateOfBirth.isValid())
        return "date of birth"; // error
    // Make sure start date is valid.
    var startDate = moment(sanitizeInput(body.startDate), 'YYYY-MM');
    if(!startDate.isValid())
        return "start date"; // error
    // Make sure gender is valid.
    var gender = sanitizeInput(body.gender);
    if(!UserValues.genders.includes(gender))
        return "gender"; // error
    // Make sure field is valid.
    var field = sanitizeInput(body.field);
    if(!UserValues.fields.includes(field))
        return "field"; // error
    // Make sure role is valid.
    var role = sanitizeInput(body.role);
    if(!UserValues.roles.includes(role))
        return "role"; // error
    // Make sure startLocation is valid.
    var startLocation = parseInt(sanitizeInput(body.startLocation));
    if(startLocation < UserValues.startLocationMin || startLocation > UserValues.startLocationMax)
        return "start location"; // error
    var newData = {
        completedRegistration: true,
        dateOfBirth: dateOfBirth,
        gender: gender,
        showAge: (body.showAge === "yes"),
        showGender: (body.showGender === "yes"),
        field: field,
        role: role,
        position: sanitizeInput(body.position, 50),
        startDate: startDate.format('YYYY-MM'),
        startLocation: startLocation,
        hasPlace: (body.hasPlace === "yes"),
        agree1: true,
        agree2: true,
        factors: {
            cleanliness: parseInt(sanitizeInput(body.factorCleanliness)),
            quietTime: parseInt(sanitizeInput(body.factorQuietTime)),
            substanceFree: parseInt(sanitizeInput(body.factorSubstanceFree)),
            sameGender: parseInt(sanitizeInput(body.factorSameGender)),
            sameAge: parseInt(sanitizeInput(body.factorSameAge)),
            sameField: parseInt(sanitizeInput(body.factorSameField))
        }
    };
    if(body.aboutMe) {
        newData.aboutMe = sanitizeInput(body.aboutMe, 400);
    }
    if(body.genderCustom) {
        newData.genderCustom = sanitizeInput(body.genderCustom);
    }
    if(body.fieldCustom) {
        newData.fieldCustom = sanitizeInput(body.fieldCustom);
    }
    if(body.roleCustom) {
        newData.roleCustom = sanitizeInput(body.roleCustom);
    }
    if(!newData.hasPlace) {
        // Make sure residenceType is valid.
        var residenceType = sanitizeInput(body.prefResidenceType);
        if(!UserValues.preferenceResTypes.includes(residenceType))
            return "preference residence type"; // error
        // Make sure number of preferred roommates (range) is valid.
        var roommates = sanitizeInput(body.prefRoommates).split(',');
        if(roommates.length !== 2 || roommates[0] > roommates[1] ||
                roommates[0] < UserValues.roommatesMin ||
                roommates[1] < UserValues.roommatesMin ||
                roommates[0] > UserValues.roommatesMax ||
                roommates[1] > UserValues.roommatesMax)
            return "roommates"; // error
        newData.preferences = {
            locations: sanitizeArray(body.prefLocations),
            residenceType: residenceType,
            roommates: roommates,
            durationInMonths: body.prefDuration ? parseInt(sanitizeInput(body.prefDuration)) : -1,
            maxCommuteTimeInMins: parseInt(sanitizeInput(body.prefMaxCommuteTime))
        };
        newData.factors.location = parseInt(sanitizeInput(body.factorLocation));
        newData.factors.residenceType = parseInt(sanitizeInput(body.factorResidence));
        newData.factors.ownBedroom = parseInt(sanitizeInput(body.factorOwnBedroom));
        newData.factors.ownBathroom = parseInt(sanitizeInput(body.factorOwnBathroom));
        newData.factors.commuteTime = parseInt(sanitizeInput(body.factorCommuteTime));
    } else {
        // Make sure residenceType is valid.
        var residenceType = sanitizeInput(body.resType);
        if(!UserValues.currentResTypes.includes(residenceType))
            return "current residence type"; // error
        newData.currentResidence = {
            location: sanitizeInput(body.resLocation),
            residenceType: residenceType,
            vacantRooms: parseInt(sanitizeInput(body.resBedrooms)),
            bathrooms: parseInt(sanitizeInput(body.resBathrooms)),
            durationInMonths: body.resDuration ? parseInt(sanitizeInput(body.resDuration)) : -1,
            commuteTimeInMins: parseInt(sanitizeInput(body.resCommuteTime))
        };
        if(body.resTypeCustom) {
            newData.currentResidence.residenceTypeCustom = sanitizeInput(body.resTypeCustom);
        }
    }
    return newData;
}
// Html-Sanitize data inputted by the user.
// Also enforce maximum character limit.
function sanitizeInput(input, maxChar=30) {
    return sanitizeHtml(input, shOptions).substring(0, maxChar);
}
// Html-Sanitize the data in an array.
// Also enforce max length.
function sanitizeArray(arr, maxLength=10) {
    if(typeof arr !== "object")
        arr = [arr];
    var newArr = [];
    for(var i=0; i<Math.min(arr.length, maxLength); i++) {
        newArr.push(sanitizeInput(arr[i]));
    }
    return newArr;
}

// Format date. Convert from '2017-09' to 'September 2017'
function formatDateNumToWords(dateString) {
    var options = {
        year: "numeric", month: "long"
    };
    return new Date(dateString+"-02").toLocaleDateString("en-US", options);
}

// Generate new token for session.
function genNewToken() {
    return getRandomInt(1000000000,
                        9999999999);
}
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
}


text:
extern void
QDFlushPortBuffer(
                  CGrafPtr    port,
                  RgnHandle   region);

// For now, optimize for 1 nib file.
static IBNibRef     sNibRef;
static CFStringRef	sNibName;

// Default window handler detects close of self
static const EventTypeSpec  kWU_DefaultEvents[] =
{
	{ kEventClassWindow, kEventWindowClosed }
};

static OSStatus WU_DefaultEventHandler( EventHandlerCallRef inCaller, EventRef inEvent, void* inRefcon )	// Note inRefCon is a WindowRef * !!!!
{
    OSStatus    err        = eventNotHandledErr;
	WindowRef*	windowRefP = (WindowRef*) inRefcon;

	// Already closed?
	if (!windowRefP || !*windowRefP)
		return err;

	switch ( GetEventKind( inEvent ) )
	{
		case kEventWindowClosed:
			*windowRefP = NULL;

			err = noErr;
			break;
	};

    return err;
}

static DEFINE_ONE_SHOT_HANDLER_GETTER( WU_DefaultEventHandler )

void	WU_CreateWindowFromNib(const char * nibFileName, const char * windowName, WindowRef& outWindowRef, UInt32 options )
{
	CFStringRef	nibName = CFStringCreateWithCString(kCFAllocatorDefault, nibFileName, kCFStringEncodingUTF8);
	CFStringRef	winName = CFStringCreateWithCString(kCFAllocatorDefault, windowName,  kCFStringEncodingUTF8);

	outWindowRef = NULL;

	// Check for changing nib files
	if (sNibRef && !CFEqual(sNibName, nibName))
	{
		DisposeNibReference(sNibRef);  sNibRef =  NULL;
		CFRelease          (sNibName); sNibName = NULL;
	}

	// Cache nib file reference
	if (!sNibRef)
	{
		CreateNibReference(nibName, &sNibRef);
		sNibName = nibName;
		CFRetain(sNibName);
	}

	if (!sNibRef)
		return;

	CreateWindowFromNib( sNibRef, winName, &outWindowRef);

	// Apply options
	if (outWindowRef)
	{
		if (options & WU_ShowWindowWhenCreated)
			ShowWindow(outWindowRef);

		if (options & WU_FlushQDWhenCreated)
			QDFlushPortBuffer(GetWindowPort(outWindowRef), NULL);

		if (WU_InstallDefaultEventHandler)
			InstallWindowEventHandler( outWindowRef, GetWU_DefaultEventHandlerUPP(),
                               GetEventTypeCount( kWU_DefaultEvents ), kWU_DefaultEvents,
                               &outWindowRef, NULL );
	}
}


text:
package de.hub.cs.dbis.aeolus.monitoring.throughput;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.tuple.Values;

/**
 * {@link SpoutThroughputCounter} reports statistical values to a regular stream in a topology using an
 * {@link SpoutOutputCollector}.
 *
 * @author mjsax
 */
class SpoutThroughputCounter extends AbstractThroughputCounter {

	/** The internally used output collector. */
	private final SpoutOutputCollector collector;

	/** The ID of the report stream. */
	protected final String reportStream;

	/**
	 * Instantiates a new {@link SpoutThroughputCounter} that emits the statistical values to the stream
	 * {@code reportStream} using the given output collector.
	 *
	 * @param collector
	 *            The output collector for emitting statistical values.
	 * @param reportStream
	 *            The ID of the statistical report stream.
	 * @param taskId
	 *            The task ID.
	 */
	public SpoutThroughputCounter(SpoutOutputCollector collector, String reportStream, int taskId) {
		super(false, taskId);
		this.collector = collector;
		this.reportStream = reportStream;
	}

	/**
	 * {@inheritDoc}
	 *
	 * The report is done, by emitting the value to the configures output stream.
	 */
	@Override
	void doEmit(Values statsTuple) {
		this.collector.emit(this.reportStream, statsTuple);
	}

}


text:
/*
 * Package Name : wm.fix.manager.ui
 * Class Name   : FixManagerUIResourceBundle
 *
 * Created by   : Igor Androsov
 * Created on   : May 17, 2006
 * Change log:
 *
 * Date			Author				Description
 * --------------------------------------------------------------------------------
 * 2006/05/17	Igor Androsov		version 1.0
 * 				webMethods
 *
 * ---------------------------------------------------------------------------------
 */
package wm.fix.manager.ui;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;

public class FixManagerUIResourceBundle extends PropertyResourceBundle
{
	public FixManagerUIResourceBundle(InputStream is) throws IOException
	{
			super(is);
			// Test case

	}
	public String getLocalizedString(String key)
	{
		String res = "";

		//String str = (String)handleGetObject(key);
		try
		{
			res = getString(key);
			//res = new String(str.getBytes(),"ISO 8859-1");
		}
		catch (Exception e)
		{
			res = "UNKNOWN";
		}
		return res;
	}
	public void dumpStrings()
	{
		System.out.println("##### Dump string table #####");
		Enumeration en = this.getKeys();
		while(en.hasMoreElements())
		{
			String key = (String)en.nextElement();
			String val = (String)this.getString(key);
			System.out.println(key+" = "+val);
		}
	}

}


text:
<?php

namespace Elastica\Query;

/**
 * SpanTerm query.
 *
 * @author Alessandro Chitolina <alekitto@gmail.com>
 * @author Marek Hernik <marek.hernik@gmail.com>
 *
 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-span-term-query.html
 */
class SpanTerm extends AbstractSpanQuery
{
    /**
     * Constructs the SpanTerm query object.
     *
     * @param array $term Calls setRawTerm with the given $term array
     */
    public function __construct(array $term = [])
    {
        $this->setRawTerm($term);
    }

    /**
     * Set term can be used instead of setTerm if some more special
     * values for a term have to be set.
     *
     * @param array $term Term array
     *
     * @return $this
     */
    public function setRawTerm(array $term): self
    {
        return $this->setParams($term);
    }

    /**
     * Adds a term to the term query.
     *
     * @param string       $key   Key to query
     * @param string|array $value Values(s) for the query. Boost can be set with array
     * @param float        $boost OPTIONAL Boost value (default = 1.0)
     *
     * @return $this
     */
    public function setTerm(string $key, $value, float $boost = 1.0): self
    {
        return $this->setRawTerm([$key => ['value' => $value, 'boost' => $boost]]);
    }
}


text:
<?php
require("../includes/config.php");

	if ($_SESSION['CME_USER']['type'] == "mro") { $btncolor = "btn btn-primary";}
	else {$btncolor = "btn btn-success";}

//START DB CONNECTION
require("../includes/mysqlwrapper_class.php");
$conn = new mysqlwrapper_class;

$getCompanyNo = $conn->execute_sql("select", array("*"), "organisation_agreements JOIN e_accounts ON oa_ea_name = ea_id", "oa_id =?", array("i" => $_POST['callValues']));

$selectExpert = $conn->execute_sql("select", array("*"), "e_accounts", "ea_id=?", array("i" =>  $getCompanyNo[0]['oa_ea_name']));

//var_dump($_POST);

?>

Are you sure you want to enable <?php echo $selectExpert[0]['ea_forename'] . " " . $selectExpert[0]['ea_surname'] ?>?

            <form id="enableAgreementForm" method="post" action="">

                Initial Reason:

<?php echo $getCompanyNo[0]['oa_cancellation_reason']; ?>

                <input type="hidden" class = "form-control" name="agreedmentId" value="<?php echo $getCompanyNo[0]['oa_id']; ?>" />
                <input type="hidden" class = "form-control" name="expertID" value="<?php echo $getCompanyNo[0]['ea_id']; ?>" />
                <input type="hidden" class = "form-control" name="mroCompany" value="<?php echo $getCompanyNo[0]['oa_mo_name']; ?>" />

                <input type="submit" id="enableAgreement" value="Confirm" class = "<?php echo $btncolor; ?> btn-lg col-md-12" />

            </form>


text:
declare module 'mattermost-redux/client/client' {
    declare export default mattermost$redux$Client3;
}

declare module 'mattermost-redux/client/client.js' {
    declare export default mattermost$redux$Client3;
}

declare class mattermost$redux$Client3 {

}


text:
<?php
namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class UserController extends Controller
{
    public function showAction($name)
    {
        $user = $this->getDoctrine()->getManager()
            ->getRepository('AcmeDemoBundle:Users')
            ->findOneByName($name);

        return $this->render('AcmeDemoBundle:Blog:user.html.twig', array('user' => $user

        ));
    }

}


text:
package org.apache.druid.segment.join.filter;

import org.apache.druid.java.util.common.Pair;
import org.apache.druid.math.expr.Expr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * Represents an analysis of what base table columns, if any, can be correlated with a column that will
 * be filtered on.
 * <p>
 * For example, if we're joining on a base table via the equiconditions (id = j.id AND f(id2) = j.id2),
 * then we can correlate j.id with id (base table column) and j.id2 with f(id2) (a base table expression).
 */
public class JoinFilterColumnCorrelationAnalysis
{
  private final String joinColumn;
  private final List<String> baseColumns;
  private final List<Expr> baseExpressions;
  private Map<Pair<String, String>, Optional<Set<String>>> correlatedValuesMap;

  public JoinFilterColumnCorrelationAnalysis(
      String joinColumn,
      Set<String> baseColumns,
      Set<Expr> baseExpressions
  )
  {
    this.joinColumn = joinColumn;
    this.baseColumns = new ArrayList<>(baseColumns);
    this.baseExpressions = new ArrayList<>(baseExpressions);
    this.baseColumns.sort(String.CASE_INSENSITIVE_ORDER);
    this.correlatedValuesMap = new HashMap<>();
  }

  public String getJoinColumn()
  {
    return joinColumn;
  }

  public List<String> getBaseColumns()
  {
    return baseColumns;
  }

  public List<Expr> getBaseExpressions()
  {
    return baseExpressions;
  }

  public Map<Pair<String, String>, Optional<Set<String>>> getCorrelatedValuesMap()
  {
    return correlatedValuesMap;
  }

  public boolean supportsPushDown()
  {
    return !baseColumns.isEmpty() || !baseExpressions.isEmpty();
  }
}


text:
package main

import (
	"bytes"
	"image"
	_ "image/gif"
	"image/jpeg"
	_ "image/png"
	"io/ioutil"
	"vip/fetch"
	"vip/test"

	. "gopkg.in/check.v1"
)

var (
	sizes = map[int]int{
		250:  333,
		500:  666,
		160:  213,
		720:  960,
		1024: 1365,
		683:  910,
		431:  574,
	}
	noExifSizes = map[int]int{
		250:  156,
		500:  312,
		160:  100,
		720:  450,
		1024: 640,
		683:  426,
		431:  269,
	}
)

var (
	_ = Suite(&ResizeSuite{})
)

type ResizeSuite struct{}

func (s *ResizeSuite) SetUpSuite(c *C) {
	setUpSuite(c)
}

func (s *ResizeSuite) SetUpTest(c *C) {
	setUpTest(c)

	storage = test.NewStore()
}

func (s *ResizeSuite) BenchmarkThumbnailResize(c *C) {
	file, err := ioutil.ReadFile("test/awesome.jpeg")
	c.Assert(err, IsNil)

	ctx := &fetch.CacheContext{
		Width: 160,
	}

	for i := 0; i < c.N; i++ {
		// Need a new io.Reader on every iteration
		buf := bytes.NewReader(file)
		_, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)
	}
}

func (s *ResizeSuite) BenchmarkLargeResize(c *C) {
	file, err := ioutil.ReadFile("test/awesome.jpeg")
	c.Assert(err, IsNil)

	ctx := &fetch.CacheContext{
		Width: 720,
	}

	for i := 0; i < c.N; i++ {
		// Need a new io.Reader on every iteration
		buf := bytes.NewReader(file)
		_, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)
	}
}

func (s *ResizeSuite) BenchmarkSquareThumbnail(c *C) {
	file, err := ioutil.ReadFile("test/awesome.jpeg")
	c.Assert(err, IsNil)

	ctx := &fetch.CacheContext{
		Width: 180,
		Crop:  true,
	}

	for i := 0; i < c.N; i++ {
		// Need a new io.Reader on every iteration
		buf := bytes.NewReader(file)
		_, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)
	}
}

func (s *ResizeSuite) TestResizeImage(c *C) {
	file, err := ioutil.ReadFile("test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	for width, height := range sizes {
		ctx := &fetch.CacheContext{
			Width: width,
		}

		data := bytes.NewBuffer(file)

		orig, _, err := fetch.GetRotatedImage(data)
		c.Check(err, IsNil)

		buf := new(bytes.Buffer)
		jpeg.Encode(buf, orig, nil)

		resized, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)
		c.Check(image.Bounds().Size().X, Equals, width)
		c.Check(image.Bounds().Size().Y, Equals, height)
	}
}

func (s *ResizeSuite) TestResizeImageSquare(c *C) {
	file, err := ioutil.ReadFile("test/awesome.jpeg")
	c.Assert(err, IsNil)

	for width, _ := range sizes {
		ctx := &fetch.CacheContext{
			Width: width,
			Crop:  true,
		}

		buf := bytes.NewReader(file)
		resized, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)

		if width > 768 {
			width = 768
		}

		c.Check(image.Bounds().Size().X, Equals, width)
		c.Check(image.Bounds().Size().Y, Equals, width)
	}
}

func (s *ResizeSuite) TestResizeOversizedImageSquare(c *C) {
	file, err := ioutil.ReadFile("test/awesome-small.jpg")
	c.Assert(err, IsNil)

	ctx := &fetch.CacheContext{
		Width: 400,
		Crop:  true,
	}

	buf := bytes.NewReader(file)
	resized, err := fetch.Resize(buf, ctx)
	c.Check(err, IsNil)

	image, _, err := image.Decode(resized)
	c.Check(err, IsNil)
	c.Check(image.Bounds().Size().X, Equals, 150)
	c.Check(image.Bounds().Size().Y, Equals, 150)
}

func (s *ResizeSuite) TestCropNoResize(c *C) {
	file, err := ioutil.ReadFile("test/awesome-small.jpg")
	c.Assert(err, IsNil)

	ctx := &fetch.CacheContext{
		Width: 0,
		Crop:  true,
	}

	buf := bytes.NewReader(file)
	resized, err := fetch.Resize(buf, ctx)
	c.Check(err, IsNil)

	image, _, err := image.Decode(resized)
	c.Check(err, IsNil)
	c.Check(image.Bounds().Size().X, Equals, 150)
	c.Check(image.Bounds().Size().Y, Equals, 150)
}

func (s *ResizeSuite) TestResizeNoExifImage(c *C) {
	file, err := ioutil.ReadFile("test/AWESOME.jpg")
	c.Assert(err, IsNil)

	for width, height := range noExifSizes {
		ctx := &fetch.CacheContext{
			Width: width,
		}

		buf := bytes.NewReader(file)
		resized, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)
		c.Check(image.Bounds().Size().X, Equals, width)
		c.Check(image.Bounds().Size().Y, Equals, height)
	}
}

func (s *ResizeSuite) TestResizeStaticGif(c *C) {
	file, err := ioutil.ReadFile("test/static.gif")
	c.Assert(err, IsNil)

	for width, _ := range sizes {
		ctx := &fetch.CacheContext{
			Width: width,
		}

		buf := bytes.NewReader(file)
		resized, err := fetch.ResizeGif(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)
		c.Check(image.Bounds().Size().X, Equals, width)
	}
}

func (s *ResizeSuite) TestResizeAnimatedGif(c *C) {
	file, err := ioutil.ReadFile("test/animated.gif")
	c.Assert(err, IsNil)

	for width, _ := range sizes {
		ctx := &fetch.CacheContext{
			Width: width,
		}

		buf := bytes.NewReader(file)
		resized, err := fetch.ResizeGif(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)
		c.Check(image.Bounds().Size().X, Equals, width)
	}
}

func (s *ResizeSuite) insertMockImage() (*fetch.CacheContext, error) {
	file, err := ioutil.ReadFile("test/exif_test_img.jpg")
	if err != nil {
		return nil, err
	}

	data := bytes.NewBuffer(file)

	image, _, err := fetch.GetRotatedImage(data)
	if err != nil {
		return nil, err
	}

	buf := new(bytes.Buffer)
	jpeg.Encode(buf, image, nil)

	// Push the file data into the mock datastore
	storage.PutReader("test_bucket", "test_id", buf, int64(len(file)), "image/jpeg")

	return &fetch.CacheContext{
		ImageId: "test_id",
		Bucket:  "test_bucket",
	}, err
}

func (s *ResizeSuite) TestOriginalColdCache(c *C) {
	// Open the file once to get it's size
	file, err := ioutil.ReadFile("test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	img, _, err := image.Decode(bytes.NewReader(file))
	c.Assert(err, IsNil)

	// Since this image should be rotated, height should equal
	// width after it's uploaded.
	originalSize := img.Bounds().Size().Y

	// A single, unresized image is in the database/store
	ctx, err := s.insertMockImage()
	c.Assert(err, IsNil)

	// Run the image resize request
	data, err := fetch.ImageData(storage, ctx)
	c.Assert(err, IsNil)

	// Verify the size of the resulting byte slice
	img, _, err = image.Decode(bytes.NewReader(data))
	c.Assert(err, IsNil)
	c.Assert(img.Bounds().Size().X, Equals, originalSize)
}

func (s *ResizeSuite) TestResizeColdCache(c *C) {
	// A single, unresized image is in the database/store
	mockCtx, err := s.insertMockImage()
	c.Assert(err, IsNil)

	for width, height := range sizes {
		ctx := &fetch.CacheContext{
			ImageId: mockCtx.ImageId,
			Bucket:  mockCtx.Bucket,
			Width:   width,
		}

		// Run the image resize request
		data, err := fetch.ImageData(storage, ctx)
		c.Assert(err, IsNil)

		// Verify the size of the resulting byte slice
		img, _, err := image.Decode(bytes.NewReader(data))
		c.Assert(err, IsNil)
		c.Assert(img.Bounds().Size().X, Equals, width)
		c.Assert(img.Bounds().Size().Y, Equals, height)
	}
}

func (s *ResizeSuite) TestResizeCropColdCache(c *C) {
	// A single, unresized image is in the database/store
	mockCtx, err := s.insertMockImage()
	c.Assert(err, IsNil)

	for width, height := range sizes {
		ctx := &fetch.CacheContext{
			ImageId: mockCtx.ImageId,
			Bucket:  mockCtx.Bucket,
			Width:   width,
			Crop:    true,
		}

		// Run the image resize request
		data, err := fetch.ImageData(storage, ctx)
		c.Assert(err, IsNil)

		// Verify the size of the resulting byte slice
		img, _, err := image.Decode(bytes.NewReader(data))
		c.Assert(err, IsNil)
		c.Assert(img.Bounds().Size().X, Equals, img.Bounds().Size().Y)
		c.Assert(img.Bounds().Size().X > 0, Equals, true)
		c.Assert(img.Bounds().Size().X <= height, Equals, true)
	}
}


text: Android app code to go in this directory


text:
package archimulator.core;

import archimulator.common.CPUExperiment;
import archimulator.common.Simulation;
import archimulator.common.SimulationObject;
import archimulator.common.report.Reportable;

/**
 * Memory hierarchy thread.
 *
 * @author Min Cai
 */
public interface MemoryHierarchyThread extends SimulationObject<CPUExperiment, Simulation>, Reportable {
    /**
     * Get the number of the thread.
     *
     * @return the number of the thread
     */
    int getNum();

    /**
     * Get the ID of the thread.
     *
     * @return the ID of the thread
     */
    int getId();

    /**
     * Get the name of the thread.
     *
     * @return the name of the thread
     */
    String getName();

    /**
     * Get the parent core.
     *
     * @return the parent core
     */
    MemoryHierarchyCore getCore();
}


text:
package github.pasiahopelto.scorelib.fetcher;

import static org.junit.Assert.*;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import com.google.common.collect.Lists;

import github.pasiahopelto.scorelib.DbConfig;
import github.pasiahopelto.scorelib.model.Score;
import github.pasiahopelto.scorelib.model.Selection;

@RunWith(MockitoJUnitRunner.class)
public class TestSelectionScorer {

	private static final String NO_VOTING_NAME = "no voting name";
	private static final String VOTE_NO = "no";
	private static final String VOTE_YES = "yes";
	private static final String VOTING_NAME = "voting name one";
	private static final String VOTING_NAME_TWO = "voting name two";
	private static final String PARTY_ONE = "party one";
	private static final String PARTY_TWO = "party two";
	private static final String PARTY_THREE = "party three";

	@InjectMocks
	private SelectionScorer scorer;

	private JdbcTemplate jdbcTemplate;
	private ArrayList<Selection> selections = Lists.newArrayList();

	@Before
	public void before() {
		ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(DbConfig.class);
		jdbcTemplate = context.getBean(JdbcTemplate.class);
		context.close();
	}

	@Test
	public void returnsEmptyListIfSelectionIsEmpty() {
		assertTrue(scorer.scoreAndSort(jdbcTemplate, Lists.newArrayList()).isEmpty());
	}

	@Test
	public void returnsEmptyListIfSelectedVotingDoesNotMatchAvailableVotings() {
		specifySelection(NO_VOTING_NAME, VOTE_YES);
		assertTrue(scorer.scoreAndSort(jdbcTemplate, selections).isEmpty());
	}

	@Test
	public void returnsSolePartyWithScore() {
		specifySelection(VOTING_NAME, VOTE_YES);
		List<Score> scores = scorer.scoreAndSort(jdbcTemplate, selections);
		assertEquals(1, scores.size());
		verifyVote(scores.get(0), PARTY_ONE, 0.66f);
	}

	@Test
	public void returnsPartiesWithScoresAndSortsByPercentageAndVoteCount() {
		specifySelection(VOTING_NAME_TWO, VOTE_YES);
		List<Score> scores = scorer.scoreAndSort(jdbcTemplate, selections);
		assertEquals(3, scores.size());
		verifyVote(scores.get(2), PARTY_THREE, 1);
		verifyVote(scores.get(1), PARTY_ONE, 1);
		verifyVote(scores.get(0), PARTY_TWO, 0);
	}

	@Test
	public void selectsFromMultipleVotings() {
		specifySelection(VOTING_NAME, VOTE_NO);
		specifySelection(VOTING_NAME_TWO, VOTE_YES);
		List<Score> scores = scorer.scoreAndSort(jdbcTemplate, selections);
		assertEquals(3, scores.size());
		verifyVote(scores.get(2), PARTY_THREE, 1);
		verifyVote(scores.get(1), PARTY_ONE, 0.28f);
		verifyVote(scores.get(0), PARTY_TWO, 0f);
	}

	private void verifyVote(Score score, String party, float percentage) {
		assertEquals(party, score.getParty());
		assertEquals(score.toString(), percentage, score.getPercentage(), 0.01f);
	}

	private void specifySelection(String votingName, String vote) {
		Selection selection = new Selection();
		selection.setVotingName(votingName);
		selection.setVote(vote);
		selections.add(selection);
	}
}


text:
package com.siyeh.ig.controlflow;

import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ui.CheckBox;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class OverlyComplexBooleanExpressionInspectionBase extends BaseInspection {
  protected static final Set<IElementType> s_booleanOperators = new HashSet<>(5);

  static {
    s_booleanOperators.add(JavaTokenType.ANDAND);
    s_booleanOperators.add(JavaTokenType.OROR);
    s_booleanOperators.add(JavaTokenType.XOR);
    s_booleanOperators.add(JavaTokenType.AND);
    s_booleanOperators.add(JavaTokenType.OR);
  }

  /**
   * @noinspection PublicField
   */
  public int m_limit = 3;
  /**
   * @noinspection PublicField
   */
  public boolean m_ignorePureConjunctionsDisjunctions = true;

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("overly.complex.boolean.expression.display.name");
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    final Integer termCount = (Integer)infos[0];
    return InspectionGadgetsBundle.message("overly.complex.boolean.expression.problem.descriptor", termCount);
  }

  @Override
  public JComponent createOptionsPanel() {
    final JPanel panel = new JPanel(new GridBagLayout());
    final CheckBox ignoreConjunctionsDisjunctionsCheckBox =
      new CheckBox(InspectionGadgetsBundle.message("overly.complex.boolean.expression.ignore.option"),
                   this, "m_ignorePureConjunctionsDisjunctions");
    final NumberFormat formatter = NumberFormat.getIntegerInstance();
    formatter.setParseIntegerOnly(true);
    final JFormattedTextField termLimitTextField = prepareNumberEditor("m_limit");

    final GridBagConstraints constraints = new GridBagConstraints();
    final JLabel label = new JLabel(InspectionGadgetsBundle.message("overly.complex.boolean.expression.max.terms.option"));

    constraints.anchor = GridBagConstraints.BASELINE_LEADING;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    panel.add(label, constraints);

    constraints.fill = GridBagConstraints.NONE;
    constraints.gridx = 1;
    panel.add(termLimitTextField, constraints);

    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.gridwidth = 2;
    constraints.weightx = 1.0;
    constraints.weighty = 1.0;
    panel.add(ignoreConjunctionsDisjunctionsCheckBox, constraints);
    return panel;
  }

  @Override
  protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
    return true;
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new OverlyComplexBooleanExpressionVisitor();
  }

  private class OverlyComplexBooleanExpressionVisitor extends BaseInspectionVisitor {

    @Override
    public void visitPolyadicExpression(@NotNull PsiPolyadicExpression expression) {
      super.visitPolyadicExpression(expression);
      checkExpression(expression);
    }

    @Override
    public void visitPrefixExpression(@NotNull PsiPrefixExpression expression) {
      super.visitPrefixExpression(expression);
      checkExpression(expression);
    }

    @Override
    public void visitParenthesizedExpression(@NotNull PsiParenthesizedExpression expression) {
      super.visitParenthesizedExpression(expression);
      checkExpression(expression);
    }

    private void checkExpression(PsiExpression expression) {
      if (!isBoolean(expression)) {
        return;
      }
      final PsiElement parent = expression.getParent();
      if (parent instanceof PsiExpression && isBoolean((PsiExpression)parent)) {
        return;
      }
      final int numTerms = countTerms(expression);
      if (numTerms <= m_limit) {
        return;
      }
      if (m_ignorePureConjunctionsDisjunctions && isPureConjunctionDisjunction(expression)) {
        return;
      }
      registerError(expression, Integer.valueOf(numTerms));
    }

    private int countTerms(PsiExpression expression) {
      if (!isBoolean(expression)) {
        return 1;
      }
      if (expression instanceof PsiPolyadicExpression) {
        final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
        final PsiExpression[] operands = polyadicExpression.getOperands();
        return Arrays.stream(operands).mapToInt(this::countTerms).sum();
      }
      else if (expression instanceof PsiPrefixExpression) {
        final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)expression;
        return countTerms(prefixExpression.getOperand());
      }
      else if (expression instanceof PsiParenthesizedExpression) {
        final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression;
        return countTerms(parenthesizedExpression.getExpression());
      }
      return 1;
    }

    private boolean isBoolean(PsiExpression expression) {
      if (expression instanceof PsiPolyadicExpression) {
        final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
        return s_booleanOperators.contains(polyadicExpression.getOperationTokenType());
      }
      else if (expression instanceof PsiPrefixExpression) {
        final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)expression;
        return JavaTokenType.EXCL.equals(prefixExpression.getOperationTokenType());
      }
      else if (expression instanceof PsiParenthesizedExpression) {
        final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression;
        return isBoolean(parenthesizedExpression.getExpression());
      }
      return false;
    }

    private boolean isPureConjunctionDisjunction(PsiExpression expression) {
      if (!(expression instanceof PsiPolyadicExpression)) {
        return false;
      }
      final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
      final IElementType sign = polyadicExpression.getOperationTokenType();
      if (!s_booleanOperators.contains(sign)) {
        return false;
      }
      final PsiExpression[] operands = polyadicExpression.getOperands();
      for (PsiExpression operand : operands) {
        if (!(operand instanceof PsiReferenceExpression) &&
            !(operand instanceof PsiMethodCallExpression) &&
            !(operand instanceof PsiLiteralExpression)) {
          return false;
        }
      }
      return true;
    }
  }
}


text:
<resources>
    <string name="app_name">PlayChat</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="sign_out">Sign Out</string>

    <string name="channel_label">Select a channel from menu</string>
    <string name="message_hint">Enter a message</string>

    <string-array name="channels">
        <item>books</item>
        <item>game</item>
        <item>music</item>
        <item>sports</item>
        <item>travel</item>
    </string-array>

    <!-- nav_header_play -->
    <string name="nav_header_play_icon">Android icon with pattern background</string>
    <string name="channel_drawer_label">Channels</string>

    <!-- PlayActivity -->
    <string name="signed_in_label">Signed in as %s</string>
    <string name="authenticating_label">Authenticating with Firebase…</string>
    <string name="authentication_failed">Firebase authentication failed: %s</string>
    <string name="mic_button_content_descriptor">Microphone button</string>
</resources>


text:
// Copied from IPRange.cc for backwards compatibility.

#include <ts/IpMap.h>
#include <ts/IpMapConf.h>
#include <ts/ink_memory.h>

static size_t const ERR_STRING_LEN = 256;
static size_t const MAX_LINE_SIZE  = 2048;

// Returns 0 if successful, 1 if failed
// line  Input text (source line).
// n     Amount of data in @a line.
// i     [in,out] Offset in line.
// addr  [out] Destination for address.
// err   Buffer for error string (must be ERR_STRING_LEN big).
int
read_addr(char *line, int n, int *i, sockaddr *addr, char *err)
{
  int k;
  char dst[INET6_ADDRSTRLEN];
  char *src        = line + *i;
  bool bracketed_p = false;

  // Allow enclosing brackets to be more consistent but
  // don't bother passing it to @c ntop.
  if ((*i < n) && ('[' == *src)) {
    ++*i, ++src, bracketed_p = true;
  }

  for (k = 0; k < INET6_ADDRSTRLEN && *i < n && (isxdigit(*src) || '.' == *src || ':' == *src); ++k, ++*i, ++src) {
    dst[k] = *src;
  }

  if (bracketed_p && (!(*i < n) || (']' != *src))) {
    snprintf(err, ERR_STRING_LEN, "Unclosed brackets");
    return EINVAL;
  }

  if (k == sizeof(dst)) {
    snprintf(err, ERR_STRING_LEN, "IP address too long");
    return EINVAL;
  }

  dst[k] = '\0';
  if (0 != ats_ip_pton(dst, addr)) {
    snprintf(err, ERR_STRING_LEN, "IP address '%s' improperly formatted", dst);
    return EINVAL;
  }
  return 0;
}

char *
Load_IpMap_From_File(IpMap *map, int fd, const char *key_str)
{
  char *zret = nullptr;
  int fd2    = dup(fd); // dup to avoid closing the original file.
  FILE *f    = nullptr;

  if (fd2 >= 0) {
    f = fdopen(fd2, "r");
  }

  if (f != nullptr) {
    zret = Load_IpMap_From_File(map, f, key_str);
    fclose(f);
  } else {
    zret = (char *)ats_malloc(ERR_STRING_LEN);
    snprintf(zret, ERR_STRING_LEN, "Unable to reopen file descriptor as stream %d:%s", errno, strerror(errno));
  }
  return zret;
}

// Skip space in line, returning true if more data is available
// (not end of line).
//
// line    Source line.
// n       Line length.
// offset  Current offset
static inline bool
skip_space(char *line, int n, int &offset)
{
  while (offset < n && isspace(line[offset])) {
    ++offset;
  }
  return offset < n;
}

// Returns 0 if successful, error string otherwise
char *
Load_IpMap_From_File(IpMap *map, FILE *f, const char *key_str)
{
  int i, n, line_no;
  int key_len = strlen(key_str);
  IpEndpoint laddr, raddr;
  char line[MAX_LINE_SIZE];
  char err_buff[ERR_STRING_LEN];

  // First hardcode 127.0.0.1 into the table
  map->mark(INADDR_LOOPBACK);

  line_no = 0;
  while (fgets(line, MAX_LINE_SIZE, f)) {
    ++line_no;
    n = strlen(line);
    // Find first white space which terminates the line key.
    for (i = 0; i < n && !isspace(line[i]); ++i) {
      ;
    }
    if (i != key_len || 0 != strncmp(line, key_str, key_len)) {
      continue;
    }
    // Now look for IP address
    while (true) {
      if (!skip_space(line, n, i)) {
        break;
      }

      if (0 != read_addr(line, n, &i, &laddr.sa, err_buff)) {
        char *error_str = (char *)ats_malloc(ERR_STRING_LEN);
        snprintf(error_str, ERR_STRING_LEN, "Invalid input configuration (%s) at line %d offset %d - '%s'", err_buff, line_no, i,
                 line);
        return error_str;
      }

      if (!skip_space(line, n, i) || line[i] == ',') {
        // You have read an IP address. Enter it in the table
        map->mark(&laddr);
        if (i == n) {
          break;
        } else {
          ++i;
        }
      } else if (line[i] == '-') {
        // What you have just read is the start of the range,
        // Now, read the end of the IP range
        ++i;
        if (!skip_space(line, n, i)) {
          char *error_str = (char *)ats_malloc(ERR_STRING_LEN);
          snprintf(error_str, ERR_STRING_LEN, "Invalid input (unterminated range) at line %d offset %d - '%s'", line_no, i, line);
          return error_str;
        } else if (0 != read_addr(line, n, &i, &raddr.sa, err_buff)) {
          char *error_str = (char *)ats_malloc(ERR_STRING_LEN);
          snprintf(error_str, ERR_STRING_LEN, "Invalid input (%s) at line %d offset %d - '%s'", err_buff, line_no, i, line);
          return error_str;
        }
        map->mark(&laddr.sa, &raddr.sa);
        if (!skip_space(line, n, i)) {
          break;
        }
        if (line[i] != ',') {
          char *error_str = (char *)ats_malloc(ERR_STRING_LEN);
          snprintf(error_str, ERR_STRING_LEN, "Invalid input (expecting comma) at line %d offset %d - '%s'", line_no, i, line);
          return error_str;
        }
        ++i;
      } else {
        char *error_str = (char *)ats_malloc(ERR_STRING_LEN);
        snprintf(error_str, ERR_STRING_LEN, "Invalid input (expecting dash or comma) at line %d offset %d", line_no, i);
        return error_str;
      }
    }
  }
  return nullptr;
}


text:
/**
 * @file
 * @brief Emaclite driver.
 *
 * @date 18.12.2009
 * @author Anton Bondarev
 */

#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>

#include <util/log.h>
#include <net/util/show_packet.h>

#include <kernel/irq.h>
#include <net/skbuff.h>
#include <net/netdevice.h>
#include <net/inetdevice.h>
#include <net/l2/ethernet.h>
#include <net/l0/net_entry.h>

#include <embox/unit.h>
#include <module/embox/driver/net/xemaclite.h>

#define CONFIG_XILINX_EMACLITE_BASEADDR OPTION_GET(NUMBER,xemaclite_base)
#define CONFIG_XILINX_EMACLITE_IRQ_NUM  OPTION_GET(NUMBER,irq_num)

EMBOX_UNIT_INIT(emaclite_init);

#define PKTSIZE 0x800

/* Xmit complete */
#define XEL_TSR_XMIT_BUSY_MASK		0x00000001UL
/* Xmit interrupt enable bit */
#define XEL_TSR_XMIT_IE_MASK		0x00000008UL
/* Buffer is active, SW bit only */
#define XEL_TSR_XMIT_ACTIVE_MASK	0x80000000UL
/* Program the MAC address */
#define XEL_TSR_PROGRAM_MASK		0x00000002UL
/* define for programming the MAC address into the EMAC Lite */
#define XEL_TSR_PROG_MAC_ADDR	(XEL_TSR_XMIT_BUSY_MASK | XEL_TSR_PROGRAM_MASK)

/* Transmit packet length upper byte */
#define XEL_TPLR_LENGTH_MASK_HI		0x0000FF00UL
/* Transmit packet length lower byte */
#define XEL_TPLR_LENGTH_MASK_LO		0x000000FFUL

/* Recv complete */
#define XEL_RSR_RECV_DONE_MASK		0x00000001UL
/* Recv interrupt enable bit */
#define XEL_RSR_RECV_IE_MASK		0x00000008UL

/* Global Interrupt Enable Register (GIER) Bit Masks */
#define XEL_GIER_GIE_MASK	0x80000000 	/* Global Enable */

/* Transmit Packet Length Register (TPLR) */
#define XEL_TPLR_LENGTH_MASK	0x0000FFFF 	/* Tx packet length */

typedef struct mdio_regs {
	uint32_t regs;
} mdio_regs_t;

typedef struct pingpong_regs {
	uint8_t pack[0x07F0];
	mdio_regs_t mdio_regs;
	uint32_t len; /*0x07F4*/
	uint32_t gie;
	uint32_t ctrl;
} pingpong_regs_t;

typedef struct xilinx_emaclite_regs {
	pingpong_regs_t tx_ping;
	pingpong_regs_t tx_pong;
	pingpong_regs_t rx_ping;
	pingpong_regs_t rx_pong;
} xilinx_emaclite_regs_t;

static struct xilinx_emaclite_regs *emaclite =
		(struct xilinx_emaclite_regs *) CONFIG_XILINX_EMACLITE_BASEADDR;
static pingpong_regs_t *current_rx_regs = NULL;
static pingpong_regs_t *current_tx_regs = NULL;

#define GIE_REG      (&emaclite->tx_ping)->gie
#define RX_PACK      ((uint8_t *) current_rx_regs->pack)
#define TX_PACK      ((uint8_t *) current_tx_regs->pack)
#define TX_LEN_REG   current_tx_regs->len
#define TX_CTRL_REG  current_tx_regs->ctrl
#define RX_CTRL_REG  current_rx_regs->ctrl

#define PINPONG_BUFFER

static void switch_rx_buff(void) {
#ifdef PINPONG_BUFFER
	if (current_rx_regs == &emaclite->rx_ping) {
		current_rx_regs = &emaclite->rx_ping;
	} else {
		current_rx_regs = &emaclite->rx_pong;
	}
#else
	current_rx_regs = &emaclite->rx_ping;
#endif
}

static void switch_tx_buff(void) {
#ifdef PINPONG_BUFFER
	if (current_tx_regs == &emaclite->tx_ping) {
		current_tx_regs = &emaclite->tx_ping;
	} else {
		current_tx_regs = &emaclite->tx_pong;
	}
#else
	current_tx_regs = &emaclite->tx_ping;
#endif
}

static void restart_buff(void) {
	switch_tx_buff();
	TX_LEN_REG = 0;
	switch_tx_buff();
	TX_LEN_REG = 0;
}

static pingpong_regs_t *get_rx_buff(void) {
	if (current_rx_regs->ctrl & XEL_RSR_RECV_DONE_MASK) {
		return current_rx_regs;
	}
	switch_rx_buff();
	if (current_rx_regs->ctrl & XEL_RSR_RECV_DONE_MASK) {
		return current_rx_regs;
	}
	return NULL;
}

/*FIXME bad function (may be use if dest and src align 4)*/
static void memcpy32(volatile uint32_t *dest, void *src, size_t len) {
	size_t lenw = (size_t) ((len & (~3)) >> 2);
	volatile uint32_t *srcw = (uint32_t*) ((uint32_t) (src) & (~3));

	while (lenw--) {
		*dest++ = *srcw++;
	}
	if (len & (~3)) {
		*dest++ = *srcw++;
	}
}

static uint32_t *word_aligned_addr(void *addr) {
	return ((uint32_t *) ((int) addr & ~0x3)) + ((int) addr & 0x3 ? 1 : 0);
}

/**
 * Send a packet on this device.
 */
static int emaclite_xmit(struct net_device *dev, struct sk_buff *skb) {
	uint32_t *aligned_data;

	if ((NULL == skb) || (NULL == dev)) {
		return -EINVAL;
	}

	if (NULL == skb_declone(skb)) {
		return -ENOMEM;
	}

	if (0 != (TX_CTRL_REG & XEL_TSR_XMIT_BUSY_MASK)) {
		switch_tx_buff();
		if (0 != (TX_CTRL_REG & XEL_TSR_XMIT_BUSY_MASK)) {
			return -EBUSY; /*transmitter is busy*/
		}
	}

	aligned_data = word_aligned_addr(skb->mac.raw);

	if ((int) aligned_data != (int) skb->mac.raw) {
		memmove(aligned_data, skb->mac.raw, skb->len);
	}

	memcpy32((uint32_t*) TX_PACK, aligned_data, skb->len);
	TX_LEN_REG = skb->len & XEL_TPLR_LENGTH_MASK;
	TX_CTRL_REG |= XEL_TSR_XMIT_BUSY_MASK;
	show_packet(skb->mac.raw, skb->len, "TX");
	skb_free(skb);

	return 0;
}

/**
 *
 */
static void pack_receiving(void *dev_id) {
	uint16_t len, proto_type;
	uint32_t tmp;
	sk_buff_t *skb;
	struct net_device_stats *stats;
	int rx_rc;

	/* Get the protocol type of the ethernet frame that arrived */
	tmp = *(volatile uint32_t *) (RX_PACK + 0xC);
	proto_type = (tmp >> 0x10) & 0xFFFF;

	/* Check if received ethernet frame is a raw ethernet frame
	 * or an IP packet or an ARP packet */
	switch (proto_type) {
	case ETH_P_IP:
		len = (((*(volatile uint32_t *) (RX_PACK + 0x10))) >> 16) & 0xFFFF;
		len += ETH_HLEN + ETH_FCS_LEN;
		break;
	case ETH_P_ARP:
		len = 28 + ETH_HLEN + ETH_FCS_LEN;
		break;
	default:
		/* Field contains type other than IP or ARP, use max
		 * frame size and let user parse it */
		len = ETH_FRAME_LEN;
		break;
	}

	/* Read from the EmacLite device */

	skb = skb_alloc(len + 4);
	if (NULL == skb) {
		log_error("Can't allocate packet, pack_pool is full\n");
		current_rx_regs->ctrl &= ~XEL_RSR_RECV_DONE_MASK;
		switch_rx_buff();
		return;
	}

	memcpy32(word_aligned_addr(skb->mac.raw), RX_PACK, (size_t) len);
	if ((int) skb->mac.raw & 0x3) {
		memmove(skb->mac.raw, word_aligned_addr(skb->mac.raw), len);
	}

	skb->len -= 8;
	/* Acknowledge the frame */
	current_rx_regs->ctrl &= ~XEL_RSR_RECV_DONE_MASK;

	/* update device statistic */
	skb->dev = dev_id;
	stats = &skb->dev->stats;
	stats->rx_packets++;
	stats->rx_bytes += skb->len;

	show_packet(skb->mac.raw, skb->len, "RX");
	rx_rc = netif_rx(skb);
	if (NET_RX_DROP == rx_rc) {
		stats->rx_dropped++;
	}
}

/**
 * IRQ handler
 */
static irq_return_t emaclite_irq_handler(unsigned int irq_num, void *dev_id) {
	while (NULL != get_rx_buff()) {
		pack_receiving(dev_id);
	}
	return IRQ_HANDLED;
}
/*default 00-00-5E-00-FA-CE*/
static const unsigned char default_mac[ETH_ALEN] = { 0x00, 0x00, 0x5E, 0x00, 0xFA,
		0xCE };

static int emaclite_open(struct net_device *dev) {
	if (NULL == dev) {
		return -EINVAL;
	}

	current_rx_regs = &emaclite->rx_ping;
	current_tx_regs = &emaclite->tx_ping;
	/*
	 * TX - TX_PING & TX_PONG initialization
	 */
	/* Restart PING TX */

	restart_buff();
	/* Copy MAC address */
	memcpy(dev->dev_addr, default_mac, ETH_ALEN);
#if 0
	/*default 00-00-5E-00-FA-CE*/
	set_mac_address(dev, dev->hw_addr);
#endif

	/*
	 * RX - RX_PING & RX_PONG initialization
	 */
	RX_CTRL_REG = XEL_RSR_RECV_IE_MASK;
#ifdef PINPONG_BUFFER
	switch_rx_buff();
	RX_CTRL_REG = XEL_RSR_RECV_IE_MASK;
	switch_rx_buff();
#endif

	GIE_REG = XEL_GIER_GIE_MASK;
	return ENOERR;
}

static int emaclite_stop(struct net_device *dev) {
	if (NULL == dev) {
		return -EINVAL;
	}

	return ENOERR;
}

static int emaclite_set_mac_address(struct net_device *dev, const void *addr) {
	if (NULL == dev || NULL == addr) {
		return -EINVAL;
	}
#if 0
	out_be32 (emaclite.baseaddress + XEL_TSR_OFFSET, 0);
	/* Set the length */
	out_be32 (emaclite.baseaddress + XEL_TPLR_OFFSET, ENET_ADDR_LENGTH);
	/* Update the MAC address in the EMAC Lite */
	out_be32 (emaclite.baseaddress + XEL_TSR_OFFSET, XEL_TSR_PROG_MAC_ADDR);
	/* Wait for EMAC Lite to finish with the MAC address update */
	while ((in_be32 (emaclite.baseaddress + XEL_TSR_OFFSET) &
					XEL_TSR_PROG_MAC_ADDR) != 0);
#endif
	return ENOERR;
}

/*
 * Get RX/TX stats
 */
static const struct net_driver _drv_ops = {
	.xmit = emaclite_xmit,
	.start = emaclite_open,
	.stop = emaclite_stop,
	.set_macaddr = emaclite_set_mac_address
};

static int emaclite_init(void) {
	/*if some module lock irq number we break initializing*/
	int res;
	struct net_device *net_device;
	/*initialize net_device structures and save
	 * information about them to local massive */
	net_device = etherdev_alloc(0);
	if (net_device == NULL) {
		return -ENOMEM;
	}
	net_device->drv_ops = &_drv_ops;
	net_device->irq = CONFIG_XILINX_EMACLITE_IRQ_NUM;
	net_device->base_addr = CONFIG_XILINX_EMACLITE_BASEADDR;

	res = irq_attach(CONFIG_XILINX_EMACLITE_IRQ_NUM, emaclite_irq_handler, 0,
			net_device, "xilinx emaclite");
	if (res != 0) {
		return res;
	}

	return inetdev_register_dev(net_device);
}


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

import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;

import java.io.Serializable;

/**
 * @author Joram Barrez
 */
public class DeleteProcessInstanceCmd extends AbstractDeleteProcessInstanceCmd implements Command<Void>, Serializable {

  private static final long serialVersionUID = 1L;
  protected String processInstanceId;

  public DeleteProcessInstanceCmd(String processInstanceId, String deleteReason, boolean skipCustomListeners) {
    this(processInstanceId, deleteReason, skipCustomListeners, false);
  }

  public DeleteProcessInstanceCmd(String processInstanceId, String deleteReason, boolean skipCustomListeners, boolean externallyTerminated) {
    this.processInstanceId = processInstanceId;
    this.deleteReason = deleteReason;
    this.skipCustomListeners = skipCustomListeners;
    this.externallyTerminated = externallyTerminated;
  }

  public Void execute(CommandContext commandContext) {
    deleteProcessInstance(commandContext, processInstanceId, deleteReason, skipCustomListeners, externallyTerminated);

    return null;
  }

}


text:
module Kopipe
  module FieldCopiers
  end
end


text:
package fabhttp_test

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"syscall"

	"github.com/hyperledger/fabric/common/fabhttp"
	"github.com/hyperledger/fabric/core/operations/fakes"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	"github.com/tedsuo/ifrit"
)

var _ = Describe("Server", func() {
	const AdditionalTestApiPath = "/some-additional-test-api"

	var (
		fakeLogger *fakes.Logger
		tempDir    string

		client       *http.Client
		unauthClient *http.Client
		options      fabhttp.Options
		server       *fabhttp.Server
	)

	BeforeEach(func() {
		var err error
		tempDir, err = ioutil.TempDir("", "fabhttp-test")
		Expect(err).NotTo(HaveOccurred())

		generateCertificates(tempDir)
		client = newHTTPClient(tempDir, true)
		unauthClient = newHTTPClient(tempDir, false)

		fakeLogger = &fakes.Logger{}
		options = fabhttp.Options{
			Logger:        fakeLogger,
			ListenAddress: "127.0.0.1:0",
			TLS: fabhttp.TLS{
				Enabled:            true,
				CertFile:           filepath.Join(tempDir, "server-cert.pem"),
				KeyFile:            filepath.Join(tempDir, "server-key.pem"),
				ClientCertRequired: false,
				ClientCACertFiles:  []string{filepath.Join(tempDir, "client-ca.pem")},
			},
		}

		server = fabhttp.NewServer(options)
	})

	AfterEach(func() {
		os.RemoveAll(tempDir)
		if server != nil {
			server.Stop()
		}
	})

	When("trying to connect with an old TLS version", func() {
		BeforeEach(func() {
			tlsOpts := []func(config *tls.Config){func(config *tls.Config) {
				config.MaxVersion = tls.VersionTLS11
				config.ClientAuth = tls.RequireAndVerifyClientCert
			}}

			client = newHTTPClient(tempDir, true, tlsOpts...)
		})

		It("does not answer clients using an older TLS version than 1.2", func() {
			server.RegisterHandler(AdditionalTestApiPath, &fakes.Handler{Code: http.StatusOK, Text: "secure"}, options.TLS.Enabled)
			err := server.Start()
			Expect(err).NotTo(HaveOccurred())

			addApiURL := fmt.Sprintf("https://%s%s", server.Addr(), AdditionalTestApiPath)
			_, err = client.Get(addApiURL)
			Expect(err.Error()).To(ContainSubstring("tls: no supported versions satisfy MinVersion and MaxVersion"))
		})
	})

	It("does not host a secure endpoint for additional APIs by default", func() {
		err := server.Start()
		Expect(err).NotTo(HaveOccurred())

		addApiURL := fmt.Sprintf("https://%s%s", server.Addr(), AdditionalTestApiPath)
		resp, err := client.Get(addApiURL)
		Expect(err).NotTo(HaveOccurred())
		Expect(resp.StatusCode).To(Equal(http.StatusNotFound)) // service is not handled by default, i.e. in peer
		resp.Body.Close()

		resp, err = unauthClient.Get(addApiURL)
		Expect(err).NotTo(HaveOccurred())
		Expect(resp.StatusCode).To(Equal(http.StatusNotFound))
	})

	It("hosts a secure endpoint for additional APIs when added", func() {
		server.RegisterHandler(AdditionalTestApiPath, &fakes.Handler{Code: http.StatusOK, Text: "secure"}, options.TLS.Enabled)
		err := server.Start()
		Expect(err).NotTo(HaveOccurred())

		addApiURL := fmt.Sprintf("https://%s%s", server.Addr(), AdditionalTestApiPath)
		resp, err := client.Get(addApiURL)
		Expect(err).NotTo(HaveOccurred())
		Expect(resp.StatusCode).To(Equal(http.StatusOK))
		Expect(resp.Header.Get("Content-Type")).To(Equal("text/plain; charset=utf-8"))
		buff, err := ioutil.ReadAll(resp.Body)
		Expect(err).NotTo(HaveOccurred())
		Expect(string(buff)).To(Equal("secure"))
		resp.Body.Close()

		resp, err = unauthClient.Get(addApiURL)
		Expect(err).NotTo(HaveOccurred())
		Expect(resp.StatusCode).To(Equal(http.StatusUnauthorized))
	})

	Context("when TLS is disabled", func() {
		BeforeEach(func() {
			options.TLS.Enabled = false
			server = fabhttp.NewServer(options)
		})

		It("does not host an insecure endpoint for additional APIs by default", func() {
			err := server.Start()
			Expect(err).NotTo(HaveOccurred())

			addApiURL := fmt.Sprintf("http://%s%s", server.Addr(), AdditionalTestApiPath)
			resp, err := client.Get(addApiURL)
			Expect(err).NotTo(HaveOccurred())
			Expect(resp.StatusCode).To(Equal(http.StatusNotFound)) // service is not handled by default, i.e. in peer
			resp.Body.Close()
		})

		It("hosts an insecure endpoint for additional APIs when added", func() {
			server.RegisterHandler(AdditionalTestApiPath, &fakes.Handler{Code: http.StatusOK, Text: "insecure"}, options.TLS.Enabled)
			err := server.Start()
			Expect(err).NotTo(HaveOccurred())

			addApiURL := fmt.Sprintf("http://%s%s", server.Addr(), AdditionalTestApiPath)
			resp, err := client.Get(addApiURL)
			Expect(err).NotTo(HaveOccurred())
			Expect(resp.StatusCode).To(Equal(http.StatusOK))
			Expect(resp.Header.Get("Content-Type")).To(Equal("text/plain; charset=utf-8"))
			buff, err := ioutil.ReadAll(resp.Body)
			Expect(err).NotTo(HaveOccurred())
			Expect(string(buff)).To(Equal("insecure"))
			resp.Body.Close()
		})
	})

	Context("when ClientCertRequired is true", func() {
		BeforeEach(func() {
			options.TLS.ClientCertRequired = true
			server = fabhttp.NewServer(options)
		})

		It("requires a client cert to connect", func() {
			err := server.Start()
			Expect(err).NotTo(HaveOccurred())

			_, err = unauthClient.Get(fmt.Sprintf("https://%s/healthz", server.Addr()))
			Expect(err).To(MatchError(ContainSubstring("remote error: tls: bad certificate")))
		})
	})

	Context("when listen fails", func() {
		var listener net.Listener

		BeforeEach(func() {
			var err error
			listener, err = net.Listen("tcp", "127.0.0.1:0")
			Expect(err).NotTo(HaveOccurred())

			options.ListenAddress = listener.Addr().String()
			server = fabhttp.NewServer(options)
		})

		AfterEach(func() {
			listener.Close()
		})

		It("returns an error", func() {
			err := server.Start()
			Expect(err).To(MatchError(ContainSubstring("bind: address already in use")))
		})
	})

	Context("when a bad TLS configuration is provided", func() {
		BeforeEach(func() {
			options.TLS.CertFile = "cert-file-does-not-exist"
			server = fabhttp.NewServer(options)
		})

		It("returns an error", func() {
			err := server.Start()
			Expect(err).To(MatchError("open cert-file-does-not-exist: no such file or directory"))
		})
	})

	It("proxies Log to the provided logger", func() {
		err := server.Log("key", "value")
		Expect(err).NotTo(HaveOccurred())

		Expect(fakeLogger.WarnCallCount()).To(Equal(1))
		Expect(fakeLogger.WarnArgsForCall(0)).To(Equal([]interface{}{"key", "value"}))
	})

	Context("when a logger is not provided", func() {
		BeforeEach(func() {
			options.Logger = nil
			server = fabhttp.NewServer(options)
		})

		It("does not panic when logging", func() {
			Expect(func() { server.Log("key", "value") }).NotTo(Panic())
		})

		It("returns nil from Log", func() {
			err := server.Log("key", "value")
			Expect(err).NotTo(HaveOccurred())
		})
	})

	It("supports ifrit", func() {
		process := ifrit.Invoke(server)
		Eventually(process.Ready()).Should(BeClosed())

		process.Signal(syscall.SIGTERM)
		Eventually(process.Wait()).Should(Receive(BeNil()))
	})

	Context("when start fails and ifrit is used", func() {
		BeforeEach(func() {
			options.TLS.CertFile = "non-existent-file"
			server = fabhttp.NewServer(options)
		})

		It("does not close the ready chan", func() {
			process := ifrit.Invoke(server)
			Consistently(process.Ready()).ShouldNot(BeClosed())
			Eventually(process.Wait()).Should(Receive(MatchError("open non-existent-file: no such file or directory")))
		})
	})
})


text:
using System;
using Acquaintance.PubSub;
using Acquaintance.Utility;
using EasyNetQ;

namespace Acquaintance.RabbitMq
{
    public class RabbitSenderBuilder<TPayload> : IRabbitSenderBuilder<TPayload>
    {
        protected readonly IBus _bus;
        protected readonly RabbitModule _module;
        private string _queueName;
        private string _remoteTopic;
        private int _expirationMs;
        private byte _priority;
        private IRabbitSenderBuildStrategy _strategy;

        public RabbitSenderBuilder(IMessageBus messageBus, IBus bus, RabbitModule module)
        {
            Assert.ArgumentNotNull(messageBus, nameof(messageBus));
            Assert.ArgumentNotNull(bus, nameof(bus));

            _bus = bus;
            _module = module;
            _strategy = new DefaultSenderBuildStrategy(messageBus.Id);
        }

        public ISubscriberReference<TPayload> Build()
        {
            var options = BuildOptionsObject();

            return _strategy.Build(_bus, options);
        }

        protected RabbitSenderOptions BuildOptionsObject()
        {
            return new RabbitSenderOptions
            {
                MessagePriority = _priority,
                MessageExpirationMs = _expirationMs < 0 ? 0 : _expirationMs,
                QueueName = _queueName,
                RemoteTopic = _remoteTopic ?? ""
            };
        }

        public IRabbitSenderBuilder<TPayload> UseDefaultQueue()
        {
            _queueName = null;
            return this;
        }

        public IRabbitSenderBuilder<TPayload> UseSpecificQueue(string queueName)
        {
            _queueName = queueName;
            return this;
        }

        public IRabbitSenderBuilder<TPayload> WithRemoteTopic(string remoteTopic)
        {
            _remoteTopic = remoteTopic;
            return this;
        }

        public IRabbitSenderBuilder<TPayload> WithMessageExpiration(int expirationMs)
        {
            _expirationMs = expirationMs;
            return this;
        }

        public IRabbitSenderBuilder<TPayload> WithMessagePriority(byte priority)
        {
            _priority = priority;
            return this;
        }

        public IRabbitSenderBuilder<TPayload> TransformTo<TRemote>(Func<Envelope<TPayload>, string, TRemote> transform)
            where TRemote : class
        {
            _strategy = new TransformingSenderBuildStrategy<TRemote>(transform);
            return this;
        }

        private interface IRabbitSenderBuildStrategy
        {
            ISubscriberReference<TPayload> Build(IBus _bus, RabbitSenderOptions options);
        }

        private class DefaultSenderBuildStrategy : IRabbitSenderBuildStrategy
        {
            private readonly string _messageBusId;

            public DefaultSenderBuildStrategy(string messageBusId)
            {
                _messageBusId = messageBusId;
            }

            public ISubscriberReference<TPayload> Build(IBus _bus, RabbitSenderOptions options)
            {
                return new RabbitForwardingSubscriberReference<TPayload, RabbitEnvelope<TPayload>>(_bus, options, (e, t) => RabbitEnvelope<TPayload>.Wrap(_messageBusId, e, t));
            }
        }

        private class TransformingSenderBuildStrategy<TRemote> : IRabbitSenderBuildStrategy
            where TRemote : class
        {
            private readonly Func<Envelope<TPayload>, string, TRemote> _transform;

            public TransformingSenderBuildStrategy(Func<Envelope<TPayload>, string, TRemote> transform)
            {
                _transform = transform;
            }

            public ISubscriberReference<TPayload> Build(IBus _bus, RabbitSenderOptions options)
            {
                return new RabbitForwardingSubscriberReference<TPayload, TRemote>(_bus, options, _transform);
            }
        }
    }
}


text:
title: PingCAP Documentation
hide_sidebar: true
hide_commit: true
hide_leftNav: true
---

<DocHomeContainer title="PingCAP Documentation" subTitle="Explore the how-to guides and references you need to use TiDB Cloud and TiDB, migrate data, and build your applications on the database.">

<DocHomeSection label="TiDB Cloud" anchor="tidb-cloud" id="tidb-cloud">

TiDB Cloud is a fully-managed Database-as-a-Service (DBaaS) that brings everything great about TiDB to your cloud, and lets you focus on your applications, not the complexities of your database.

<DocHomeCardContainer>

<DocHomeCard href="https://docs.pingcap.com/tidbcloud" icon="doc2" label="TiDB Cloud Docs">

See the documentation of TiDB Cloud

</DocHomeCard>

<DocHomeCard href="https://docs.pingcap.com/tidbcloud/tidb-cloud-quickstart" icon="cloud5" label="Get Started with TiDB Cloud">

Guides you through an easy way to get started with TiDB Cloud

</DocHomeCard>

<DocHomeCard href="https://docs.pingcap.com/tidbcloud/tidb-cloud-poc" icon="cloud3" label="Perform a PoC with TiDB Cloud">

Helps you quickly complete a Proof of Concept (PoC) of TiDB Cloud

</DocHomeCard>

</DocHomeCardContainer>

Get the power of a cloud-native, distributed SQL database built for real-time analytics in a fully-managed service.

Try Free

</DocHomeSection>

<DocHomeSection label="TiDB" anchor="tidb" id="tidb">

TiDB is an open-source, distributed, NewSQL database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. It is MySQL compatible and features horizontal scalability, strong consistency, and high availability. You can deploy TiDB on premises or in the cloud.

<DocHomeCardContainer>

<DocHomeCard href="https://docs.pingcap.com/tidb/stable" icon="doc1" label="TiDB Docs">

See the documentation of TiDB

</DocHomeCard>

<DocHomeCard href="https://docs.pingcap.com/tidb/stable/quick-start-with-tidb" icon="doc5" label="Get Started with TiDB">

Walks you through the quickest way to get started with TiDB

</DocHomeCard>

<DocHomeCard href="https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup" icon="cloud7" label="Deploy a Local TiDB Cluster">

Learn how to deploy TiDB locally in production

</DocHomeCard>

</DocHomeCardContainer>

The open-source TiDB platform is released under the Apache 2.0 license, and supported by the community.

Download

</DocHomeSection>

<DocHomeSection label="Developers" anchor="developers" id="developers">

<DocHomeCardContainer>

<DocHomeCard href="https://docs.pingcap.com/tidb/stable/dev-guide-overview" icon="doc8" label="Developer Guide">

Documentation for TiDB application developers

</DocHomeCard>

<DocHomeCard href="https://docs.pingcap.com/tidbcloud/dev-guide-overview" icon="cloud-dev" label="Developer Guide">

Documentation for TiDB Cloud application developers

</DocHomeCard>

</DocHomeCardContainer>

</DocHomeSection>

<DocHomeSection label="More resources" anchor="resources" id="resources">

<DocHomeCardContainer>

<DocHomeCard href="https://en.pingcap.com/education/" icon="cloud1" label="PingCAP Education">

Learn TiDB and TiDB Cloud through well-designed online courses and instructor-led training

</DocHomeCard>

<DocHomeCard href="https://en.pingcap.com/community/" icon="doc9" label="Community">

Join us on Slack or become a contributor

</DocHomeCard>

<DocHomeCard href="https://en.pingcap.com/blog/" icon="doc10" label="Blog Posts">

Learn great articles about TiDB and TiDB Cloud

</DocHomeCard>

<DocHomeCard href="https://en.pingcap.com/videos/" icon="doc11" label="Videos">

See a compilation of short videos describing TiDB and a variety of use cases

</DocHomeCard>

<DocHomeCard href="https://en.pingcap.com/event/" icon="events" label="Events">

Learn events about PingCAP and the community

</DocHomeCard>

<DocHomeCard href="https://en.pingcap.com/ebook-whitepaper/" icon="papers" label="eBooks & Papers">

Download eBooks and papers

</DocHomeCard>

<DocHomeCard href="https://ossinsight.io/" icon="ossinsight" label="OSS Insight">

A powerful insight tool that analyzes in depth any GitHub repository, powered by TiDB Cloud

</DocHomeCard>

<DocHomeCard href="https://github.com/pingcap/docs/blob/master/CONTRIBUTING.md" icon="contributor" label="Contribute">

Let's work together to make the documentation better!

</DocHomeCard>

</DocHomeCardContainer>

</DocHomeSection>

</DocHomeContainer>


text:
import pyspatialite.dbapi2 as spatialite

def create(dbfile):
    print "Initializing", dbfile
    conn = spatialite.connect(dbfile)
    cur = conn.cursor()
    sql = 'SELECT InitSpatialMetadata()'
    cur.execute(sql)
    sql = 'CREATE TABLE gc ('
    sql += 'code TEXT NOT NULL PRIMARY KEY'
    sql += ', description TEXT NOT NULL'
    sql += ', type TEXT NOT NULL'
    sql += ', container TEXT NOT NULL'
    sql += ', diff FLOAT NOT NULL'
    sql += ', terr FLOAT NOT NULL'
    sql += ")"
    cur.execute(sql)
    sql = "SELECT AddGeometryColumn('gc', "
    sql += "'location', 4326, 'POINT', 'XY')"
    cur.execute(sql)
    cur.execute("select createspatialindex('gc', 'location')")
    conn.commit()
    cur.close()