text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Security;
using Orchard.ContentManagement;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Security;
using Orchard.Services;
using Orchard.Themes;
using Orchard.UI.Notify;
using Orchard.Users.Events;
using Orchard.Users.Models;
using Orchard.Users.Services;
using Orchard.Utility.Extensions;

namespace Orchard.Users.Controllers {
    [HandleError, Themed]
    public class AccountController : Controller {
        private readonly IAuthenticationService _authenticationService;
        private readonly IMembershipService _membershipService;
        private readonly IUserService _userService;
        private readonly IOrchardServices _orchardServices;
        private readonly IUserEventHandler _userEventHandler;
        private readonly IClock _clock;

        public AccountController(
            IAuthenticationService authenticationService,
            IMembershipService membershipService,
            IUserService userService,
            IOrchardServices orchardServices,
            IUserEventHandler userEventHandler,
            IClock clock) {

            _authenticationService = authenticationService;
            _membershipService = membershipService;
            _userService = userService;
            _orchardServices = orchardServices;
            _userEventHandler = userEventHandler;
            _clock = clock;

            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
        }

        public ILogger Logger { get; set; }
        public Localizer T { get; set; }

        [AlwaysAccessible]
        public ActionResult AccessDenied() {
            var returnUrl = Request.QueryString["ReturnUrl"];
            var currentUser = _authenticationService.GetAuthenticatedUser();

            if (currentUser == null) {
                Logger.Information("Access denied to anonymous request on {0}", returnUrl);
                var shape = _orchardServices.New.LogOn().Title(T("Access Denied").Text);
                return new ShapeResult(this, shape);
            }

            Logger.Information("Access denied to user #{0} '{1}' on {2}", currentUser.Id, currentUser.UserName, returnUrl);

            _userEventHandler.AccessDenied(currentUser);

            return View();
        }

        [AlwaysAccessible]
        public ActionResult LogOn(string returnUrl) {
            if (_authenticationService.GetAuthenticatedUser() != null)
                return this.RedirectLocal(returnUrl);

            var shape = _orchardServices.New.LogOn().Title(T("Log On").Text);
            return new ShapeResult(this, shape);
        }

        [HttpPost]
        [AlwaysAccessible]
        [ValidateInput(false)]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(string userNameOrEmail, string password, string returnUrl, bool rememberMe = false) {
            _userEventHandler.LoggingIn(userNameOrEmail, password);

            var user = ValidateLogOn(userNameOrEmail, password);
            if (!ModelState.IsValid) {
                var shape = _orchardServices.New.LogOn().Title(T("Log On").Text);

                return new ShapeResult(this, shape);
            }

            var membershipSettings = _membershipService.GetSettings();
            if (user != null &&
                membershipSettings.EnableCustomPasswordPolicy &&
                membershipSettings.EnablePasswordExpiration &&
                _membershipService.PasswordIsExpired(user, membershipSettings.PasswordExpirationTimeInDays)) {
                return RedirectToAction("ChangeExpiredPassword", new { username = user.UserName });
            }

            _authenticationService.SignIn(user, rememberMe);
            _userEventHandler.LoggedIn(user);

            return this.RedirectLocal(returnUrl);
        }

        public ActionResult LogOff(string returnUrl) {
            _authenticationService.SignOut();

            var loggedUser = _authenticationService.GetAuthenticatedUser();
            if (loggedUser != null) {
                _userEventHandler.LoggedOut(loggedUser);
            }

            return this.RedirectLocal(returnUrl);
        }

        [AlwaysAccessible]
        public ActionResult Register() {
            // ensure users can register
            var membershipSettings = _membershipService.GetSettings();
            if (!membershipSettings.UsersCanRegister) {
                return HttpNotFound();
            }

            ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength();
            ViewData["LowercaseRequirement"] = membershipSettings.GetPasswordLowercaseRequirement();
            ViewData["UppercaseRequirement"] = membershipSettings.GetPasswordUppercaseRequirement();
            ViewData["SpecialCharacterRequirement"] = membershipSettings.GetPasswordSpecialRequirement();
            ViewData["NumberRequirement"] = membershipSettings.GetPasswordNumberRequirement();

            var shape = _orchardServices.New.Register();

            return new ShapeResult(this, shape);
        }

        [HttpPost]
        [AlwaysAccessible]
        [ValidateInput(false)]
        public ActionResult Register(string userName, string email, string password, string confirmPassword, string returnUrl = null) {
            // ensure users can register
            var membershipSettings = _membershipService.GetSettings();
            if (!membershipSettings.UsersCanRegister) {
                return HttpNotFound();
            }

            ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength();
            ViewData["LowercaseRequirement"] = membershipSettings.GetPasswordLowercaseRequirement();
            ViewData["UppercaseRequirement"] = membershipSettings.GetPasswordUppercaseRequirement();
            ViewData["SpecialCharacterRequirement"] = membershipSettings.GetPasswordSpecialRequirement();
            ViewData["NumberRequirement"] = membershipSettings.GetPasswordNumberRequirement();

            if (ValidateRegistration(userName, email, password, confirmPassword)) {
                // Attempt to register the user
                // No need to report this to IUserEventHandler because _membershipService does that for us
                var user = _membershipService.CreateUser(new CreateUserParams(userName, password, email, null, null, false));

                if (user != null) {
                    if (user.As<UserPart>().EmailStatus == UserStatus.Pending) {
                        var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl;
                        if (String.IsNullOrWhiteSpace(siteUrl)) {
                            siteUrl = HttpContext.Request.ToRootUrlString();
                        }

                        _userService.SendChallengeEmail(user.As<UserPart>(), nonce => Url.MakeAbsolute(Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));

                        _userEventHandler.SentChallengeEmail(user);
                        return RedirectToAction("ChallengeEmailSent", new { ReturnUrl = returnUrl });
                    }

                    if (user.As<UserPart>().RegistrationStatus == UserStatus.Pending) {
                        return RedirectToAction("RegistrationPending", new { ReturnUrl = returnUrl });
                    }

                    _userEventHandler.LoggingIn(userName, password);
                    _authenticationService.SignIn(user, false /* createPersistentCookie */);
                    _userEventHandler.LoggedIn(user);

                    return this.RedirectLocal(returnUrl);
                }

                ModelState.AddModelError("_FORM", T(ErrorCodeToString(/*createStatus*/MembershipCreateStatus.ProviderError)));
            }

            // If we got this far, something failed, redisplay form
            var shape = _orchardServices.New.Register();
            return new ShapeResult(this, shape);
        }

        [AlwaysAccessible]
        public ActionResult RequestLostPassword() {
            // ensure users can request lost password
            var membershipSettings = _membershipService.GetSettings();
            if (!membershipSettings.EnableLostPassword) {
                return HttpNotFound();
            }

            return View();
        }

        [HttpPost]
        [AlwaysAccessible]
        public ActionResult RequestLostPassword(string username) {
            // ensure users can request lost password
            var membershipSettings = _membershipService.GetSettings();
            if (!membershipSettings.EnableLostPassword) {
                return HttpNotFound();
            }

            if (string.IsNullOrWhiteSpace(username)) {
                ModelState.AddModelError("username", T("You must specify a username or e-mail."));
                return View();
            }

            var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl;
            if (string.IsNullOrWhiteSpace(siteUrl)) {
                siteUrl = HttpContext.Request.ToRootUrlString();
            }

            _userService.SendLostPasswordEmail(username, nonce =>
                Url.MakeAbsolute(Url.Action("LostPassword", "Account", new { Area = "Orchard.Users", nonce }), siteUrl));

            _orchardServices.Notifier.Information(T("If your username or email is correct, we will send you an email with a link to reset your password."));

            return RedirectToAction("LogOn");
        }

        [Authorize]
        [AlwaysAccessible]
        public ActionResult ChangePassword() {
            var membershipSettings = _membershipService.GetSettings();
            ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength();
            ViewData["LowercaseRequirement"] = membershipSettings.GetPasswordLowercaseRequirement();
            ViewData["UppercaseRequirement"] = membershipSettings.GetPasswordUppercaseRequirement();
            ViewData["SpecialCharacterRequirement"] = membershipSettings.GetPasswordSpecialRequirement();
            ViewData["NumberRequirement"] = membershipSettings.GetPasswordNumberRequirement();

            ViewData["InvalidateOnPasswordChange"] = _orchardServices.WorkContext
                .CurrentSite.As<SecuritySettingsPart>()
                .ShouldInvalidateAuthOnPasswordChanged;

            return View();
        }

        [Authorize]
        [HttpPost]
        [AlwaysAccessible]
        [ValidateInput(false)]
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "Exceptions result in password not being changed.")]
        public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword) {
            var membershipSettings = _membershipService.GetSettings();
            ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength();
            ViewData["LowercaseRequirement"] = membershipSettings.GetPasswordLowercaseRequirement();
            ViewData["UppercaseRequirement"] = membershipSettings.GetPasswordUppercaseRequirement();
            ViewData["SpecialCharacterRequirement"] = membershipSettings.GetPasswordSpecialRequirement();
            ViewData["NumberRequirement"] = membershipSettings.GetPasswordNumberRequirement();
            var shouldSignout = _orchardServices.WorkContext
                .CurrentSite.As<SecuritySettingsPart>()
                .ShouldInvalidateAuthOnPasswordChanged;
            ViewData["InvalidateOnPasswordChange"] = shouldSignout;

            if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword)) {
                return View();
            }

            if (PasswordChangeIsSuccess(currentPassword, newPassword, _orchardServices.WorkContext.CurrentUser.UserName)) {
                if (shouldSignout) {
                    _authenticationService.SignOut();

                    var loggedUser = _authenticationService.GetAuthenticatedUser();
                    if (loggedUser != null) {
                        _userEventHandler.LoggedOut(loggedUser);
                    }

                }
                return RedirectToAction("ChangePasswordSuccess");
            }
            else {
                return ChangePassword();
            }
        }

        [AlwaysAccessible]
        public ActionResult ChangeExpiredPassword(string username) {
            var membershipSettings = _membershipService.GetSettings();
            var lastPasswordChangeUtc = _membershipService.GetUser(username).As<UserPart>().LastPasswordChangeUtc;

            if (lastPasswordChangeUtc.Value.AddDays(membershipSettings.PasswordExpirationTimeInDays) > _clock.UtcNow) {
                return RedirectToAction("LogOn");
            }

            var viewModel = _orchardServices.New.ViewModel(
                Username: username,
                PasswordLength: membershipSettings.GetMinimumPasswordLength(),
                LowercaseRequirement: membershipSettings.GetPasswordLowercaseRequirement(),
                UppercaseRequirement: membershipSettings.GetPasswordUppercaseRequirement(),
                SpecialCharacterRequirement: membershipSettings.GetPasswordSpecialRequirement(),
                NumberRequirement: membershipSettings.GetPasswordNumberRequirement());

            return View(viewModel);
        }

        [HttpPost, AlwaysAccessible, ValidateInput(false)]
        public ActionResult ChangeExpiredPassword(string currentPassword, string newPassword, string confirmPassword, string username) {
            var membershipSettings = _membershipService.GetSettings();
            var viewModel = _orchardServices.New.ViewModel(
                Username: username,
                PasswordLength: membershipSettings.GetMinimumPasswordLength(),
                LowercaseRequirement: membershipSettings.GetPasswordLowercaseRequirement(),
                UppercaseRequirement: membershipSettings.GetPasswordUppercaseRequirement(),
                SpecialCharacterRequirement: membershipSettings.GetPasswordSpecialRequirement(),
                NumberRequirement: membershipSettings.GetPasswordNumberRequirement());

            if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword)) {
                return View(viewModel);
            }

            if (PasswordChangeIsSuccess(currentPassword, newPassword, username)) {
                return RedirectToAction("ChangePasswordSuccess");
            }
            else {
                return View(viewModel);
            }
        }

        private bool PasswordChangeIsSuccess(string currentPassword, string newPassword, string username) {
            try {
                var validated = _membershipService.ValidateUser(username, currentPassword, out List<LocalizedString> validationErrors);

                if (validated != null) {
                    _membershipService.SetPassword(validated, newPassword);
                    _userEventHandler.ChangedPassword(validated, newPassword);

                    // if security settings tell to invalidate on password change fire the LoggedOut event
                    if (_orchardServices.WorkContext.CurrentSite.As<SecuritySettingsPart>().ShouldInvalidateAuthOnPasswordChanged) {
                        _userEventHandler.LoggedOut(validated);
                    }

                    return true;
                }

            }
            catch {
                ModelState.AddModelError("_FORM", T("The current password is incorrect or the new password is invalid."));

                return false;
            }

            return false;
        }

        [AlwaysAccessible]
        public ActionResult LostPassword(string nonce) {
            if (_userService.ValidateLostPassword(nonce) == null) {
                return RedirectToAction("LogOn");
            }

            var membershipSettings = _membershipService.GetSettings();
            ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength();
            ViewData["LowercaseRequirement"] = membershipSettings.GetPasswordLowercaseRequirement();
            ViewData["UppercaseRequirement"] = membershipSettings.GetPasswordUppercaseRequirement();
            ViewData["SpecialCharacterRequirement"] = membershipSettings.GetPasswordSpecialRequirement();
            ViewData["NumberRequirement"] = membershipSettings.GetPasswordNumberRequirement();
            return View();
        }

        [HttpPost]
        [AlwaysAccessible]
        [ValidateInput(false)]
        public ActionResult LostPassword(string nonce, string newPassword, string confirmPassword) {
            IUser user;
            if ((user = _userService.ValidateLostPassword(nonce)) == null) {
                return Redirect("~/");
            }

            var membershipSettings = _membershipService.GetSettings();
            ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength();
            ViewData["LowercaseRequirement"] = membershipSettings.GetPasswordLowercaseRequirement();
            ViewData["UppercaseRequirement"] = membershipSettings.GetPasswordUppercaseRequirement();
            ViewData["SpecialCharacterRequirement"] = membershipSettings.GetPasswordSpecialRequirement();
            ViewData["NumberRequirement"] = membershipSettings.GetPasswordNumberRequirement();

            ValidatePassword(newPassword);

            if (!string.Equals(newPassword, confirmPassword, StringComparison.Ordinal)) {
                ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match."));
            }

            if (!ModelState.IsValid) {
                return View();
            }

            _membershipService.SetPassword(user, newPassword);

            _userEventHandler.ChangedPassword(user, newPassword);

            return RedirectToAction("ChangePasswordSuccess");
        }

        [AlwaysAccessible]
        public ActionResult ChangePasswordSuccess() {
            ViewData["InvalidateOnPasswordChange"] = _orchardServices.WorkContext
                .CurrentSite.As<SecuritySettingsPart>()
                .ShouldInvalidateAuthOnPasswordChanged;

            return View();
        }

        [AlwaysAccessible]
        public ActionResult RegistrationPending() {
            return View();
        }

        [AlwaysAccessible]
        public ActionResult ChallengeEmailSent() {
            return View();
        }

        [AlwaysAccessible]
        public ActionResult ChallengeEmailSuccess() {
            return View();
        }

        [AlwaysAccessible]
        public ActionResult ChallengeEmailFail() {
            return View();
        }

        [AlwaysAccessible]
        public ActionResult ChallengeEmail(string nonce) {
            var user = _userService.ValidateChallenge(nonce);

            if (user != null) {
                _userEventHandler.ConfirmedEmail(user);

                return RedirectToAction("ChallengeEmailSuccess");
            }

            return RedirectToAction("ChallengeEmailFail");
        }

        #region Validation Methods
        private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword) {
            if (string.IsNullOrEmpty(currentPassword)) {
                ModelState.AddModelError("currentPassword", T("You must specify a current password."));
            }

            if (string.Equals(currentPassword, newPassword, StringComparison.Ordinal)) {
                ModelState.AddModelError("newPassword", T("The new password must be different from the current password."));
            }

            ValidatePassword(newPassword);

            if (!string.Equals(newPassword, confirmPassword, StringComparison.Ordinal)) {
                ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match."));
            }

            return ModelState.IsValid;
        }

        private IUser ValidateLogOn(string userNameOrEmail, string password) {
            bool validate = true;

            if (string.IsNullOrEmpty(userNameOrEmail)) {
                ModelState.AddModelError("userNameOrEmail", T("You must specify a username or e-mail."));
                validate = false;
            }
            if (string.IsNullOrEmpty(password)) {
                ModelState.AddModelError("password", T("You must specify a password."));
                validate = false;
            }

            if (!validate)
                return null;

            var validationResult = _membershipService.ValidateUser(userNameOrEmail, password, out List<LocalizedString> validationErrors);
            if (validationResult == null) {
                _userEventHandler.LogInFailed(userNameOrEmail, password);
            }

            foreach (var error in validationErrors) {
                ModelState.AddModelError("_FORM", error);
            }

            return validationResult;
        }

        private bool ValidateRegistration(string userName, string email, string password, string confirmPassword) {
            bool validate = true;

            if (string.IsNullOrEmpty(userName)) {
                ModelState.AddModelError("username", T("You must specify a username."));
                validate = false;
            }
            else {
                if (userName.Length >= UserPart.MaxUserNameLength) {
                    ModelState.AddModelError("username", T("The username you provided is too long."));
                    validate = false;
                }
            }

            if (string.IsNullOrEmpty(email)) {
                ModelState.AddModelError("email", T("You must specify an email address."));
                validate = false;
            }
            else if (email.Length >= UserPart.MaxEmailLength) {
                ModelState.AddModelError("email", T("The email address you provided is too long."));
                validate = false;
            }
            else if (!Regex.IsMatch(email, UserPart.EmailPattern, RegexOptions.IgnoreCase)) {
                // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
                ModelState.AddModelError("email", T("You must specify a valid email address."));
                validate = false;
            }

            if (!validate)
                return false;

            if (!_userService.VerifyUserUnicity(userName, email)) {
                ModelState.AddModelError("userExists", T("User with that username and/or email already exists."));
            }

            ValidatePassword(password);

            if (!string.Equals(password, confirmPassword, StringComparison.Ordinal)) {
                ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match."));
            }
            return ModelState.IsValid;
        }

        private void ValidatePassword(string password) {
            if (!_userService.PasswordMeetsPolicies(password, out IDictionary<string, LocalizedString> validationErrors)) {
                foreach (var error in validationErrors) {
                    ModelState.AddModelError(error.Key, error.Value);
                }
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus) {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus) {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return
                        "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return
                        "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return
                        "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        #endregion
    }
}


text:
/*
	File:		FSCopyObject.h

	Contains:	A Copy/Delete Files/Folders engine which uses the HFS+ API's

*/

/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code, released
 * March 31, 1998.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2000
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

// Modified 2006-01-23 - added this comment.

#ifndef __FSCOPYOBJECT_H__
#define __FSCOPYOBJECT_H__

#include <Files.h>

#ifdef __cplusplus
extern "C" {
#endif

#define DEBUG_COPY_OBJECT  0	// set to zero if you don't want debug spew

#define QuoteExceptionString(x) #x

#if DEBUG_COPY_OBJECT
	#include <stdio.h>

	#define mycheck_noerr(error)                                                \
	    do {                                                                    \
	        OSStatus localError = error;                                        \
	        if (localError == noErr) ;                                          \
	        else {                                                              \
	           printf(QuoteExceptionString(error) " != noErr in File: %s, Function: %s, Line: %d, Error: %d\n",	\
	           							  __FILE__, __FUNCTION__, __LINE__, localError);		\
	        }                                                                   \
	    } while (false)

	#define mycheck(assertion)                                                	\
	    do {                                                                	\
	        if (assertion) ;                                                	\
	        else {                                                          	\
	           printf(QuoteExceptionString(assertion) " failed in File: %s, Function: %s, Line: %d\n",	\
	           							  __FILE__, __FUNCTION__, __LINE__);	\
	        }                                                               	\
	    } while (false)
    #define myverify(assertion)       mycheck(assertion)
    #define myverify_noerr(assertion) mycheck_noerr( (assertion) )
#else
	#define mycheck(assertion)
	#define mycheck_noerr(err)
    #define myverify(assertion)       do { (void) (assertion); } while (0)
    #define myverify_noerr(assertion) myverify(assertion)
#endif

/*
	This code is a combination of MoreFilesX (by Jim Luther) and MPFileCopy (by Quinn)
	with some added features and bug fixes.  This code will run in OS 9.1 and up
	and 10.1.x (Classic and Carbon)
*/

/*****************************************************************************/

#pragma mark CopyObjectFilterProcPtr

/*
	This is the prototype for the CallCopyObjectFilterProc function which
	is called once for each file and directory found by FSCopyObject.
	The CallCopyObjectFilterProc can use the read-only data it receives for
	whatever it wants.

	The result of the CallCopyObjectFilterProc function indicates if
	iteration should be stopped. To stop iteration, return true; to continue
	iteration, return false.

	The yourDataPtr parameter can point to whatever data structure you might
	want to access from within the CallCopyObjectFilterProc.

	containerChanged	--> Set to true if the container's contents changed
							during iteration.
	currentLevel		--> The current recursion level into the container.
							1 = the container, 2 = the container's immediate
							subdirectories, etc.
	currentOSErr		--> The current error code, shows the results of the
							copy of the current object (ref)
	catalogInfo			--> The catalog information for the current object.
							Only the fields requested by the whichInfo
							parameter passed to FSIterateContainer are valid.
	ref					--> The FSRef to the current object.
	spec				--> The FSSpec to the current object if the wantFSSpec
							parameter passed to FSCopyObject is true.
	name				--> The name of the current object if the wantName
							parameter passed to FSCopyObject is true.
	yourDataPtr			--> An optional pointer to whatever data structure you
							might want to access from within the
							CallCopyObjectFilterProc.
	result				<-- To stop iteration, return true; to continue
							iteration, return false.

	__________

	Also see:	FSCopyObject
*/

typedef CALLBACK_API( Boolean , CopyObjectFilterProcPtr ) (
	Boolean containerChanged,
	ItemCount currentLevel,
	OSErr currentOSErr,
	const FSCatalogInfo *catalogInfo,
	const FSRef *ref,
	const FSSpec *spec,
	const HFSUniStr255 *name,
	void *yourDataPtr);

/*****************************************************************************/

#pragma mark CallCopyObjectFilterProc

#define CallCopyObjectFilterProc(userRoutine, containerChanged, currentLevel, currentOSErr, catalogInfo, ref, spec, name, yourDataPtr) \
	(*(userRoutine))((containerChanged), (currentLevel), (currentOSErr), (catalogInfo), (ref), (spec), (name), (yourDataPtr))

/*****************************************************************************/

#pragma mark FSCopyObject

/*
	The FSCopyObject function takes a source object (can be a file or directory)
	and copies it (and its contents if it's a directory) to the new destination
	directory.

	It will call your CopyObjectFilterProcPtr once for each file/directory
	copied

	The maxLevels parameter is only used when the object is a directory,
	ignored otherwise.
	It lets you control how deep the recursion goes.
	If maxLevels is 1, FSCopyObject only scans the specified directory;
	if maxLevels is 2, FSCopyObject scans the specified directory and
	one subdirectory below the specified directory; etc. Set maxLevels to
	zero to scan all levels.

	The yourDataPtr parameter can point to whatever data structure you might
	want to access from within your CopyObjectFilterProcPtr.

	source				--> The FSRef to the object you want to copy
	destDir				--> The FSRef to the directory you wish to copy source to
	maxLevels			--> Maximum number of directory levels to scan or
							zero to scan all directory levels, ignored if the
							object is a file
	whichInfo			--> The fields of the FSCatalogInfo you wish passed
							to you in your CopyObjectFilterProc
	wantFSSpec			--> Set to true if you want the FSSpec to each
							object passed to your CopyObjectFilterProc.
	wantName			--> Set to true if you want the name of each
							object passed to your CopyObjectFilterProc.
	iterateFilter		--> A pointer to the CopyObjectFilterProc you
							want called once for each object found
							by FSCopyObject.
	yourDataPtr			--> An optional pointer to whatever data structure you
							might want to access from within the
							CopyObjectFilterProc.
*/

OSErr FSCopyObject(	const FSRef *source,
					const FSRef *destDir,
				 	UniCharCount nameLength,
				 	const UniChar *copyName,			// can be NULL (no rename during copy)
				 	ItemCount maxLevels,
				 	FSCatalogInfoBitmap whichInfo,
					Boolean wantFSSpec,
					Boolean wantName,
					CopyObjectFilterProcPtr filterProcPtr,	// can be NULL
					void *yourDataPtr,						// can be NULL
					FSRef *newObject);						// can be NULL

/*****************************************************************************/

#pragma mark FSDeleteObjects

/*
	The FSDeleteObjects function takes an FSRef to a file or directory
	and attempts to delete it.  If the object is a directory, all files
	and subdirectories in the specified directory are deleted. If a
	locked file or directory is encountered, it is unlocked and then
	deleted.  After deleting the directory's contents, the directory
	is deleted. If any unexpected errors are encountered,
	FSDeleteContainer quits and returns to the caller.

	source				--> FSRef to an object (can be file or directory).

	__________
*/

OSErr FSDeleteObjects(	const FSRef *source );

#ifdef __cplusplus
}
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Intl\Data\Util;

/**
 * Scans a directory with data files for locales.
 *
 * The name of each file with the extension ".txt" is considered, if it "looks"
 * like a locale:
 *
 *  - the name must start with two letters;
 *  - the two letters may optionally be followed by an underscore and any
 *    sequence of other symbols.
 *
 * For example, "de" and "de_DE" are considered to be locales. "root" and "meta"
 * are not.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @internal
 */
class LocaleScanner
{
    /**
     * Returns all locales found in the given directory.
     *
     * @param string $sourceDir The directory with ICU files
     *
     * @return array An array of locales. The result also contains locales that
     *               are in fact just aliases for other locales. Use
     *               {@link scanAliases()} to determine which of the locales
     *               are aliases
     */
    public function scanLocales($sourceDir)
    {
        $locales = glob($sourceDir.'/*.txt');

        // Remove file extension and sort
        array_walk($locales, function (&$locale) { $locale = basename($locale, '.txt'); });

        // Remove non-locales
        $locales = array_filter($locales, function ($locale) {
            return preg_match('/^[a-z]{2}(_.+)?$/', $locale);
        });

        sort($locales);

        return $locales;
    }

    /**
     * Returns all locale aliases found in the given directory.
     *
     * @param string $sourceDir The directory with ICU files
     *
     * @return array An array with the locale aliases as keys and the aliased
     *               locales as values
     */
    public function scanAliases($sourceDir)
    {
        $locales = $this->scanLocales($sourceDir);
        $aliases = array();

        // Delete locales that are no aliases
        foreach ($locales as $locale) {
            $content = file_get_contents($sourceDir.'/'.$locale.'.txt');

            // Aliases contain the text "%%ALIAS" followed by the aliased locale
            if (preg_match('/"%%ALIAS"\{"([^"]+)"\}/', $content, $matches)) {
                $aliases[$locale] = $matches[1];
            }
        }

        return $aliases;
    }
}


text:
require 'singleton'

module SkipEmbedded
  class InitialSettings
    include Singleton
    def self.config=(abs_path)
      @config_path = abs_path
    end

    def self.config
      @config_path ||= File.expand_path("config/initial_settings.yml", Rails.root)
    end

    def self.[](key)
      instance[key]
    end

    def initialize
      env = defined?(RAILS_ENV) ? RAILS_ENV : "development"
      @config = YAML.load_file(self.class.config)[env].freeze
    end

    def [](key)
      @config[key.to_s]
    end
  end
end


text:
package org.springframework.boot.cli.command.init;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link InitializrService}
 *
 * @author Stephane Nicoll
 */
public class InitializrServiceTests extends AbstractHttpClientMockTests {

	@Rule
	public final ExpectedException thrown = ExpectedException.none();

	private final InitializrService invoker = new InitializrService(this.http);

	@Test
	public void loadMetadata() throws IOException {
		mockSuccessfulMetadataGet(false);
		InitializrServiceMetadata metadata = this.invoker.loadMetadata("http://foo/bar");
		assertThat(metadata).isNotNull();
	}

	@Test
	public void generateSimpleProject() throws IOException {
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
				"application/xml", "foo.zip");
		ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
		assertProjectEntity(entity, mockHttpRequest.contentType,
				mockHttpRequest.fileName);
	}

	@Test
	public void generateProjectCustomTargetFilename() throws IOException {
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		request.setOutput("bar.zip");
		MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
				"application/xml", null);
		ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
		assertProjectEntity(entity, mockHttpRequest.contentType, null);
	}

	@Test
	public void generateProjectNoDefaultFileName() throws IOException {
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
				"application/xml", null);
		ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
		assertProjectEntity(entity, mockHttpRequest.contentType, null);
	}

	@Test
	public void generateProjectBadRequest() throws IOException {
		String jsonMessage = "Unknown dependency foo:bar";
		mockProjectGenerationError(400, jsonMessage);
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		request.getDependencies().add("foo:bar");
		this.thrown.expect(ReportableException.class);
		this.thrown.expectMessage(jsonMessage);
		this.invoker.generate(request);
	}

	@Test
	public void generateProjectBadRequestNoExtraMessage() throws IOException {
		mockProjectGenerationError(400, null);
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		this.thrown.expect(ReportableException.class);
		this.thrown.expectMessage("unexpected 400 error");
		this.invoker.generate(request);
	}

	@Test
	public void generateProjectNoContent() throws IOException {
		mockSuccessfulMetadataGet(false);
		CloseableHttpResponse response = mock(CloseableHttpResponse.class);
		mockStatus(response, 500);
		given(this.http.execute(isA(HttpGet.class))).willReturn(response);
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		this.thrown.expect(ReportableException.class);
		this.thrown.expectMessage("No content received from server");
		this.invoker.generate(request);
	}

	@Test
	public void loadMetadataBadRequest() throws IOException {
		String jsonMessage = "whatever error on the server";
		mockMetadataGetError(500, jsonMessage);
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		this.thrown.expect(ReportableException.class);
		this.thrown.expectMessage(jsonMessage);
		this.invoker.generate(request);
	}

	@Test
	public void loadMetadataInvalidJson() throws IOException {
		CloseableHttpResponse response = mock(CloseableHttpResponse.class);
		mockHttpEntity(response, "Foo-Bar-Not-JSON".getBytes(), "application/json");
		mockStatus(response, 200);
		given(this.http.execute(isA(HttpGet.class))).willReturn(response);
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		this.thrown.expect(ReportableException.class);
		this.thrown.expectMessage("Invalid content received from server");
		this.invoker.generate(request);
	}

	@Test
	public void loadMetadataNoContent() throws IOException {
		CloseableHttpResponse response = mock(CloseableHttpResponse.class);
		mockStatus(response, 500);
		given(this.http.execute(isA(HttpGet.class))).willReturn(response);
		ProjectGenerationRequest request = new ProjectGenerationRequest();
		this.thrown.expect(ReportableException.class);
		this.thrown.expectMessage("No content received from server");
		this.invoker.generate(request);
	}

	private ProjectGenerationResponse generateProject(ProjectGenerationRequest request,
			MockHttpProjectGenerationRequest mockRequest) throws IOException {
		mockSuccessfulProjectGeneration(mockRequest);
		ProjectGenerationResponse entity = this.invoker.generate(request);
		assertThat(entity.getContent()).as("wrong body content")
				.isEqualTo(mockRequest.content);
		return entity;
	}

	private static void assertProjectEntity(ProjectGenerationResponse entity,
			String mimeType, String fileName) {
		if (mimeType == null) {
			assertThat(entity.getContentType()).isNull();
		}
		else {
			assertThat(entity.getContentType().getMimeType()).isEqualTo(mimeType);
		}
		assertThat(entity.getFileName()).isEqualTo(fileName);
	}

}


text:
<?php require_once('header.php');?>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URI;?>/public/lib/css/nav_and_menu.css">
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URI;?>/public/lib/css/data_table.css">

<img src="<?php echo BASE_URI;?>/public/lib/img/ico/cxcy.ico" width="50px" height="50px">

 创新创业中心

 <?php echo $navHtml;?>

<?php echo $userHtml;?>

        <menu class="content_left">

 <?php echo $menuHtml;?>

        </menu>

 <?php if(isset($table) && isset($table['addition'])) echo $table['addition']; ?>

                    <?php
                        //标题行
                        if(isset($table) && isset($table['theader'])) echo $table['theader'];
                        //内容行
                        if(isset($table) && isset($table['tbody'])) echo $table['tbody'];
                    ?>

             <?php  if(isset($table) && isset($table['pageBar'])) echo $table['pageBar'];?>

<?php require_once('footer.php');?>


text:
package es.bsc.compss.types.data.operation;

import es.bsc.compss.log.Loggers;
import es.bsc.compss.types.allocatableactions.ExecutionAction;
import es.bsc.compss.types.data.listener.EventListener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class JobTransfersListener extends EventListener {

    // Loggers
    private static final Logger LOGGER = LogManager.getLogger(Loggers.FTM_COMP);
    private static final boolean DEBUG = LOGGER.isDebugEnabled();

    private int operation = 0;
    private int errors = 0;
    private boolean enabled = false;

    private final ExecutionAction execution;

    /**
     * New JobTransfersListener for a given execution action.
     *
     * @param execution Associated ExecutionAction.
     */
    public JobTransfersListener(ExecutionAction execution) {
        this.execution = execution;
    }

    /**
     * Activate the transfers listener.
     */
    public void enable() {
        boolean finished;
        boolean failed;
        synchronized (this) {
            this.enabled = true;
            finished = (this.operation == 0);
            failed = (this.errors > 0);
        }
        if (finished) {
            if (failed) {
                doFailures();
            } else {
                doReady();
            }
        }
    }

    /**
     * Adds a new operation to the listener.
     */
    public synchronized void addOperation() {
        this.operation++;
    }

    @Override
    public void notifyEnd(DataOperation fOp) {
        boolean enabled;
        boolean finished;
        boolean failed;
        synchronized (this) {
            this.operation--;
            finished = (this.operation == 0);
            failed = this.errors > 0;
            enabled = this.enabled;
        }
        if (finished && enabled) {
            if (failed) {
                doFailures();
            } else {
                doReady();
            }
        }
    }

    @Override
    public void notifyFailure(DataOperation fOp, Exception e) {
        String fOpName = "None";
        if (fOp != null) {
            fOpName = fOp.getName();
        }
        if (DEBUG) {
            LOGGER.error("THREAD " + Thread.currentThread().getName() + " File Operation failed on " + fOpName
                + ", file role is JOB_FILE, operation end state is FAILED", e);
        } else {
            LOGGER.error("THREAD " + Thread.currentThread().getName() + " File Operation failed on " + fOpName
                + ", file role is JOB_FILE operation end state is FAILED");
        }

        boolean enabled;
        boolean finished;
        synchronized (this) {
            this.errors++;
            this.operation--;
            finished = this.operation == 0;
            enabled = this.enabled;
        }
        if (enabled && finished) {
            doFailures();
        }
    }

    private void doReady() {
        this.execution.doSubmit(this.getId());
    }

    private void doFailures() {
        this.execution.failedTransfers(this.errors);
    }

}


text:
import  * as DynamicValues from './dynamicValues.model'
import { ControllerModel } from './controller.model'
import { SensorModel } from './sensor.model'
import { DashboardModel } from './dashboard.model'
import { ActionModel } from './action.model'
import { IComponent } from './IComponent.model';
import { KerviService } from '../kervi.service'

export class ComponentFactory{

    public static createComponents(message: any, kerviService:KerviService){
        var foundComponents =this.createComponentsRec(message, kerviService);
        this.linkToDashboards(foundComponents[0], foundComponents[1]);
        return foundComponents[0];
    }

    private static createComponentsRec(message: any, kerviService){
        var result=[];
        var dashboards=[];
        if (Array.isArray(message)) {
            for (var i = 0; (i < message.length); i++) {
                subComponents = this.createComponentsRec(message[i], kerviService);
                result=result.concat(subComponents[0]);
                dashboards=dashboards.concat(subComponents[1]);
            }
        } else {
            var component:any=null;
            var subComponents:any[] = [];
            if (message.componentType=="KerviAction")
                component = new ActionModel(message);
            else if (message.componentType=="dashboard"){
                component = new DashboardModel(message);
                dashboards.push(component);
            } else if (message.componentType=="sensor"){
                component = new SensorModel(message, kerviService);
                subComponents = component.subSensors;
            }else if (message.componentType=="controller")
                component = new ControllerModel(message);
            else if (message.componentType == "boolean-value")
                component = new DynamicValues.DynamicBooleanModel(message);
            else if (message.componentType == "number-value")
                component = new DynamicValues.DynamicNumberModel(message, kerviService);
            else if (message.componentType == "string-value")
                component = new DynamicValues.DynamicStringModel(message);
            else if (message.componentType == "enum-value")
                component = new DynamicValues.DynamicEnumModel(message);
            else if (message.componentType == "datetime-value")
                component = new DynamicValues.DynamicDateTimeModel(message);
            else if (message.componentType == "color-value")
                component = new DynamicValues.DynamicColorModel(message);

            if (component)
                result.push(component);

            if (subComponents){
                for(let subComponent of subComponents){
                    result.push(subComponent);
                }
            }
        }
        return [result, dashboards];
    }

    private static linkToDashboards(components:IComponent[], dashboards:DashboardModel[]){
        console.log("ltd", components, dashboards);

        for(let component of components){
            if (!(component instanceof DashboardModel)){
                for(let link of component.dashboards){
                    for(let dashboard of dashboards){
                        dashboard.addDashboardLink(link);
                    }
                }
            }
        }
    }
}


text: Tests that console correctly finds suggestions in complicated cases.


text:
#ifndef __GC_H_
#define __GC_H_
#define UUID_2FF3A001_1E1B_4344_888A_70F3AAE7B9BB

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <colors.h>

#ifdef __cplusplus
extern "C"
{
#endif

  /**
   * garbdge collection path:
   *   root -> {malloced_obj}
   *   malloced_object -> {ref_object}
   * when root was expired
   *   set root -> nil
   *   then all objs malloced by the root will be GCed
   **/

  typedef struct gc_root {
    struct gc_root *next;
    bool is_primitive;
    char* my_func_name;
    void* my_func;
    void* my_parent_func;
    int m_closed;
  } gc_root_t;

  typedef gc_root_t* gc_root_ptr_t;

  typedef void (*fobj_gc)(void *p);
  typedef void (*delegated_free)(void *p);

  typedef struct gc_obj_holder
    {
      void *p;
      delegated_free _free;
    } gc_obj_holder_t;

  extern void *gc_obj_holder_new(gc_root_t *proot, void *p, delegated_free _free);

  extern gc_root_t *gc_root_new(const char *my_func_name);
  extern gc_root_t *gc_root_new_with_complex_return(const char *my_func_name);
  extern void gc_root_close(gc_root_ptr_t *pproot);
  extern void gc_root_cleanup(void *p);

  extern void *gc_malloc(gc_root_t *proot, size_t sz);
  extern void *gc_malloc_with_gc(gc_root_t *proot, size_t sz, fobj_gc _gc);

  extern void *gc_checkin(gc_root_t *proot, void *dest, void *src);
  extern void *gc_checkout(gc_root_t *proot, void *dest, void *src);

  extern void gc_mark_ref(void *source_ptr, void *dest_ptr);
  extern void gc_mark_ref_with_one2many(void *source_ptr, void *dest_ptr);
  extern void gc_mark_unref(void *source_ptr, void *dest_ptr);
  extern void gc_collect();

  extern void xgc_print_stacktrace(char *fname, int lineno);

#ifndef __GNUC__
#error   RAII For c  support gcc only
#endif

#define using_raii_proot()                                                        \
  for ( gc_root_ptr_t                                                             \
       proot __attribute__((cleanup (gc_root_close))) = gc_root_new(__FUNCTION__) \
       , proot_next = proot;                                                      \
       proot_next == proot; proot_next++)

#define using_raii_proot_complex_return()              \
  for ( gc_root_ptr_t                                  \
       proot __attribute__((cleanup (gc_root_close)))  \
       = gc_root_new_with_complex_return(__FUNCTION__) \
       , proot_next=proot;                             \
       proot_next == proot; proot_next++ )

#define dismiss_unused(o) \
  do {                    \
  } while ((o) != (o))

#ifndef cast
#define cast(type, expr) ((type)(expr))
#endif

#ifndef sizeof_uint
# define sizeof_uint(type) cast(unsigned int, sizeof(type))
#endif

#define GC_LOGLEVEL_DEBUG       7
#define GC_LOGLEVEL_INFO        6
#define GC_LOGLEVEL_WARNING     5
#define GC_LOGLEVEL_ERROR       4
#define GC_LOGLEVEL_FATAL       4

#define GC_LOG_BRIEF false

#define GC_LOG(LEVEL, logstr, color, __fmt, ...)       if (LEVEL <= __gc_log_level)  {   \
  if (GC_LOG_BRIEF) \
  fprintf(stdout, color "%s:%d\t%s\t", strrchr(__FILE__, '/')+1,  __LINE__,logstr); \
  else \
  fprintf(stdout, color "%s:%s:%d\t%s\t", strrchr(__FILE__, '/')+1,   __FUNCTION__,__LINE__, logstr); \
  fprintf(stdout, __fmt, ##__VA_ARGS__); \
  fprintf(stdout, __C_RESET__ ); \
}

#define xgc_debug(__fmt, ...)     GC_LOG(GC_LOGLEVEL_DEBUG, "DEBUG", __C_RESET__,  __fmt, ##__VA_ARGS__)
#define xgc_info(__fmt, ...)     GC_LOG(GC_LOGLEVEL_INFO, "INFO", __C_YELLOW__,  __fmt, ##__VA_ARGS__)
#define xgc_warn(__fmt, ...)     GC_LOG(GC_LOGLEVEL_WARNING, "WARN", __C_CYAN__,  __fmt, ##__VA_ARGS__)
#define xgc_error(__fmt, ...)     GC_LOG(GC_LOGLEVEL_ERROR, "ERROR", __C_RED__,  __fmt, ##__VA_ARGS__)
#define xgc_fatal(__fmt, ...)     GC_LOG(GC_LOGLEVEL_ERROR, "FATAL", __C_YELLOW__,  __fmt, ##__VA_ARGS__)

#define xgc_assert(expr)  { if (!(expr)) { xgc_print_stacktrace(__FILE__,  __LINE__);  assert(expr); } }

#define xgc_println() printf("%s\n", __C_RESET__ );
#define xgc_reset() pintf("%s", __C_RESET__ );

extern int __gc_log_level;

#ifdef __cplusplus
}

#endif

#endif


text:
import __init__
import settings

tweenk_core = settings.core()
tweenk_balance = settings.balance()

import db

class WeeklyStats:

	mongo = db.mongoAdapter()
	balance = settings.balance()
	core = settings.core()

	def __init__(self):
		pass

	def updateStats(self):

		collection = 'weekly_stats'

		if not self.mongo.collectionExist(collection):
			self.mongo.createCollection(collection)

		stats = self.mongo.getu('statistics', {'user_id': 12164662})
		prev_weekly = self.mongo.getu(collection)

		if not prev_weekly:
			prev_weekly = []

		str_prev_weekly = {}
		for stat in prev_weekly:
			str_prev_weekly.update({str(stat['user_id']): stat['stats']})

		to_update = []

		for stat in stats:
			str_id = str(stat['user_id'])
			if str_id in str_prev_weekly:
				diff = {
					'monsters': stat['stats']['kills_monster'] - str_prev_weekly[str_id]['monsters'],
					'players': stat['stats']['pvp_kills_player'] - str_prev_weekly[str_id]['players'],
					'lvl': stat['stats']['lvl'] - str_prev_weekly[str_id]['lvl']
				}

				record = {'user_id': stat['user_id'], 'stats': diff}

				if diff['monsters'] + diff['players'] + diff['lvl'] > 0:
					to_update.append(record)

					normal = {
						'monsters': stat['stats']['kills_monster'],
						'players': stat['stats']['pvp_kills_player'],
						'lvl': stat['stats']['lvl']
					}

					self.mongo.update(collection, {'user_id': stat['user_id']}, {'stats': normal})

			else:
				diff = {
					'monsters': stat['stats']['kills_monster'],
				    'players': stat['stats']['pvp_kills_player'],
				    'lvl': stat['stats']['lvl']
				}

				record = {'user_id': stat['user_id'], 'stats': diff}

				if diff['monsters'] + diff['players'] + diff['lvl'] > 1:
					to_update.append(record)

				self.mongo.insert(collection, record)

		for item in to_update:
			print item

if __name__ == "__main__":

	ws = WeeklyStats()
	ws.updateStats()


text:
import { Component } from '@angular/core';
import { FormioAuthService } from '../auth.service';
@Component({
  templateUrl: './login.component.html'
})
export class FormioAuthLoginComponent {
  constructor(public service: FormioAuthService) {}
}


text:
module Rubybench
  module CLI
    class Reporter
      def initialize(formatter)

      end
    end
  end
end


text:
.amazonjs_search_form input[type="text"] {
  margin: 5px 0;
  padding: 5px;
  width: 80%;
}
.amazonjs_search_form .button-large {
  height: 30px !important;
  line-height: 28px !important;
  padding: 0 12px 2px !important;
}

#search_results {
  margin: 1em;
  min-height: 200px;
}
#search_results .error .error_body {
  overflow: auto;
}
#search_results .indicator {
  display: block;
  width: 300px;
  height: 200px;
  margin: 0 auto;
  background: transparent url(../images/ajax-loader.gif) no-repeat center;
}
#search_results .searchindex {
  clear: both;
}
#search_results .searchpager {
  border: 1px solid #ddd;
  text-align: center;
  padding: 2px;
  margin: 2px;
}
#search_results .searchpager .prev {
  margin-right: 1em;
}
#search_results .searchpager .next {
  margin-left: 1em;
}
#search_results .amazonjs_searchitem {
  display: block;
  margin: 0;
  padding: 5px;
  border-bottom: 1px solid #ddd;
}
#search_results .amazonjs_searchitem .amazonjs_footer {
  clear: both;
}
#search_results h4 {
  display: inline;
  font-size: 1em;
  font-weight: normal;
  margin: .5em;
}
#search_results h4 a {
  text-decoration: none;
}
#search_results img {
  float: left;
  border: 1px solid #DFDFDF;
}
#search_results .amazonjs_searchitem .select {
  float: right !important;
  margin-left: 1em;
}

#overlay {
  position: absolute;
  display: none;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background-color: #fff;
  filter: alpha(opacity=75);
  /*IE*/
  -moz-opacity: 0.75;
  /*FF*/
  opacity: 0.75;
}

#template_form {
  position: absolute;
  display: none;
  border: 1px solid #ddd;
  background-color: #fff;
  left: 5px;
  right: 5px;
  padding: 10px;
}
#template_form h2 {
  font-size: 1em;
  margin: 5px 0;
  padding: 0;
}
#template_form label, #template_form legend {
  font-size: .9em;
}
#template_form label.disabled {
  color: #999;
}
#template_form .select_template {
  margin-bottom: 10px;
}
#template_form .select_template legend {
  margin: 5px 0;
}
#template_form .buttons {
  margin: 5px auto 0 auto;
  text-align: center;
}

#select_template fieldset {
  margin-left: 1em;
}
#select_template fieldset input {
  margin-left: 1em;
}

#preview_code {
  width: 100%;
  height: 4em;
  font-size: .9em;
}


text:
///////////////////////////////////////////////////////////////////////////////
//
// File GlobalLinSys.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: GlobalLinSys definition
//
///////////////////////////////////////////////////////////////////////////////

#include <MultiRegions/GlobalLinSysPETSc.h>

#include "petscis.h"
#include "petscversion.h"

namespace Nektar
{
    namespace MultiRegions
    {
        /**
         * @class GlobalLinSysPETSc
         *
         * Solves a linear system using PETSc.
         */

        GlobalLinSysPETSc::GlobalLinSysPETSc(
            const GlobalLinSysKey                &pKey,
            const boost::weak_ptr<ExpList>       &pExp,
            const boost::shared_ptr<AssemblyMap> &pLocToGloMap)
            : GlobalLinSys(pKey, pExp, pLocToGloMap)
        {
            // Check PETSc is initialized
            // For some reason, this is needed on OS X as logging is not
            // initialized properly in the call within CommMpi.
            PetscInitializeNoArguments();

            // Create matrix
            MatCreate(PETSC_COMM_WORLD, &m_matrix);
        }

        GlobalLinSysPETSc::~GlobalLinSysPETSc()
        {
        }

        /**
         * @brief Solve linear system using PETSc.
         *
         * The general strategy being a PETSc solve is to:
         *
         * - Copy values into the PETSc vector #m_b
         * - Solve the system #m_ksp and place result into #m_x.
         * - Scatter results back into #m_locVec using #m_ctx scatter object.
         * - Copy from #m_locVec to output array #pOutput.
         */
        void GlobalLinSysPETSc::v_SolveLinearSystem(
            const int                          pNumRows,
            const Array<OneD,const NekDouble> &pInput,
                  Array<OneD,      NekDouble> &pOutput,
            const AssemblyMapSharedPtr        &locToGloMap,
            const int                          pNumDir)
        {
            const int nHomDofs = pNumRows - pNumDir;

            // Populate RHS vector from input
            VecSetValues(m_b, nHomDofs, &m_reorderedMap[0],
                         &pInput[pNumDir], INSERT_VALUES);

            // Assemble RHS vector
            VecAssemblyBegin(m_b);
            VecAssemblyEnd  (m_b);

            // Do system solve
            KSPSolve(m_ksp, m_b, m_x);

            // Scatter results to local vector
            VecScatterBegin(m_ctx, m_x, m_locVec,
                            INSERT_VALUES, SCATTER_FORWARD);
            VecScatterEnd  (m_ctx, m_x, m_locVec,
                            INSERT_VALUES, SCATTER_FORWARD);

            // Copy results into output vector
            PetscScalar *tmp;
            VecGetArray    (m_locVec, &tmp);
            Vmath::Vcopy   (nHomDofs, tmp, 1, &pOutput[pNumDir], 1);
            VecRestoreArray(m_locVec, &tmp);
        }

        /**
         * @brief Set up PETSc local (equivalent to Nektar++ global) and global
         * (equivalent to universal) scatter maps.
         *
         * These maps are used in GlobalLinSysPETSc::v_SolveLinearSystem to
         * scatter the solution vector back to each process.
         */
        void GlobalLinSysPETSc::SetUpScatter()
        {
            const int nHomDofs = m_reorderedMap.size();

            // Create local and global numbering systems for vector
            IS isGlobal, isLocal;
            ISCreateGeneral(PETSC_COMM_SELF, nHomDofs, &m_reorderedMap[0],
                            PETSC_COPY_VALUES, &isGlobal);
            ISCreateStride (PETSC_COMM_SELF, nHomDofs, 0, 1, &isLocal);

            // Create local vector for output
            VecCreate        (PETSC_COMM_SELF, &m_locVec);
            VecSetSizes      (m_locVec, nHomDofs, PETSC_DECIDE);
            VecSetFromOptions(m_locVec);

            // Create scatter context
            VecScatterCreate (m_x, isGlobal, m_locVec, isLocal, &m_ctx);

            // Clean up
            ISDestroy(&isGlobal);
            ISDestroy(&isLocal);
        }

        /**
         * @brief Calculate a reordering of universal IDs for PETSc.
         *
         * PETSc requires a unique, contiguous index of all global and universal
         * degrees of freedom which represents its position inside the
         * matrix. Presently Gs does not guarantee this, so this routine
         * constructs a new universal mapping.
         */
        void GlobalLinSysPETSc::CalculateReordering(
            const Array<OneD, const int> &glo2uniMap,
            const Array<OneD, const int> &glo2unique,
            const AssemblyMapSharedPtr   &pLocToGloMap)
        {
            LibUtilities::CommSharedPtr vComm
                = m_expList.lock()->GetSession()->GetComm();

            const int nDirDofs = pLocToGloMap->GetNumGlobalDirBndCoeffs();
            const int nHomDofs = glo2uniMap.num_elements() - nDirDofs;
            const int nProc    = vComm->GetSize();
            const int rank     = vComm->GetRank();

            int n, cnt;

            // Count number of unique degrees of freedom on each process.
            m_nLocal = Vmath::Vsum(nHomDofs, glo2unique + nDirDofs, 1);
            m_reorderedMap.resize(nHomDofs);

            // Reduce coefficient counts across all processors.
            Array<OneD, int> localCounts(nProc, 0), localOffset(nProc, 0);
            localCounts[rank] = nHomDofs;
            vComm->AllReduce(localCounts, LibUtilities::ReduceSum);

            for (n = 1; n < nProc; ++n)
            {
                localOffset[n] = localOffset[n-1] + localCounts[n-1];
            }

            int totHomDofs = Vmath::Vsum(nProc, localCounts, 1);
            vector<unsigned int> allUniIds(totHomDofs, 0);

            // Assemble list of universal IDs
            for (n = 0; n < nHomDofs; ++n)
            {
                int gid = n + nDirDofs;
                allUniIds[n + localOffset[rank]] = glo2uniMap[gid];
            }

            // Reduce this across processors so that each process has a list of
            // all universal IDs.
            vComm->AllReduce(allUniIds, LibUtilities::ReduceSum);
            std::sort(allUniIds.begin(), allUniIds.end());
            map<int,int> uniIdReorder;

            // Renumber starting from 0.
            for (cnt = n = 0; n < allUniIds.size(); ++n)
            {
                if (uniIdReorder.count(allUniIds[n]) > 0)
                {
                    continue;
                }

                uniIdReorder[allUniIds[n]] = cnt++;
            }

            // Populate reordering map.
            for (n = 0; n < nHomDofs; ++n)
            {
                int gid = n + nDirDofs;
                int uniId = glo2uniMap[gid];
                ASSERTL0(uniIdReorder.count(uniId) > 0, "Error in ordering");
                m_reorderedMap[n] = uniIdReorder[uniId];
            }
        }

        /**
         * @brief Construct PETSc matrix and vector handles.
         *
         * @todo Preallocation should be done at this point, since presently
         *       matrix allocation takes a significant amount of time.
         */
        void GlobalLinSysPETSc::SetUpMatVec()
        {
            // CREATE VECTORS
            VecCreate        (PETSC_COMM_WORLD, &m_x);
            VecSetSizes      (m_x, m_nLocal, PETSC_DECIDE);
            VecSetFromOptions(m_x);
            VecDuplicate     (m_x, &m_b);

            // CREATE MATRICES
            MatCreate        (PETSC_COMM_WORLD, &m_matrix);
            MatSetType       (m_matrix, MATAIJ);
            MatSetSizes      (m_matrix, m_nLocal, m_nLocal,
                              PETSC_DETERMINE, PETSC_DETERMINE);
            MatSetFromOptions(m_matrix);
            MatSetUp         (m_matrix);
        }

        /**
         * @brief Set up KSP solver object.
         *
         * This is reasonably generic setup -- most solver types can be changed
         * using the .petscrc file.
         */
        void GlobalLinSysPETSc::SetUpSolver(NekDouble tolerance)
        {
            KSPCreate(PETSC_COMM_WORLD, &m_ksp);
            KSPSetTolerances(
                m_ksp, tolerance, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT);
            KSPSetFromOptions(m_ksp);
#if PETSC_VERSION_GE(3,5,0)
            KSPSetOperators(m_ksp, m_matrix, m_matrix);
#else
            KSPSetOperators(m_ksp, m_matrix, m_matrix, SAME_NONZERO_PATTERN);
#endif
        }
    }
}


text:
using std::endl;
using std::map;
using std::string;
using std::vector;

using namespace cv;

ImgProcImage::ImgProcImage()
{
}

ImgProcImage::ImgProcImage(const cv::Mat &image, ImgprocMode mode, std::ofstream *metadata_file, const string &image_dest)
: original(image), mode(mode), metadata_file(metadata_file), dest(image_dest)
{
    // imwrite requires filenames to end with an image file extension in order to know what
    // type of image file to create
    if (this->mode != BATCH)
    {
        return;
    }

    bool dest_ends_with_valid_ext = false;

    for (int i = 0; i < NUM_SUPPORTED_IMG_EXT; i++)
    {
        size_t pos = this->dest.rfind(SUPPORTED_IMG_EXT[i]);
        dest_ends_with_valid_ext |= (pos == (this->dest.size() - strlen(SUPPORTED_IMG_EXT[i])));
    }

    if (!dest_ends_with_valid_ext)
    {
        this->dest += DEFAULT_IMG_EXT;
    }
}

cv::Mat &ImgProcImage::get_original_image()
{
    return this->original;
}

void ImgProcImage::add_intermediate_image(const string &name, const Mat &image)
{
    // Intermediate images only used in WINDOW mode
    if (this->mode == WINDOW)
    {
        this->intermediate_images[name] = image.clone();
    }
}

void ImgProcImage::add_final_image(const Mat &image)
{
    this->processed = image;
}

bool ImgProcImage::record()
{
    int key = 0;
    map<string, Mat>::iterator    img_it;
    map<string, double>::iterator time_it;
    vector<Vec3f>::iterator       circle_it;
    vector<string>::iterator      obs_it;

    switch (this->mode)
    {
    case WINDOW:
        // Show original image
        imshow("original", this->original);

        // Show intermediate images
        for (img_it = this->intermediate_images.begin(); img_it != this->intermediate_images.end(); img_it++)
        {
            imshow(img_it->first, img_it->second);
        }

        // Show final image
        imshow("processed", this->processed);

        // Wait for user to press any key
        key = waitKey(0);
        destroyAllWindows();
        break;

    case BATCH:

        // Save processed image
        imwrite(this->dest, this->processed);

        // Save filename metadata
        *(this->metadata_file) << this->dest << METADATA_SEP;

        // Save circle metadata
        for (circle_it = this->circles.begin(); circle_it != this->circles.end(); circle_it++)
        {
            *(this->metadata_file) << "c(" << (*circle_it)[0] << "," << (*circle_it)[1] << "," << (*circle_it)[2] << ")" << METADATA_SEP;
        }

        // Save time metadata
        for (time_it = this->execution_times.begin(); time_it != this->execution_times.end(); time_it++)
        {
            *(this->metadata_file) << "t(\"" << time_it->first << "\"," << time_it->second << ")" << METADATA_SEP;
        }

        // Save observation metadata
        for (obs_it = this->observations.begin(); obs_it != this->observations.end(); obs_it++)
        {
            *(this->metadata_file) << "\"" << *obs_it << "\""  << METADATA_SEP;
        }

        // End line
        *(this->metadata_file) << endl;

        break;

    default:
        break;
    }

    return key == ESC_KEY;
}

void ImgProcImage::add_circle(const Vec3f &circle)
{
    this->circles.push_back(circle);
}

void ImgProcImage::add_circles(const vector<Vec3f> &new_circles)
{
    this->circles.reserve(this->circles.size() + std::distance(new_circles.begin(), new_circles.end()));
    this->circles.insert(this->circles.end(), new_circles.begin(), new_circles.end());
}

void ImgProcImage::add_observation(const std::string &observation)
{
    this->observations.push_back(observation);
}

void ImgProcImage::add_execution_time(const std::string &name, double num_secs)
{
    this->execution_times[name] = num_secs;
}

const Mat& ImgProcImage::get_original() const
{
    return this->original;
}


text:
<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Authenticatable
{
     use EntrustUserTrait;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function ngos(){
      return $this->belongsToMany('App\Ngo', 'ngo_users');
    }
    public function languages(){
      return $this->belongsToMany('App\Language', 'user_languages');
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include "arrow/compute/function_internal.h"

#include "arrow/array/util.h"
#include "arrow/compute/function.h"
#include "arrow/compute/registry.h"
#include "arrow/io/memory.h"
#include "arrow/ipc/reader.h"
#include "arrow/ipc/writer.h"
#include "arrow/record_batch.h"
#include "arrow/scalar.h"
#include "arrow/util/checked_cast.h"

namespace arrow {
namespace compute {
namespace internal {
using ::arrow::internal::checked_cast;

constexpr char kTypeNameField[] = "_type_name";

Result<std::shared_ptr<StructScalar>> FunctionOptionsToStructScalar(
    const FunctionOptions& options) {
  std::vector<std::string> field_names;
  std::vector<std::shared_ptr<Scalar>> values;
  const auto* options_type =
      dynamic_cast<const GenericOptionsType*>(options.options_type());
  if (!options_type) {
    return Status::NotImplemented("serializing ", options.type_name(),
                                  " to StructScalar");
  }
  RETURN_NOT_OK(options_type->ToStructScalar(options, &field_names, &values));
  field_names.push_back(kTypeNameField);
  const char* options_name = options.type_name();
  values.emplace_back(
      new BinaryScalar(Buffer::Wrap(options_name, std::strlen(options_name))));
  return StructScalar::Make(std::move(values), std::move(field_names));
}

Result<std::unique_ptr<FunctionOptions>> FunctionOptionsFromStructScalar(
    const StructScalar& scalar) {
  ARROW_ASSIGN_OR_RAISE(auto type_name_holder, scalar.field(kTypeNameField));
  const std::string type_name =
      checked_cast<const BinaryScalar&>(*type_name_holder).value->ToString();
  ARROW_ASSIGN_OR_RAISE(auto raw_options_type,
                        GetFunctionRegistry()->GetFunctionOptionsType(type_name));
  const auto* options_type = checked_cast<const GenericOptionsType*>(raw_options_type);
  return options_type->FromStructScalar(scalar);
}

Result<std::shared_ptr<Buffer>> GenericOptionsType::Serialize(
    const FunctionOptions& options) const {
  ARROW_ASSIGN_OR_RAISE(auto scalar, FunctionOptionsToStructScalar(options));
  ARROW_ASSIGN_OR_RAISE(auto array, MakeArrayFromScalar(*scalar, 1));
  auto batch =
      RecordBatch::Make(schema({field("", array->type())}), /*num_rows=*/1, {array});
  ARROW_ASSIGN_OR_RAISE(auto stream, io::BufferOutputStream::Create());
  ARROW_ASSIGN_OR_RAISE(auto writer, ipc::MakeFileWriter(stream, batch->schema()));
  RETURN_NOT_OK(writer->WriteRecordBatch(*batch));
  RETURN_NOT_OK(writer->Close());
  return stream->Finish();
}

Result<std::unique_ptr<FunctionOptions>> GenericOptionsType::Deserialize(
    const Buffer& buffer) const {
  return DeserializeFunctionOptions(buffer);
}

Result<std::unique_ptr<FunctionOptions>> DeserializeFunctionOptions(
    const Buffer& buffer) {
  io::BufferReader stream(buffer);
  ARROW_ASSIGN_OR_RAISE(auto reader, ipc::RecordBatchFileReader::Open(&stream));
  ARROW_ASSIGN_OR_RAISE(auto batch, reader->ReadRecordBatch(0));
  if (batch->num_rows() != 1) {
    return Status::Invalid(
        "serialized FunctionOptions's batch repr was not a single row - had ",
        batch->num_rows());
  }
  if (batch->num_columns() != 1) {
    return Status::Invalid(
        "serialized FunctionOptions's batch repr was not a single column - had ",
        batch->num_columns());
  }
  auto column = batch->column(0);
  if (column->type()->id() != Type::STRUCT) {
    return Status::Invalid(
        "serialized FunctionOptions's batch repr was not a struct column - was ",
        column->type()->ToString());
  }
  ARROW_ASSIGN_OR_RAISE(auto raw_scalar,
                        checked_cast<const StructArray&>(*column).GetScalar(0));
  auto scalar = checked_cast<const StructScalar&>(*raw_scalar);
  return FunctionOptionsFromStructScalar(scalar);
}

}  // namespace internal
}  // namespace compute
}  // namespace arrow


text:
require 'rubygems/package'  # Gem::Package::TarReader
require 'stringio'

module TarFile

  class Reader

    def initialize(tar_file)
      io = StringIO.new(tar_file, 'r+t')
      @reader = Gem::Package::TarReader.new(io)
    end

    def files
      @reader.each.with_object({}) do |entry,memo|
        filename = entry.full_name
        content = entry.read || '' # avoid nil
        memo[filename] = content
      end
    end

  end

end


text:
/* $Id$ */

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.francelabs.datafari.connectors.share;

import java.util.Locale;
import java.util.Map;

import org.apache.manifoldcf.core.interfaces.IHTTPOutput;
import org.apache.manifoldcf.core.interfaces.ManifoldCFException;

public class Messages extends org.apache.manifoldcf.ui.i18n.Messages {
  public static final String DEFAULT_BUNDLE_NAME = "com.francelabs.datafari.connectors.share.common";
  public static final String DEFAULT_PATH_NAME = "com.francelabs.datafari.connectors.share";

  /**
   * Constructor - do no instantiate
   */
  protected Messages() {
  }

  public static String getString(final Locale locale, final String messageKey) {
    return getString(DEFAULT_BUNDLE_NAME, locale, messageKey, null);
  }

  public static String getAttributeString(final Locale locale, final String messageKey) {
    return getAttributeString(DEFAULT_BUNDLE_NAME, locale, messageKey, null);
  }

  public static String getBodyString(final Locale locale, final String messageKey) {
    return getBodyString(DEFAULT_BUNDLE_NAME, locale, messageKey, null);
  }

  public static String getAttributeJavascriptString(final Locale locale, final String messageKey) {
    return getAttributeJavascriptString(DEFAULT_BUNDLE_NAME, locale, messageKey, null);
  }

  public static String getBodyJavascriptString(final Locale locale, final String messageKey) {
    return getBodyJavascriptString(DEFAULT_BUNDLE_NAME, locale, messageKey, null);
  }

  public static String getString(final Locale locale, final String messageKey, final Object[] args) {
    return getString(DEFAULT_BUNDLE_NAME, locale, messageKey, args);
  }

  public static String getAttributeString(final Locale locale, final String messageKey, final Object[] args) {
    return getAttributeString(DEFAULT_BUNDLE_NAME, locale, messageKey, args);
  }

  public static String getBodyString(final Locale locale, final String messageKey, final Object[] args) {
    return getBodyString(DEFAULT_BUNDLE_NAME, locale, messageKey, args);
  }

  public static String getAttributeJavascriptString(final Locale locale, final String messageKey, final Object[] args) {
    return getAttributeJavascriptString(DEFAULT_BUNDLE_NAME, locale, messageKey, args);
  }

  public static String getBodyJavascriptString(final Locale locale, final String messageKey, final Object[] args) {
    return getBodyJavascriptString(DEFAULT_BUNDLE_NAME, locale, messageKey, args);
  }

  // More general methods which allow bundlenames and class loaders to be
  // specified.

  public static String getString(final String bundleName, final Locale locale, final String messageKey, final Object[] args) {
    return getString(Messages.class, bundleName, locale, messageKey, args);
  }

  public static String getAttributeString(final String bundleName, final Locale locale, final String messageKey, final Object[] args) {
    return getAttributeString(Messages.class, bundleName, locale, messageKey, args);
  }

  public static String getBodyString(final String bundleName, final Locale locale, final String messageKey, final Object[] args) {
    return getBodyString(Messages.class, bundleName, locale, messageKey, args);
  }

  public static String getAttributeJavascriptString(final String bundleName, final Locale locale, final String messageKey, final Object[] args) {
    return getAttributeJavascriptString(Messages.class, bundleName, locale, messageKey, args);
  }

  public static String getBodyJavascriptString(final String bundleName, final Locale locale, final String messageKey, final Object[] args) {
    return getBodyJavascriptString(Messages.class, bundleName, locale, messageKey, args);
  }

  // Resource output

  public static void outputResource(final IHTTPOutput output, final Locale locale, final String resourceKey, final Map<String, String> substitutionParameters, final boolean mapToUpperCase) throws ManifoldCFException {
    outputResource(output, Messages.class, DEFAULT_PATH_NAME, locale, resourceKey, substitutionParameters, mapToUpperCase);
  }

  public static void outputResourceWithVelocity(final IHTTPOutput output, final Locale locale, final String resourceKey, final Map<String, String> substitutionParameters, final boolean mapToUpperCase) throws ManifoldCFException {
    outputResourceWithVelocity(output, Messages.class, DEFAULT_BUNDLE_NAME, DEFAULT_PATH_NAME, locale, resourceKey, substitutionParameters, mapToUpperCase);
  }

  public static void outputResourceWithVelocity(final IHTTPOutput output, final Locale locale, final String resourceKey, final Map<String, Object> contextObjects) throws ManifoldCFException {
    outputResourceWithVelocity(output, Messages.class, DEFAULT_BUNDLE_NAME, DEFAULT_PATH_NAME, locale, resourceKey, contextObjects);
  }

}


text:
package com.packt.flappeebee;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.packt.flappeebee.model.GameWorld;
import com.packt.flappeebee.model.GameWorldSettings;

public class GameScreen extends ScreenAdapter {

    private GameWorld gameWorld;

    @Override
    public void show() {
        boolean npotSupported = Gdx.graphics.supportsExtension("GL_OES_texture_npot")
                || Gdx.graphics.supportsExtension("GL_ARB_texture_non_power_of_two");
        System.out.println("isNpotSupported: " + npotSupported);

        GameWorldSettings gameWorldSettings = new GameWorldSettings();
        gameWorldSettings.virtualWidth = 1024;
        gameWorldSettings.virtualHeight = 768;
        gameWorld = new GameWorld(gameWorldSettings);
    }

    @Override
    public void resize(int width, int height) {
        gameWorld.resize(width, height);
    }

    @Override
    public void render(float delta) {
        clearScreen();                      // очищаем экран
        // обработка клавиш теперь размазана по коду
        gameWorld.render(delta);             // обновление игрового мира (состояние и рендеринг)

        //TODO пробросить вывод runtime-ошибок на экран
    }

    private void clearScreen() {
        Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    }

}


text:
"""
	@Brief test suggestion-server interface
	@Author wmd
	@Create 2015.11.05
"""

import sys

from tiny_sugg import SuggServer

def test():
	server = SuggServer()
	server.init()

	prefix = "面"
	sugg_info = server.get_sugg(prefix)

	print sugg_info['prefix']
	for item in sugg_info['sugg']:
		print '\t%s\t%s\t%s' % (item['text'], item['score'], item['att'])

if __name__ == '__main__':
	test()


text:
package custommetrics

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"k8s.io/kubernetes/pkg/api"
)

func TestGetCAdvisorCustomMetricsDefinitionPath(t *testing.T) {

	regularContainer := &api.Container{
		Name: "test_container",
	}

	cmContainer := &api.Container{
		Name: "test_container",
		VolumeMounts: []api.VolumeMount{
			{
				Name:      "cm",
				MountPath: CustomMetricsDefinitionDir,
			},
		},
	}
	path, err := GetCAdvisorCustomMetricsDefinitionPath(regularContainer)
	assert.Nil(t, path)
	assert.NoError(t, err)

	path, err = GetCAdvisorCustomMetricsDefinitionPath(cmContainer)
	assert.NotEmpty(t, *path)
	assert.NoError(t, err)
}


text:
<!DOCTYPE html>

<title>OffscreenCanvas test: 2d.imageData.create1.initial</title>

2d.imageData.create1.initial

createImageData(imgdata) returns transparent black data of the right size


text:
using System;

namespace HoloToolkit.Sharing.SyncModel
{
    /// <summary>
    /// Used to markup SyncPrimitives within a class.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field)]
    public class SyncDataAttribute : Attribute
    {
        public string CustomFieldName;
    }

    /// <summary>
    /// Used to markup SyncObject classes, so that they properly get instantiated
    /// when using a hierarchical data model that inherits from SyncObject.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class SyncDataClassAttribute : Attribute
    {
        public string CustomClassName;
    }
}


text:
package fr.abachar.collab.web.tags.beans;

import fr.abachar.collab.model.Tag;

/**
 * Created with IntelliJ IDEA.
 * User: abachar
 * Date: 28/06/13
 * Time: 18:40
 * To change this template use File | Settings | File Templates.
 */
public class TagUpdateBean {
    private Tag tag;

    public TagUpdateBean(Tag tag) {
        //To change body of created methods use File | Settings | File Templates.
    }

    public Tag getTag() {
        return tag;
    }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.gpp;

import com.intellij.codeInsight.generation.OverrideImplementExploreUtil;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap;
import org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrSignature;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider;
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType;
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.AbstractClosureParameterEnhancer;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;

import java.util.*;

/**
 * @author peter
 */
public class GppClosureParameterTypeProvider extends AbstractClosureParameterEnhancer {
  @Override
  protected PsiType getClosureParameterType(@NotNull GrFunctionalExpression expression, int index) {
    final PsiElement parent = expression.getParent();
    if (parent instanceof GrNamedArgument) {
      final Pair<PsiMethod, PsiSubstitutor> pair = getOverriddenMethod((GrNamedArgument)parent);
      if (pair != null) {
        final PsiParameter[] parameters = pair.first.getParameterList().getParameters();
        if (parameters.length > index) {
          return pair.second.substitute(parameters[index].getType());
        }
        return null;
      }
    }

    if (parent instanceof GrListOrMap) {
      final GrListOrMap list = (GrListOrMap)parent;
      if (!list.isMap()) {
        final PsiType listType = list.getType();
        final int argIndex = Arrays.asList(list.getInitializers()).indexOf(expression);
        assert argIndex >= 0;
        if (listType instanceof GrTupleType) {
          for (PsiType type : GroovyExpectedTypesProvider.getDefaultExpectedTypes(list)) {
            if (!(type instanceof PsiClassType)) continue;

            final GroovyResolveResult[] candidates = PsiUtil.getConstructorCandidates((PsiClassType)type,((GrTupleType)listType).getComponentTypesArray(), expression);
            for (GroovyResolveResult resolveResult : candidates) {
              final PsiElement method = resolveResult.getElement();
              if (!(method instanceof PsiMethod) || !((PsiMethod)method).isConstructor()) continue;

              final PsiParameter[] parameters = ((PsiMethod)method).getParameterList().getParameters();
              if (parameters.length <= argIndex) continue;

              final PsiType toCastTo = resolveResult.getSubstitutor().substitute(parameters[argIndex].getType());
              final PsiType suggestion = getSingleMethodParameterType(toCastTo, index, expression);
              if (suggestion != null) return suggestion;
            }
          }
        }
        return null;
      }
    }

    for (PsiType constraint : GroovyExpectedTypesProvider.getDefaultExpectedTypes(expression)) {
      final PsiType suggestion = getSingleMethodParameterType(constraint, index, expression);
      if (suggestion != null) {
        return suggestion;
      }
    }
    return null;
  }

  @Nullable
  public static Pair<PsiMethod, PsiSubstitutor> getOverriddenMethod(GrNamedArgument namedArgument) {
    return ContainerUtil.getFirstItem(getOverriddenMethodVariants(namedArgument), null);
  }

  @NotNull
  public static List<Pair<PsiMethod, PsiSubstitutor>> getOverriddenMethodVariants(GrNamedArgument namedArgument) {

    final GrArgumentLabel label = namedArgument.getLabel();
    if (label == null) {
      return Collections.emptyList();
    }

    final String methodName = label.getName();
    if (methodName == null) {
      return Collections.emptyList();
    }

    final PsiElement map = namedArgument.getParent();
    if (map instanceof GrListOrMap && ((GrListOrMap)map).isMap()) {
      for (PsiType expected : GroovyExpectedTypesProvider.getDefaultExpectedTypes((GrExpression)map)) {
        if (expected instanceof PsiClassType) {
          final List<Pair<PsiMethod, PsiSubstitutor>> pairs = getMethodsToOverrideImplementInInheritor((PsiClassType)expected, false);
          return ContainerUtil.findAll(pairs, pair -> methodName.equals(pair.first.getName()));
        }
      }
    }

    return Collections.emptyList();
  }

  @Nullable
  public static PsiType getSingleMethodParameterType(@Nullable PsiType type, int index, @NotNull GrFunctionalExpression expression) {
    final PsiType[] signature = findSingleAbstractMethodSignature(type);
    if (signature == null) {
      return null;
    }
    final GrSignature closureSignature = GrClosureSignatureUtil.createSignature(expression);
    if (GrClosureSignatureUtil.isSignatureApplicable(Collections.singletonList(closureSignature), signature, expression)) {
      return signature.length > index ? signature[index] : PsiType.NULL;
    }
    return null;
  }

  @Nullable
  public static PsiType[] findSingleAbstractMethodSignature(@Nullable PsiType type) {
    if (type instanceof PsiClassType && !(TypesUtil.isClassType(type, GroovyCommonClassNames.GROOVY_LANG_CLOSURE))) {
      List<Pair<PsiMethod, PsiSubstitutor>> result = getMethodsToOverrideImplementInInheritor((PsiClassType)type, true);
      if (result.size() == 1) {
        return getParameterTypes(result.get(0));
      }
    }
    return null;
  }

  public static PsiType[] getParameterTypes(final Pair<PsiMethod, PsiSubstitutor> pair) {
    return ContainerUtil.map2Array(pair.first.getParameterList().getParameters(), PsiType.class, psiParameter -> pair.second.substitute(psiParameter.getType()));
  }

  @NotNull
  public static List<Pair<PsiMethod, PsiSubstitutor>> getMethodsToOverrideImplementInInheritor(PsiClassType classType, boolean toImplement) {
    final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics();
    final PsiClass psiClass = resolveResult.getElement();
    if (psiClass == null) {
      return Collections.emptyList();
    }

    List<Pair<PsiMethod, PsiSubstitutor>> over = getMethodsToOverrideImplement(psiClass, false);
    List<Pair<PsiMethod, PsiSubstitutor>> impl = getMethodsToOverrideImplement(psiClass, true);

    for (PsiMethod method : psiClass.getMethods()) {
      (method.hasModifierProperty(PsiModifier.ABSTRACT) ? impl : over).add(Pair.create(method, PsiSubstitutor.EMPTY));
    }

    for (Iterator<Pair<PsiMethod, PsiSubstitutor>> iterator = impl.iterator(); iterator.hasNext();) {
      Pair<PsiMethod, PsiSubstitutor> pair = iterator.next();
      if (hasTraitImplementation(pair.first)) {
        iterator.remove();
        over.add(pair);
      }
    }

    final List<Pair<PsiMethod, PsiSubstitutor>> result = toImplement ? impl : over;
    for (int i = 0, resultSize = result.size(); i < resultSize; i++) {
      Pair<PsiMethod, PsiSubstitutor> pair = result.get(i);
      result.set(i, Pair.create(pair.first, resolveResult.getSubstitutor().putAll(pair.second)));
    }
    return result;
  }

  private static ArrayList<Pair<PsiMethod, PsiSubstitutor>> getMethodsToOverrideImplement(PsiClass psiClass, final boolean toImplement) {
    final ArrayList<Pair<PsiMethod, PsiSubstitutor>> result = new ArrayList<>();
    for (CandidateInfo info : OverrideImplementExploreUtil.getMethodsToOverrideImplement(psiClass, toImplement)) {
      result.add(Pair.create((PsiMethod) info.getElement(), info.getSubstitutor()));
    }
    return result;
  }

  private static boolean hasTraitImplementation(PsiMethod method) {
    return method.getModifierList().hasAnnotation("org.mbte.groovypp.runtime.HasDefaultImplementation");
  }
}


text:
var Test = function() {
  this.someVar = 123;
};

Test.prototype.someMethod = function() {
  console.log(this.someVar);
}

Test.prototype.someOther = function() {
  console.log("other");
  this.someMethod();
  this.__special();
}

Test.prototype.__special = function() {
  console.log("special");
}

var oTest = new Test();
oTest.someOther();