text:
/**
 * Tree 工具集
 * @author Brian Li
 * @email lbxxlht@163.com
 * @version 0.0.2.1
 */
define(function (require) {

    return {
        /**
         * 获取Tree节点数据源
         * @interface getLeafItem
         * @param {Array.<TreeItemObject>} datasource Tree数据源
         * @param {Array.<Number>} indexs 节点序列,从树的第一层开始,依照序列从children中检出
         * @return {TreeItemObject} 节点数据源
         */
        getLeafItem: function (datasource, indexs) {
            var result = {children: datasource};
            for (var i = 0; i < indexs.length; i++) {
                var index = parseInt(indexs[i], 10);
                if (isNaN(index)) continue;
                if (result.children instanceof Array && result.children.length > index) {
                    result = result.children[index];
                }
            }
            return result;
        },
        /**
         * 获取Tree节点的选择状态
         * @interface getNodeSelectInfo
         * @param {TreeItemObject} item 节点数据源
         * @param {Object} selectedHash Tree选择状态hash,以item.value为key
         * @param {String} index 节点序列
         * @param {Object} loadCache 树遍历临时hash,由于树遍历时出现相同计算,所以要使用cache以提高效率
         * @return {TreeNodeSelectState} 节点选择状态
         */
        /**
         * @structure TreeNodeSelectState
         * @param {Number} total 子树所有节点个数
         * @param {Number} selected 子树所有选中节点个数
         */
        getNodeSelectInfo: function (item, selectedHash, index, loadCache) {
            loadCache = loadCache || {};
            index = index || '';
            // 已缓存
            if (loadCache.hasOwnProperty(index)) {
                return loadCache[index];
            }
            var result = {
                total: 0,
                selected: 0
            };
            // 叶子
            if (!(item.children instanceof Array)) {
                result.total += 1;
                result.selected = selectedHash[item.value] === true ? 1 : 0;
                loadCache[index] = JSON.parse(JSON.stringify(result));
                return result;
            }
            // 树
            for (var i = 0; i < item.children.length; i++) {
                var child = item.children[i];
                var childIndex = index + ',' + i;
                if (!loadCache.hasOwnProperty(childIndex)) {
                    this.getNodeSelectInfo(child, selectedHash, childIndex, loadCache);
                }
                var cache = loadCache[childIndex];
                result.total += cache.total;
                result.selected += cache.selected;
            }
            loadCache[index] = JSON.parse(JSON.stringify(result));
            return result;
        },
        /**
         * 获取Tree叶子个数
         * @interface getLeafCount
         * @param {Array} datasource 树数据源
         * @return {Number} 叶子节点个数
         */
        getLeafCount: function (datasource) {
            var result = 0;
            getCount(datasource);
            function getCount(arr) {
                for (var i = 0; i < arr.length; i++) {
                    if (!arr[i].children || !arr[i].children.length) {
                        result++;
                        continue;
                    }
                    getCount(arr[i].children);
                }
            }
            return result;
        },
        /**
         * 修改异步数据源叶子选中状态
         * @interface targetAsyncLeaf
         * @param {Object} selected 选中状态hash
         * @param {Object} selectorEngine 选择器引擎
         * @param {Array} datasource tree新的数据源
         * @return {Boolean} selected是否被修改
         */
        targetAsyncLeaf: function (selected, selectorEngine, datasource) {
            var result = false;
            doing(datasource);
            return result;
            function doing(arr) {
                if (!(arr instanceof Array) || !arr.length) return;
                for (var i = 0; i < arr.length; i++) {
                    var item = arr[i];
                    // 叶子节点
                    if (!(item.children instanceof Array)) {
                        // 空的children属性被删掉了
                        if (selected[item.value] === 1) {
                            selected[item.value] = true;
                        }
                        continue;
                    }
                    // 无孩子节点
                    if (!item.children.length) continue;
                    // 有孩子节点,但不是新加载的
                    if (selected[item.value] !== 1) {
                        doing(item.children);
                        continue;
                    }
                    delete selected[item.value];
                    selectorEngine.select(selected, item);
                    result = true;
                }
            }
        },
        dualTreeSelectorEngine: {
            /**
             * 指针方法,选中子树
             * @interface dualTreeSelectorEngine.select
             * @param {Object} selected Tree的选中hash
             * @param {TreeItemObject} item 节点数据源
             * @example
             * 此处逻辑:
             * (1)如果当前节点是叶子节点,标记为true
             * (2)如果当前节点不是叶子节点,在其树下所有叶子标记为true
             * (3)如果当点节点有children属性,但children长度为0,则将此节点标记为1
             */
            select: function (selected, item) {

                if (!(item.children instanceof Array)) {
                    selected[item.value] = true;
                    return;
                }

                if (item.children.length === 0) {
                    selected[item.value] = 1;
                    return;
                }

                targetChildren(item.children);

                function targetChildren(arr) {
                    if (!(arr instanceof Array)) return;
                    for (var i = 0; i < arr.length; i++) {
                        var child = arr[i];
                        if (child.children instanceof Array) {
                            targetChildren(child.children);
                            continue;
                        }
                        selected[child.value] = true;
                    }
                }
            },

            /**
             * 指针方法,删除子树
             * @interface dualTreeSelectorEngine.unselect
             * @param {Object} selected Tree的选中hash
             * @param {TreeItemObject} item 节点数据源
             * @example
             * 此处逻辑
             * (1)如果是叶子,则删除
             * (2)如果不是叶子,则删除该子树上的所有叶子
             */
            unselect: function (selected, item) {

                if (!(item.children instanceof Array)) {
                    delete selected[item.value];
                    return;
                }

                delChildren(item.children);

                function delChildren(arr) {
                    if (!(arr instanceof Array)) return;
                    for (var i = 0; i < arr.length; i++) {
                        var child = arr[i];
                        if (child.children instanceof Array) {
                            delChildren(child.children);
                            continue;
                        }
                        delete selected[child.value];
                    }
                }
            }
        }
    };
});


text:
SET NAMES 'utf8';
CREATE TABLE chat_bookmark_user_message (
    id int(20) NOT NULL AUTO_INCREMENT,
    chat_user_id int(11) NOT NULL,
    chat_room_id int(11) NOT NULL,
    chat_message_id int(11) NOT NULL,
    PRIMARY KEY (id),
   CONSTRAINT FK_bookmark_user FOREIGN KEY (chat_user_id) REFERENCES chat_user(id),
   CONSTRAINT FK_bookmark_room  FOREIGN KEY (chat_room_id) REFERENCES chat_room(id),
   CONSTRAINT FK_bookmark_message  FOREIGN KEY (chat_message_id) REFERENCES chat_user_message(id),
   CONSTRAINT UC_bookmark UNIQUE (chat_user_id,chat_message_id)
);

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
	* Copyright 2011 Thomas Bocek
	*
	* Licensed under the Apache License, Version 2.0 (the "License"); you may not
	* use this file except in compliance with the License. You may obtain a copy of
	* the License at
	*
	* http://www.apache.org/licenses/LICENSE-2.0
	*
	* Unless required by applicable law or agreed to in writing, software
	* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
	* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
	* License for the specific language governing permissions and limitations under
	* the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>net.tomp2p</groupId>
		<artifactId>tomp2p-parent</artifactId>
		<version>5.0-Beta9.1-SNAPSHOT</version>
	</parent>

	<artifactId>tomp2p-social</artifactId>
	<name>TomP2P social</name>
	<packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0</url>
		</license>
	</licenses>

	<dependencies>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-transport</artifactId>
		</dependency>

		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>tomp2p-dht</artifactId>
			<version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.mapdb</groupId>
			<artifactId>mapdb</artifactId>
			<version>1.0.6</version>
		</dependency>

		<!-- For testing -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
</project>


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

#if WINDOWS_BUILD

using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class ThePdfCoder
    {
        [Fact]
        public void Test_Format()
        {
            using (var image = new MagickImage(Files.Coders.CartoonNetworkStudiosLogoAI))
            {
                Assert.Equal(765, image.Width);
                Assert.Equal(361, image.Height);
                Assert.Equal(MagickFormat.Ai, image.Format);
            }
        }
    }
}

#endif


text:
using infrastructure.libs.validators;
using System;

namespace infrastructure.user.models
{
    public class UserReset
    {
        private readonly int _userid;
        private readonly string _email;
        private readonly string _passwordToken;
        private readonly DateTime _passwordTokenExpiryDate;

        public UserReset(int userid, string email, string passwordToken, DateTime passwordTokenExpiryDate)
        {
            CustomValidators.IntNotNegative(userid, "userid is invalid.");
            CustomValidators.StringNotNullorEmpty(email, "email is invalid.");
            CustomValidators.StringNotNullorEmpty(passwordToken, "passwordToken is invalid.");
            CustomValidators.NotNull(passwordTokenExpiryDate, "passwordTokenExpiryDate is invalid.");

            _userid = userid;
            _email = email;
            _passwordToken = passwordToken;
            _passwordTokenExpiryDate = passwordTokenExpiryDate;
        }

        public int UserId => _userid;
        public string EmailTo => _email;
        public DateTime PasswordTokenExpiryDate => _passwordTokenExpiryDate;
        public string PasswordToken => _passwordToken;
    }
}


text:
//
//  ModalPresentationViewController.h
//  MultiCustomUIComponent
//
//  Created by fang wang on 17/1/13.
//  Copyright © 2017年 wdy. All rights reserved.
//

#import <UIKit/UIKit.h>

@class ModalPresentationViewController;

typedef enum : NSUInteger {
    ModalPresentationAnimationStyleFade,    // 渐现渐隐,默认
    ModalPresentationAnimationStylePopup,   // 从中心点弹出
    ModalPresentationAnimationStyleSlide    // 从下往上升起
} ModalPresentationAnimationStyle;

@protocol ModalPresentationContentViewProtocol <NSObject>

@optional

/**
 *  当浮层使用modalController提供的默认布局时,则可通过这个方法告诉modalController当前浮层期望的大小
 *  @param  controller  当前的modalController
 *  @param  limitSize   浮层最大的宽高,由当前modalController的大小及`contentViewMargins`、`maximumContentViewWidth`决定
 *  @return 返回浮层在`limitSize`限定内的大小,如果业务自身不需要限制宽度/高度,则为width/height返回CGFLOAT_MAX即可
 */
- (CGSize)preferredContentSizeInModalPresentationVC:(ModalPresentationViewController *)controller
                                          limitSize:(CGSize)limitSize;

@end

@protocol ModalPresentationViewControllerDelegate <NSObject>
@optional

/**
 *  是否应该隐藏浮层,会在调用`hideWithAnimated:completion:`时,以及点击背景遮罩时被调用。默认为YES。
 *  @param  controller  当前的modalController
 *  @return 是否允许隐藏,YES表示允许隐藏,NO表示不允许隐藏
 */
- (BOOL)shouldHideModalPresentationViewController:(ModalPresentationViewController *)controller;

/**
 *  modalController隐藏后的回调函数,不管是直接调用`hideWithAnimated:completion:`,还是通过点击遮罩触发的隐藏,都会调用这个方法。
 *  如果你想区分这两种方式的隐藏回调,请直接使用hideWithAnimated方法的completion参数,以及`didHideByDimmingViewTappedBlock`属性。
 *  @param  controller  当前的modalController
 */
- (void)didHideModalPresentationViewController:(ModalPresentationViewController *)controller;
- (void)requestHideAllModalPresentationViewController;
@end

/**
 *  一个提供通用的弹出浮层功能的控件,可以将任意`UIView`或`UIViewController`以浮层的形式显示出来并自动布局。
 *
 *  支持 3 种方式显示浮层:
 *
 *  1. **推荐** 新起一个 `UIWindow` 盖在当前界面上,将 `QMUIModalPresentationViewController` 以 `rootViewController` 的形式显示出来,可通过 `supportedOrientationMask` 支持横竖屏,不支持在浮层不消失的情况下做界面切换(因为 window 会把背后的 controller 盖住,看不到界面切换)
 *  @code
 *  [modalPresentationViewController showWithAnimated:YES completion:nil];
 *  @endcode
 *
 *  2. 使用系统接口来显示,支持界面切换,**注意** 使用这种方法必定只能以动画的形式来显示浮层,无法以无动画的形式来显示,并且 `animated` 参数必须为 `NO`。可通过 `supportedOrientationMask` 支持横竖屏。
 *  @code
 *  [self presentViewController:modalPresentationViewController animated:NO completion:nil];
 *  @endcode
 *
 *  3. 将浮层作为一个 subview 添加到 `superview` 上,从而能够实现在浮层不消失的情况下进行界面切换,但需要 `superview` 自行管理浮层的大小和横竖屏旋转,而且 `QMUIModalPresentationViewController` 不能用局部变量来保存,会在显示后被释放,需要自行 retain。横竖屏跟随当前界面的设置。
 *  @code
 *  self.modalPresentationViewController.view.frame = CGRectMake(50, 50, 100, 100);
 *  [self.view addSubview:self.modalPresentationViewController.view];
 *  @endcode
 *
 *  默认的布局会将浮层居中显示,浮层的大小可通过接口控制:
 *  1. 如果是用 `contentViewController`,则可通过 `preferredContentSizeInModalPresentationViewController:limitSize:` 来设置
 *  2. 如果使用 `contentView`,或者使用 `contentViewController` 但没实现 `preferredContentSizeInModalPresentationViewController:limitSize:`,则调用`contentView`的`sizeThatFits:`方法获取大小。
 *
 *  通过`layoutBlock`、`showingAnimation`、`hidingAnimation`可设置自定义的布局、打开及隐藏的动画,并允许你适配键盘升起时的场景。
 *
 *  默认提供背景遮罩`dimmingView`,你也可以使用自己的遮罩 view。
 *
 *  默认提供多种显示动画,可通过 `animationStyle` 来设置。
 *
 *  @warning 如果使用者retain了modalPresentationViewController,注意应该在`hideWithAnimated:completion:`里release
 *
 *  @see QMUIAlertController
 *  @see QMUIDialogViewController
 *  @see QMUIMoreOperationController
 */
@interface ModalPresentationViewController : UIViewController

@property(nonatomic, weak) id <ModalPresentationViewControllerDelegate> delegate;

/**
 *  要被弹出的浮层
 *  @warning 当设置了`contentView`时,不要再设置`contentViewController`
 */
@property(nonatomic, strong) UIView *contentView;

/**
 *  背景遮罩,默认为一个普通的`UIView`,背景色为`UIColorMask`,可设置为自己的view,注意`dimmingView`的大小将会盖满整个控件。
 *
 *  `QMUIModalPresentationViewController`会自动给自定义的`dimmingView`添加手势以实现点击遮罩隐藏浮层。
 */
@property(nonatomic, strong) UIView *dimmingView;
/**
 *  要被弹出的浮层,适用于浮层以UIViewController的形式来管理的情况。
 *  @warning 当设置了`contentViewController`时,`contentViewController.view`会被当成`contentView`使用,因此不要再自行设置`contentView`
 *  @warning 注意`contentViewController`是强引用,容易导致循环引用,使用时请注意
 */
@property(nonatomic, strong) UIViewController<ModalPresentationContentViewProtocol> *contentViewController;
/**
 *  设置`contentView`布局时与外容器的间距,默认为(20, 20, 20, 20)
 *  @warning 当设置了`layoutBlock`属性时,此属性不生效
 */
@property(nonatomic, assign) UIEdgeInsets contentViewMargins UI_APPEARANCE_SELECTOR;

/**
 *  限制`contentView`布局时的最大宽度,默认为iPhone 6竖屏下的屏幕宽度减去`contentViewMargins`在水平方向的值,
    也即浮层在iPhone 6 Plus或iPad上的宽度以iPhone 6上的宽度为准。
 *  @warning 当设置了`layoutBlock`属性时,此属性不生效
 */
@property(nonatomic, assign) CGFloat maximumContentViewWidth UI_APPEARANCE_SELECTOR;

/**
 *  由于点击遮罩导致浮层被隐藏时的回调(区分于`hideWithAnimated:completion:`里的completion,这里是特地用于点击遮罩的情况)
 */
@property(nonatomic, copy) void (^didHideByDimmingViewTappedBlock)();

/**
 *  控制当前是否以模态的形式存在。如果以模态的形式存在,则点击空白区域不会隐藏浮层。
 *
 *  默认为NO,也即点击空白区域将会自动隐藏浮层。
 */
@property(nonatomic, assign, getter=isModal) BOOL modal;

/**
 *  标志当前浮层的显示/隐藏状态,默认为NO。
 */
@property(nonatomic, assign, readonly, getter=isVisible) BOOL visible;

/**
 *  修改当前界面要支持的横竖屏方向,默认为 SupportedOrientationMask。
 */
@property(nonatomic, assign) UIInterfaceOrientationMask supportedOrientationMask;

/**
 *  设置要使用的显示/隐藏动画的类型,默认为`ModalPresentationAnimationStyleFade`。
 *  @warning 当使用了`showingAnimation`和`hidingAnimation`时,该属性无效
 */
@property(nonatomic, assign) ModalPresentationAnimationStyle animationStyle UI_APPEARANCE_SELECTOR;

/**
 *  管理自定义的浮层布局,将会在浮层显示前、控件的容器大小发生变化时(例如横竖屏、来电状态栏)被调用
 *  @arg  containerBounds         浮层所在的父容器的大小,也即`self.view.bounds`
 *  @arg  keyboardHeight          键盘在当前界面里的高度,若无键盘,则为0
 *  @arg  contentViewDefaultFrame 不使用自定义布局的情况下的默认布局,会受`contentViewMargins`、`maximumContentViewWidth`、`contentView sizeThatFits:`的影响
 *
 *  @see contentViewMargins
 *  @see maximumContentViewWidth
 */
@property(nonatomic, copy) void (^layoutBlock)(CGRect containerBounds, CGFloat keyboardHeight, CGRect contentViewDefaultFrame);

/**
 *  管理自定义的显示动画,需要管理的对象包括`contentView`和`dimmingView`,在`showingAnimation`被调用前,`contentView`已被添加到界面上。若使用了`layoutBlock`,则会先调用`layoutBlock`,再调用`showingAnimation`。在动画结束后,必须调用参数里的`completion` block。
 *  @arg  dimmingView         背景遮罩的View,请自行设置显示遮罩的动画
 *  @arg  containerBounds     浮层所在的父容器的大小,也即`self.view.bounds`
 *  @arg  keyboardHeight      键盘在当前界面里的高度,若无键盘,则为0
 *  @arg  contentViewFrame    动画执行完后`contentView`的最终frame,若使用了`layoutBlock`,则也即`layoutBlock`计算完后的frame
 *  @arg  completion          动画结束后给到modalController的回调,modalController会在这个回调里做一些状态设置,务必调用。
 */
@property(nonatomic, copy) void (^showingAnimation)(UIView *dimmingView, CGRect containerBounds, CGFloat keyboardHeight, CGRect contentViewFrame, void(^completion)(BOOL finished));

/**
 *  管理自定义的隐藏动画,需要管理的对象包括`contentView`和`dimmingView`,在动画结束后,必须调用参数里的`completion` block。
 *  @arg  dimmingView         背景遮罩的View,请自行设置隐藏遮罩的动画
 *  @arg  containerBounds     浮层所在的父容器的大小,也即`self.view.bounds`
 *  @arg  keyboardHeight      键盘在当前界面里的高度,若无键盘,则为0
 *  @arg  completion          动画结束后给到modalController的回调,modalController会在这个回调里做一些清理工作,务必调用
 */
@property(nonatomic, copy) void (^hidingAnimation)(UIView *dimmingView, CGRect containerBounds, CGFloat keyboardHeight, void(^completion)(BOOL finished));

/**
 *  将浮层以 UIWindow 的方式显示出来
 *  @param animated    是否以动画的形式显示
 *  @param completion  显示动画结束后的回调
 */
- (void)showWithAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion;

/**
 *  将浮层隐藏掉
 *  @param animated    是否以动画的形式隐藏
 *  @param completion  隐藏动画结束后的回调
 *  @warning 这里的`completion`只会在你显式调用`hideWithAnimated:completion:`方法来隐藏浮层时会被调用,如果你通过点击`dimmingView`来触发`hideWithAnimated:completion:`,则completion是不会被调用的,那种情况下如果你要在浮层隐藏后做一些事情,请使用`delegate`提供的`didHideModalPresentationViewController:`方法。
 */
- (void)hideWithAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion;

/**
 *  将浮层以 addSubview 的方式显示出来
 *
 *  @param view         要显示到哪个 view 上
 *  @param animated     是否以动画的形式显示
 *  @param completion   显示动画结束后的回调
 */
- (void)showInView:(UIView *)view animated:(BOOL)animated completion:(void (^)(BOOL finished))completion;

/**
 *  将某个 view 上显示的浮层隐藏掉
 *  @param view         要隐藏哪个 view 上的浮层
 *  @param animated     是否以动画的形式隐藏
 *  @param completion   隐藏动画结束后的回调
 *  @warning 这里的`completion`只会在你显式调用`hideInView:animated:completion:`方法来隐藏浮层时会被调用,如果你通过点击`dimmingView`来触发`hideInView:animated:completion:`,则completion是不会被调用的,那种情况下如果你要在浮层隐藏后做一些事情,请使用`delegate`提供的`didHideModalPresentationViewController:`方法。
 */
- (void)hideInView:(UIView *)view animated:(BOOL)animated completion:(void (^)(BOOL finished))completion;
@end

@interface ModalPresentationViewController (Manager)

/**
 *  判断当前App里是否有modalViewController正在显示(存在modalViewController但不可见的时候,也视为不存在)
 *  @return 只要存在正在显示的浮层,则返回YES,否则返回NO
 */
+ (BOOL)isAnyModalPresentationViewControllerVisible;

/**
 *  把所有正在显示的并且允许被隐藏的modalViewController都隐藏掉
 *  @return 只要遇到一个正在显示的并且不能被隐藏的浮层,就会返回NO,否则都返回YES,表示成功隐藏掉所有可视浮层
 *  @see    shouldHideModalPresentationViewController:
 */
+ (BOOL)hideAllVisibleModalPresentationViewControllerIfCan;
@end

@interface ModalPresentationViewController (UIAppearance)

+ (instancetype)appearance;

@end

@interface UIViewController (ModalPresentationViewController)

/**
 *  获取弹出当前vieController的QMUIModalPresentationViewController
 */
@property(nonatomic, weak, readonly) ModalPresentationViewController *modalPresentedViewController;
@end

@interface UIViewController (Helper)
/**
 *  获取当前controller里的最高层可见viewController(可见的意思是还会判断self.view.window是否存在)
 *
 *  @see 如果要获取当前App里的可见viewController,请使用<i>[Helper visibleViewController]</i>
 *
 *  @return 当前controller里的最高层可见viewController
 */
- (UIViewController *)visibleViewControllerIfExist;
@end

@interface ModalPresentationWindow : UIWindow

@end

/**********************************************************************************************************/
//  使用介绍
/*
// 自定义显示 和 隐藏动画
- (void)handleLayoutBlockAndAnimation {
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];
    contentView.backgroundColor = [UIColor blackColor];
    contentView.layer.cornerRadius = 6;

    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 0;
    label.text = @"hello world!";
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(0, 0, contentView.frame.size.width, 50);
    label.center = CGPointMake(contentView.center.x, contentView.center.y - 20);
    [contentView addSubview:label];

    UITextField* textField = [[UITextField alloc] init];
    textField.frame = CGRectMake(0, 0, contentView.frame.size.width, 30);
    textField.center = CGPointMake(contentView.center.x, contentView.center.y + 40);
    [contentView addSubview:textField];

    ModalPresentationViewController *modalViewController = [[ModalPresentationViewController alloc] init];
    modalViewController.contentView = contentView;
    //    modalViewController.layoutBlock = ^(CGRect containerBounds, CGFloat keyboardHeight, CGRect contentViewDefaultFrame) {
    //        CGFloat contentViewX = (containerBounds.origin.x - contentView.frame.origin.x)*0.5;
    //        CGFloat contentViewY = (containerBounds.origin.y - contentView.frame.origin.y)*0.5;
    //        contentView.frame = CGRectMake(100,
    //                                       100,
    //                                       (CGRectGetWidth(containerBounds)-CGRectGetWidth(contentView.frame))*0.5,
    //                                       CGRectGetHeight(containerBounds) - 20 - CGRectGetHeight(contentView.frame));
    //    };

    modalViewController.showingAnimation = ^(UIView *dimmingView, CGRect containerBounds, CGFloat keyboardHeight, CGRect contentViewFrame, void(^completion)(BOOL finished)) {
        //        CGFloat contentViewX = (containerBounds.origin.x - contentView.frame.origin.x)*0.5;
        //        CGFloat contentViewY = (containerBounds.origin.y - contentView.frame.origin.y)*0.5;
        //        CGFloat contentViewW = contentView.frame.size.width;
        //        CGFloat contentViewH = contentView.frame.size.height;
        //        contentView.frame = CGRectMake(100, 100, contentViewW, contentViewH);
        dimmingView.alpha = 0;
        [UIView animateWithDuration:.3 delay:0.0 options:QMUIViewAnimationOptionsCurveOut animations:^{
            dimmingView.alpha = 1;
            contentView.frame = contentViewFrame;
        } completion:^(BOOL finished) {
            // 记住一定要在适当的时机调用completion()
            if (completion) {
                completion(finished);
            }
        }];
    };

    modalViewController.hidingAnimation = ^(UIView *dimmingView, CGRect containerBounds, CGFloat keyboardHeight, void(^completion)(BOOL finished)) {
        [UIView animateWithDuration:.3 delay:0.0 options:QMUIViewAnimationOptionsCurveOut animations:^{
            dimmingView.alpha = 0.0;
        } completion:^(BOOL finished) {
            // 记住一定要在适当的时机调用completion()
            if (completion) {
                completion(finished);
            }
        }];
    };
    [modalViewController showWithAnimated:YES completion:nil];
}

- (void)customDimmingView{
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];
    contentView.backgroundColor = [UIColor whiteColor];
    contentView.layer.cornerRadius = 6;

    UIImageView* imageV = [[UIImageView alloc] init];
    imageV.image = [UIImage imageNamed:@"name01.jpeg"];

    ModalPresentationViewController *modalViewController = [[ModalPresentationViewController alloc] init];
    modalViewController.dimmingView = imageV;
    modalViewController.contentView = contentView;
    [modalViewController showWithAnimated:YES completion:nil];
}

// 内容是控制器的时候
- (void)testContentViewController{

    ModalContentViewController* vc = [[ModalContentViewController alloc] init];
    ModalPresentationViewController *modalViewController = [[ModalPresentationViewController alloc] init];
    modalViewController.contentViewController = vc;
    modalViewController.maximumContentViewWidth = CGFLOAT_MAX;
    [modalViewController showWithAnimated:YES completion:nil];
}

// 弹出动画,文本框键盘处理
- (void)testModalViewController{

    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];
    contentView.backgroundColor = [UIColor whiteColor];
    contentView.layer.cornerRadius = 6;

    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 0;
    label.text = @"hello world!";
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(0, 0, contentView.frame.size.width, 50);
    label.center = CGPointMake(contentView.center.x, contentView.center.y - 20);
    [contentView addSubview:label];

    UITextField* textField = [[UITextField alloc] init];
    textField.frame = CGRectMake(0, 0, contentView.frame.size.width, 30);
    textField.center = CGPointMake(contentView.center.x, contentView.center.y + 40);
    [contentView addSubview:textField];

    // 以Window方式弹出
    ModalPresentationViewController *modalViewController = [[ModalPresentationViewController alloc] init];
    modalViewController.contentView = contentView;
    //    modalViewController.maximumContentViewWidth = CGFLOAT_MAX;
    [modalViewController showWithAnimated:YES completion:nil];
    //    [self presentViewController:modalViewController animated:NO completion:nil];

    //    if (self.myModalViewController) {
    //        [self.myModalViewController hideInView:self.view animated:YES completion:nil];
    //    }
    //
    //    self.myModalViewController = [[ModalPresentationViewController alloc] init];
    //    self.myModalViewController.contentView = contentView;
    //    self.myModalViewController.animationStyle = ModalPresentationAnimationStylePopup;
    //    self.myModalViewController.view.frame = self.view.bounds;
    //    [self.myModalViewController showInView:self.view animated:YES completion:nil];
}

*/


text:
#ifndef PCL_KDTREE_KDTREE_H_
#define PCL_KDTREE_KDTREE_H_

#include <limits.h>
#include <pcl/pcl_macros.h>
#include <pcl/point_cloud.h>
#include <pcl/point_representation.h>
#include <pcl/common/io.h>
#include <pcl/common/copy_point.h>

namespace pcl
{
  /** \brief KdTree represents the base spatial locator class for kd-tree implementations.
    * \author Radu B Rusu, Bastian Steder, Michael Dixon
    * \ingroup kdtree
    */
  template <typename PointT>
  class KdTree
  {
    public:
      typedef boost::shared_ptr <std::vector<int> > IndicesPtr;
      typedef boost::shared_ptr <const std::vector<int> > IndicesConstPtr;

      typedef pcl::PointCloud<PointT> PointCloud;
      typedef boost::shared_ptr<PointCloud> PointCloudPtr;
      typedef boost::shared_ptr<const PointCloud> PointCloudConstPtr;

      typedef pcl::PointRepresentation<PointT> PointRepresentation;
      //typedef boost::shared_ptr<PointRepresentation> PointRepresentationPtr;
      typedef boost::shared_ptr<const PointRepresentation> PointRepresentationConstPtr;

      // Boost shared pointers
      typedef boost::shared_ptr<KdTree<PointT> > Ptr;
      typedef boost::shared_ptr<const KdTree<PointT> > ConstPtr;

      /** \brief Empty constructor for KdTree. Sets some internal values to their defaults.
        * \param[in] sorted set to true if the application that the tree will be used for requires sorted nearest neighbor indices (default). False otherwise.
        */
      KdTree (bool sorted = true) : input_(), indices_(),
                                    epsilon_(0.0f), min_pts_(1), sorted_(sorted),
                                    point_representation_ (new DefaultPointRepresentation<PointT>)
      {
      };

      /** \brief Provide a pointer to the input dataset.
        * \param[in] cloud the const boost shared pointer to a PointCloud message
        * \param[in] indices the point indices subset that is to be used from \a cloud - if NULL the whole cloud is used
        */
      virtual void
      setInputCloud (const PointCloudConstPtr &cloud, const IndicesConstPtr &indices = IndicesConstPtr ())
      {
        input_   = cloud;
        indices_ = indices;
      }

      /** \brief Get a pointer to the vector of indices used. */
      inline IndicesConstPtr
      getIndices () const
      {
        return (indices_);
      }

      /** \brief Get a pointer to the input point cloud dataset. */
      inline PointCloudConstPtr
      getInputCloud () const
      {
        return (input_);
      }

      /** \brief Provide a pointer to the point representation to use to convert points into k-D vectors.
        * \param[in] point_representation the const boost shared pointer to a PointRepresentation
        */
      inline void
      setPointRepresentation (const PointRepresentationConstPtr &point_representation)
      {
        point_representation_ = point_representation;
        if (!input_) return;
        setInputCloud (input_, indices_);  // Makes sense in derived classes to reinitialize the tree
      }

      /** \brief Get a pointer to the point representation used when converting points into k-D vectors. */
      inline PointRepresentationConstPtr
      getPointRepresentation () const
      {
        return (point_representation_);
      }

      /** \brief Destructor for KdTree. Deletes all allocated data arrays and destroys the kd-tree structures. */
      virtual ~KdTree () {};

      /** \brief Search for k-nearest neighbors for the given query point.
        * \param[in] p_q the given query point
        * \param[in] k the number of neighbors to search for
        * \param[out] k_indices the resultant indices of the neighboring points (must be resized to \a k a priori!)
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points (must be resized to \a k
        * a priori!)
        * \return number of neighbors found
        */
      virtual int
      nearestKSearch (const PointT &p_q, int k,
                      std::vector<int> &k_indices, std::vector<float> &k_sqr_distances) const = 0;

      /** \brief Search for k-nearest neighbors for the given query point.
        *
        * \attention This method does not do any bounds checking for the input index
        * (i.e., index >= cloud.points.size () || index < 0), and assumes valid (i.e., finite) data.
        *
        * \param[in] cloud the point cloud data
        * \param[in] index a \a valid index in \a cloud representing a \a valid (i.e., finite) query point
        * \param[in] k the number of neighbors to search for
        * \param[out] k_indices the resultant indices of the neighboring points (must be resized to \a k a priori!)
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points (must be resized to \a k
        * a priori!)
        *
        * \return number of neighbors found
        *
        * \exception asserts in debug mode if the index is not between 0 and the maximum number of points
        */
      virtual int
      nearestKSearch (const PointCloud &cloud, int index, int k,
                      std::vector<int> &k_indices, std::vector<float> &k_sqr_distances) const
      {
        assert (index >= 0 && index < static_cast<int> (cloud.points.size ()) && "Out-of-bounds error in nearestKSearch!");
        return (nearestKSearch (cloud.points[index], k, k_indices, k_sqr_distances));
      }

      /** \brief Search for k-nearest neighbors for the given query point.
        * This method accepts a different template parameter for the point type.
        * \param[in] point the given query point
        * \param[in] k the number of neighbors to search for
        * \param[out] k_indices the resultant indices of the neighboring points (must be resized to \a k a priori!)
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points (must be resized to \a k
        * a priori!)
        * \return number of neighbors found
        */
      template <typename PointTDiff> inline int
      nearestKSearchT (const PointTDiff &point, int k,
                       std::vector<int> &k_indices, std::vector<float> &k_sqr_distances) const
      {
        PointT p;
        copyPoint (point, p);
        return (nearestKSearch (p, k, k_indices, k_sqr_distances));
      }

      /** \brief Search for k-nearest neighbors for the given query point (zero-copy).
        *
        * \attention This method does not do any bounds checking for the input index
        * (i.e., index >= cloud.points.size () || index < 0), and assumes valid (i.e., finite) data.
        *
        * \param[in] index a \a valid index representing a \a valid query point in the dataset given
        * by \a setInputCloud. If indices were given in setInputCloud, index will be the position in
        * the indices vector.
        *
        * \param[in] k the number of neighbors to search for
        * \param[out] k_indices the resultant indices of the neighboring points (must be resized to \a k a priori!)
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points (must be resized to \a k
        * a priori!)
        * \return number of neighbors found
        *
        * \exception asserts in debug mode if the index is not between 0 and the maximum number of points
        */
      virtual int
      nearestKSearch (int index, int k,
                      std::vector<int> &k_indices, std::vector<float> &k_sqr_distances) const
      {
        if (indices_ == NULL)
        {
          assert (index >= 0 && index < static_cast<int> (input_->points.size ()) && "Out-of-bounds error in nearestKSearch!");
          return (nearestKSearch (input_->points[index], k, k_indices, k_sqr_distances));
        }
        else
        {
          assert (index >= 0 && index < static_cast<int> (indices_->size ()) && "Out-of-bounds error in nearestKSearch!");
          return (nearestKSearch (input_->points[(*indices_)[index]], k, k_indices, k_sqr_distances));
        }
      }

      /** \brief Search for all the nearest neighbors of the query point in a given radius.
        * \param[in] p_q the given query point
        * \param[in] radius the radius of the sphere bounding all of p_q's neighbors
        * \param[out] k_indices the resultant indices of the neighboring points
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points
        * \param[in] max_nn if given, bounds the maximum returned neighbors to this value. If \a max_nn is set to
        * 0 or to a number higher than the number of points in the input cloud, all neighbors in \a radius will be
        * returned.
        * \return number of neighbors found in radius
        */
      virtual int
      radiusSearch (const PointT &p_q, double radius, std::vector<int> &k_indices,
                    std::vector<float> &k_sqr_distances, unsigned int max_nn = 0) const = 0;

      /** \brief Search for all the nearest neighbors of the query point in a given radius.
        *
        * \attention This method does not do any bounds checking for the input index
        * (i.e., index >= cloud.points.size () || index < 0), and assumes valid (i.e., finite) data.
        *
        * \param[in] cloud the point cloud data
        * \param[in] index a \a valid index in \a cloud representing a \a valid (i.e., finite) query point
        * \param[in] radius the radius of the sphere bounding all of p_q's neighbors
        * \param[out] k_indices the resultant indices of the neighboring points
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points
        * \param[in] max_nn if given, bounds the maximum returned neighbors to this value. If \a max_nn is set to
        * 0 or to a number higher than the number of points in the input cloud, all neighbors in \a radius will be
        * returned.
        * \return number of neighbors found in radius
        *
        * \exception asserts in debug mode if the index is not between 0 and the maximum number of points
        */
      virtual int
      radiusSearch (const PointCloud &cloud, int index, double radius,
                    std::vector<int> &k_indices, std::vector<float> &k_sqr_distances,
                    unsigned int max_nn = 0) const
      {
        assert (index >= 0 && index < static_cast<int> (cloud.points.size ()) && "Out-of-bounds error in radiusSearch!");
        return (radiusSearch(cloud.points[index], radius, k_indices, k_sqr_distances, max_nn));
      }

      /** \brief Search for all the nearest neighbors of the query point in a given radius.
        * \param[in] point the given query point
        * \param[in] radius the radius of the sphere bounding all of p_q's neighbors
        * \param[out] k_indices the resultant indices of the neighboring points
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points
        * \param[in] max_nn if given, bounds the maximum returned neighbors to this value. If \a max_nn is set to
        * 0 or to a number higher than the number of points in the input cloud, all neighbors in \a radius will be
        * returned.
        * \return number of neighbors found in radius
        */
      template <typename PointTDiff> inline int
      radiusSearchT (const PointTDiff &point, double radius, std::vector<int> &k_indices,
                     std::vector<float> &k_sqr_distances, unsigned int max_nn = 0) const
      {
        PointT p;
        copyPoint (point, p);
        return (radiusSearch (p, radius, k_indices, k_sqr_distances, max_nn));
      }

      /** \brief Search for all the nearest neighbors of the query point in a given radius (zero-copy).
        *
        * \attention This method does not do any bounds checking for the input index
        * (i.e., index >= cloud.points.size () || index < 0), and assumes valid (i.e., finite) data.
        *
        * \param[in] index a \a valid index representing a \a valid query point in the dataset given
        * by \a setInputCloud. If indices were given in setInputCloud, index will be the position in
        * the indices vector.
        *
        * \param[in] radius the radius of the sphere bounding all of p_q's neighbors
        * \param[out] k_indices the resultant indices of the neighboring points
        * \param[out] k_sqr_distances the resultant squared distances to the neighboring points
        * \param[in] max_nn if given, bounds the maximum returned neighbors to this value. If \a max_nn is set to
        * 0 or to a number higher than the number of points in the input cloud, all neighbors in \a radius will be
        * returned.
        * \return number of neighbors found in radius
        *
        * \exception asserts in debug mode if the index is not between 0 and the maximum number of points
        */
      virtual int
      radiusSearch (int index, double radius, std::vector<int> &k_indices,
                    std::vector<float> &k_sqr_distances, unsigned int max_nn = 0) const
      {
        if (indices_ == NULL)
        {
          assert (index >= 0 && index < static_cast<int> (input_->points.size ()) && "Out-of-bounds error in radiusSearch!");
          return (radiusSearch (input_->points[index], radius, k_indices, k_sqr_distances, max_nn));
        }
        else
        {
          assert (index >= 0 && index < static_cast<int> (indices_->size ()) && "Out-of-bounds error in radiusSearch!");
          return (radiusSearch (input_->points[(*indices_)[index]], radius, k_indices, k_sqr_distances, max_nn));
        }
      }

      /** \brief Set the search epsilon precision (error bound) for nearest neighbors searches.
        * \param[in] eps precision (error bound) for nearest neighbors searches
        */
      virtual inline void
      setEpsilon (float eps)
      {
        epsilon_ = eps;
      }

      /** \brief Get the search epsilon precision (error bound) for nearest neighbors searches. */
      inline float
      getEpsilon () const
      {
        return (epsilon_);
      }

      /** \brief Minimum allowed number of k nearest neighbors points that a viable result must contain.
        * \param[in] min_pts the minimum number of neighbors in a viable neighborhood
        */
      inline void
      setMinPts (int min_pts)
      {
        min_pts_ = min_pts;
      }

      /** \brief Get the minimum allowed number of k nearest neighbors points that a viable result must contain. */
      inline int
      getMinPts () const
      {
        return (min_pts_);
      }

    protected:
      /** \brief The input point cloud dataset containing the points we need to use. */
      PointCloudConstPtr input_;

      /** \brief A pointer to the vector of point indices to use. */
      IndicesConstPtr indices_;

      /** \brief Epsilon precision (error bound) for nearest neighbors searches. */
      float epsilon_;

      /** \brief Minimum allowed number of k nearest neighbors points that a viable result must contain. */
      int min_pts_;

      /** \brief Return the radius search neighbours sorted **/
      bool sorted_;

      /** \brief For converting different point structures into k-dimensional vectors for nearest-neighbor search. */
      PointRepresentationConstPtr point_representation_;

      /** \brief Class getName method. */
      virtual std::string
      getName () const = 0;
  };
}

#endif  //#ifndef _PCL_KDTREE_KDTREE_H_


text:
@interface NotificationController()

@property (weak, nonatomic) IBOutlet WKInterfaceLabel *bodyMessage;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *titleMessage;

@end

@implementation NotificationController

- (instancetype)init {
    self = [super init];
    if (self){

		NSLog(@"%s",__FUNCTION__);	// このメソッド名をデバッグ出力
}
    return self;
}

- (void)willActivate {
    [super willActivate];

	NSLog(@"%s",__FUNCTION__);	// このメソッド名をデバッグ出力
}

- (void)didDeactivate {
    [super didDeactivate];

	NSLog(@"%s",__FUNCTION__);	// このメソッド名をデバッグ出力
}

- (void)didReceiveLocalNotification:(UILocalNotification *)localNotification withCompletion:(void (^)(WKUserNotificationInterfaceType))completionHandler {
    completionHandler(WKUserNotificationInterfaceTypeCustom);
}

- (void)didReceiveRemoteNotification:(NSDictionary *)remoteNotification withCompletion:(void (^)(WKUserNotificationInterfaceType))completionHandler {

	// 通知データから情報を取り出す
	NSDictionary* apsDict = [remoteNotification objectForKey:@"aps"];
	NSDictionary* alertDict = [apsDict objectForKey:@"alert"];
	NSString*	bodyString = [alertDict objectForKey:@"body"];
	NSString*	titleString = [alertDict objectForKey:@"title"];

	// 動的ロングルック画面のラベルに表示
	[_bodyMessage setText:bodyString];
	[_titleMessage setText:titleString];

	// 完了ハンドラを呼ぶ
	completionHandler(WKUserNotificationInterfaceTypeCustom);
}

@end


text:
class MapFunction;
class Params;

class MapFunctionFactory {
public:
  static MapFunction* getNewMapFunctionInstance(
    const std::string& mapName, const Params& params);

private:
  MapFunctionFactory();
};

#endif // MAPRED_MAP_FUNCTION_FACTORY_H


text:
This changelog is auto-generated using git-changelog.
See https://github.com/lkdjiin/git-changelog for more information.

2013-07-18 Version 0.2.1
==========================
* 2013-07-18 Fix bug for markdown format
  Html entities are now escaped.
* 2013-07-18 Fix bug with markdown format
  Commit body now start on a new line.
* 2013-07-18 Add auto-generated changelog file

2013-07-18 Version 0.2.0
==========================
* 2013-07-18 Add html format output
  A new --html option outputs a <ul>.
* 2013-07-17 First commit
  The script outputs in markdown and accept the option '--since'.


text: module.exports = require("./asyncToGenerator.js");


text:
class AddCreatorIdToClaims < ActiveRecord::Migration[4.2]
  def change
    add_column :claims, :creator_id, :integer
    add_index :claims, :creator_id
  end
end


text:
Welcome to Terasology Google Code-in 2017 Showcase site!

This page is created to serve as a tutorial on how to create content for the Google Code-in 2017 showcase page.

# Installation
## Prerequisites
### Mac OSX/Linux
This site is built with [jekyll](https://jekyllrb.com/) which comes as a ruby gem. So you need to install Ruby to get started.

[RVM](https://rvm.io/) make it easy to install and manage different versions of Ruby. Install Ruby using RVM by running the following commands

```
~ $ gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

~ $ \curl -sSL https://get.rvm.io | bash -s stable --ruby
```

This installs RVM with the latest stable version of Ruby

**Ubuntu users:** You may need to enable `Run command as a login shell` in Ubuntu's Terminal, under _Edit > Profile Preferences > Title and Command_. Then close the terminal and reopen it. You may also want to run `source ~/.rvm/scripts/rvm` to load RVM.

To install ruby gems from a Gemfile you would need `bundler` which by default comes with RVM ruby but if isn't present you would need to install it using the command `gem install bundler`.

### Windows

If on Windows, you can follow [this guide](https://jekyllrb.com/docs/windows/) on how to install [jekyll](https://jekyllrb.com/).

## Deployment
After you have installed Ruby and cloned the repository deploy the application running the following commands
```
# Enter the app directory
~ $ cd movingblocks.github.com

# Install gems using bundler
~/cd movingblocks.github.com $ bundle install

# Build site starting jekyll server
~/cd movingblocks.github.com $ bundle exec jekyll serve
```

You are ready to go! Browse to `http://localhost:4000`

Source: [FOSSASIA](https://github.com/fossasia/gci16.fossasia.org/wiki/Installation)

# Adding a mentor

Create a <github username>.md file in `_mentors`, you need to use the following format and fill in the information accordingly.

```yaml
---
name: Mentor's full name
country: Mentor's country (2 Letter)
timezone: Mentor's timezone
github: Mentor's GitHub username
introduction: >
  Hello! My name is XXX! It's nice to meet you, I hope you enjoy your stay in MovingBlocks :D
  // This is an example introduction
fields:
  - enter your field here
  - enter your field here
---
```
**NOTE**
- You can check your country code and timezone from this [Wikipedia page](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Country code is written `CC` and Timezone is `TZ`

# Adding a world generator

Create a <world generator name>.md file in `_worldgen`, you need to use the following format and fill in the information accordingly.

```yaml
---
name: World generator's name
author: World generator's author
banner-img: "/img/world-gen-img-goes-here.jpg"
description: >
  World generator description goes here
---
```
**NOTE**
- Add your banner image to folder `/img/`


text:
function[beta] = beta_angles(z,varargin)
% beta_angles -- computation of beta angles from complex samples
%
% beta = beta_angles(z, {k=0, scale=dyadic})
%
%     Computes the beta angles at scale k, defined as
%
%        beta_k(n) = arg((z(n+ind(k)) - z(n))/(z(n) - z(n-ind(k)))),
%
%     for all n. ind(k) is an indexing function defined depending on the
%     optional input 'scale':
%
%        scale = 'dyadic'            Dyadic scaling: ind(k) = 2^k
%        scale = 'linear'            Linear scaling: ind(k) = k+1
%
%     The range of the angle is the same as Matlab's `angle' function: [-pi,pi].

persistent strict_inputs indexing
if isempty(strict_inputs)
  from labtools import strict_inputs
  from shapelab.curves import indexing
end

inputs = {'scale', 'k'};
defaults = {'dyadic', 0};

opt = strict_inputs(inputs, defaults, [], varargin{:});

zsize = size(z);
z = z(:);

ind = indexing(opt.scale);

zp = circshift(z, -ind(opt.k));
zm = circshift(z, ind(opt.k));

beta = angle((zp-z)./(z-zm));

beta = reshape(beta, zsize);


text:
/*
 * compound.h
 *
 *  Created on: Jan 15, 2015
 *      Author: radoslav
 */

#ifndef COMPOUND_H_
#define COMPOUND_H_

#include "statement.h"
#include "environment.h"
#include <vector>

class CompoundStatement: public Statement
{
	std::vector<Statement*> body;

	void copy(const CompoundStatement&);
	void destroy();

public:
	CompoundStatement(): Statement(STATEMENT_COMPOUND) {}
	CompoundStatement(const char*&);
	CompoundStatement(const CompoundStatement&);
	CompoundStatement& operator=(const CompoundStatement&);
	~CompoundStatement();

	CompoundStatement* clone() const { return new CompoundStatement(*this); }

	std::vector<Statement*>::const_iterator getBodyIterator() const { return body.begin(); }
	std::vector<Statement*>::const_iterator getBodyEndIterator() const { return body.end(); }

	Value* execute(Environment&) const;
};

#endif /* COMPOUND_H_ */


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Realms;

namespace DotNetRu.RealmUpdateLibrary
{
    public static class RealmExtensions
    {
        public static RealmObject Clone(this RealmObject source)
        {
            // If source is null return null
            if (source == null)
            {
                return default;
            }

            var targetType = source.GetType();

            var target = Activator.CreateInstance(targetType);

            // List of skip namespaces
            var skipNamespaces = new List<string>
            {
                typeof(Realm).Namespace
            };

            var collectionNamespace = typeof(List<string>).Namespace;

            var flags = BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;

            var targetProperties = targetType.GetProperties(flags)
                .Where(x => !x.IsDefined(typeof(IgnoredAttribute), true))
                .Where(x => !x.IsDefined(typeof(BacklinkAttribute), true));

            foreach (var property in targetProperties)
            {
                if (skipNamespaces.Contains(property.DeclaringType.Namespace))
                {
                    continue;
                }

                var propertyInfo = targetType.GetProperty(property.Name, flags);
                if (propertyInfo == null)
                {
                    continue;
                }

                var sourceValue = property.GetValue(source);

                if (sourceValue is RealmObject)
                {
                    var targetValue = (sourceValue as RealmObject).Clone();
                    propertyInfo.SetValue(target, targetValue);

                    continue;
                }

                if (property.PropertyType.Namespace == collectionNamespace && sourceValue != null)
                {
                    var sourceList = sourceValue as IEnumerable;

                    var targetList = property.GetValue(target) as IList;

                    // Enumerate source list and recursively call Clone method on each object
                    foreach (var item in sourceList)
                    {
                        object value;

                        if (item.GetType().IsValueType || item.GetType() == typeof(string))
                        {
                            value = item;
                        }
                        else
                        {
                            value = (item as RealmObject).Clone();
                        }

                        targetList.Add(value);
                    }

                    continue;
                }

                propertyInfo.SetValue(target, sourceValue);
            }

            return target as RealmObject;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace PH7\Framework\Cron\Run;

defined('PH7') or exit('Restricted access');

use PH7\Framework\Core\Core;
use PH7\Framework\Url\Uri;

abstract class Cron extends Core
{
    private const URI_FILENAME_INDEX = 3;
    private const URI_DELAY_INDEX = 2;
    private const HOUR_IN_SECS = 3600;
    private const DELAY_FILE_EXT = '.txt';

    /**
     * If the server takes time loading the script,
     * we add 10 secs to make sure it won't be seen as "already ran within the cron delay"
     */
    private const DELAY_TOLERANCE_INTERVAL_IN_SEC = 10;

    private int $iTime;

    private Uri $oUri;

    private string $sDelayPathFile;

    public function __construct()
    {
        parent::__construct();

        $this->iTime = time();
        $this->oUri = Uri::getInstance();
        $this->sDelayPathFile = $this->getDelayedFilePath();
    }

    /**
     * @return bool Returns TRUE if the delay is valid, otherwise FALSE.
     */
    protected function checkDelay(): bool
    {
        $bStatus = true; // Default delay status is TRUE

        if ($iSavedTime = $this->getSavedDelay()) {
            $iHours = $this->getCronDelay();
            $iCronTime = $iSavedTime + $this->convertHoursToSeconds($iHours);

            $bStatus = $this->hasDelayPassed($iCronTime);
            if ($bStatus) {
                $this->file->deleteFile($this->sDelayPathFile);
            }
        }

        if ($bStatus) {
            $this->file->putFile($this->sDelayPathFile, $this->iTime);
        }

        return $bStatus;
    }

    /**
     * @return int|false The file contents if it exists, FALSE otherwise.
     * TODO PHP v8.2 will support `false` as standalone type. Will be able to be stricter by replace return types with "int|false"
     */
    private function getSavedDelay(): int|bool
    {
        if ($this->file->existFile($this->sDelayPathFile)) {
            return (int)$this->file->getFile($this->sDelayPathFile);
        }

        return false;
    }

    /**
     * @return string The current cron filename.
     */
    private function getFileName(): string
    {
        return strtolower($this->oUri->fragment(self::URI_FILENAME_INDEX));
    }

    /**
     * @return string The full path of the delayed text file containing the UNIX time of the last cron job execution.
     */
    private function getDelayedFilePath(): string
    {
        return PH7_PATH_SYS . 'core/assets/cron/_delay/' . $this->getFileName() . self::DELAY_FILE_EXT;
    }

    /**
     * Get the cron delay.
     *
     * @return int Delay in hour.
     */
    private function getCronDelay(): int
    {
        /**
         * @internal We cast the value into integer type to get only the integer data (without the 'h' character).
         */
        return (int)$this->oUri->fragment(self::URI_DELAY_INDEX);
    }

    /**
     * @param int $iCronTime
     *
     * @return bool Returns FALSE if the delay hasn't yet elapsed, TRUE otherwise.
     */
    private function hasDelayPassed($iCronTime): bool
    {
        return $iCronTime <= $this->iTime + self::DELAY_TOLERANCE_INTERVAL_IN_SEC;
    }

    /**
     * @param int $iHours Hour(s).
     *
     * @return int Seconds
     */
    private function convertHoursToSeconds(int $iHours): int
    {
        return $iHours * self::HOUR_IN_SECS;
    }
}


text:
"""Utility functions for JAX tests."""

import os
from typing import Any, Mapping, Optional

from absl import flags
from absl.testing import parameterized
import jax
from jax import numpy as jnp
import numpy as np
from praxis import base_layer
from praxis import py_utils
import tensorflow.compat.v2 as tf

FLAGS = flags.FLAGS
JTensor = jnp.ndarray
NestedMap = py_utils.NestedMap

_dtype = lambda x: getattr(x, 'dtype', None) or np.asarray(x).dtype

class TestCase(parameterized.TestCase):
  """Test method for flax tests."""

  def assertAllClose(self,
                     x,
                     y,
                     check_dtypes=True,
                     rtol=1E-5,
                     atol=1E-5,
                     **kwargs):
    """Wrapper for np.testing.assert_allclose()."""
    x = np.asarray(x)
    y = np.asarray(y)
    if check_dtypes:
      self.assertDtypesMatch(x, y)
    x = x.astype(np.float32) if x.dtype == jnp.bfloat16 else x
    y = y.astype(np.float32) if y.dtype == jnp.bfloat16 else y
    np.testing.assert_allclose(x, y, rtol=rtol, atol=atol, **kwargs)

  def assertArraysEqual(self, x, y, check_dtypes=True, **kwargs):
    """Wrapper for np.testing.assert_array_equal()."""
    x = np.asarray(x)
    y = np.asarray(y)
    if check_dtypes:
      self.assertDtypesMatch(x, y)
    np.testing.assert_array_equal(x, y, **kwargs)

  def assertDtypesMatch(self, x, y):
    self.assertEqual(
        jax.dtypes.canonicalize_dtype(_dtype(x)),
        jax.dtypes.canonicalize_dtype(_dtype(y)))

def to_np(x: JTensor) -> np.ndarray:
  """Converts TF/JAX tensors to numpy."""
  return np.asarray(x, dtype=np.float32)

def unshard_input_nmap(x_nmap: NestedMap) -> NestedMap:
  """Unshards input sequences.

  Args:
    x_nmap: NestedMap with some tensors of shape [num_devices, batch, ...].

  Returns:
    NestedMap with tensors reshaped to [num_devices * batch, seq_len].
  """

  def unshard(x: JTensor) -> JTensor:
    num_devices = x.shape[0]
    batch_size = x.shape[1]
    new_shape = [num_devices * batch_size] + list(x.shape[2:])
    return jnp.reshape(x, new_shape)

  return jax.tree_util.tree_map(unshard, x_nmap)

def to_tf_nmap(x_nmap: NestedMap) -> NestedMap:
  """Converts numpy dtypes to TF dtypes in a variable collection."""

  def to_tf(x: Any) -> JTensor:
    if not isinstance(x, np.ndarray):
      x = np.array(x)
    if x.dtype == np.float32:
      return tf.constant(np.asarray(x, x.dtype), tf.float32)
    elif x.dtype == np.int32:
      return tf.constant(np.asarray(x, x.dtype), tf.int32)
    if x.dtype == np.float64:
      return tf.constant(np.asarray(x, x.dtype), tf.float64)
    elif x.dtype == np.int64:
      return tf.constant(np.asarray(x, x.dtype), tf.int64)
    elif x.dtype == np.uint32:
      return tf.constant(np.asarray(x, x.dtype), tf.uint32)
    else:
      assert False, 'dtype not supported yet ' + str(x.dtype)

  return tf.nest.map_structure(to_tf, x_nmap)

def apply(layer, layer_vars, method, *args, context_p=None, **kwargs):
  with base_layer.JaxContext.new_context(hparams=context_p):
    return layer.apply(layer_vars, *args, **kwargs, method=method)

def replace_jax_transformer_ffwd_vars_to_tf(
    jax_initial_vars: NestedMap) -> NestedMap:
  """Replaces JAX TransformerFeedForward vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX TransformerFeedforward layer vars.

  Returns:
    tf_initial_vars which is TF compatible.
  """
  tf_initial_vars = jax_initial_vars.copy()
  tf_initial_vars = py_utils.NestedMap()
  tf_initial_vars.fflayer = py_utils.NestedMap(
      fc=[
          py_utils.NestedMap(
              w=jax_initial_vars.ffn_layer1.linear.w,
              b=jax_initial_vars.ffn_layer1.bias.b),
          py_utils.NestedMap(
              w=jax_initial_vars.ffn_layer2.linear.w,
              b=jax_initial_vars.ffn_layer2.bias.b),
      ],
      dropout=[py_utils.NestedMap(), py_utils.NestedMap()],
  )
  tf_initial_vars.layer_norm = py_utils.NestedMap(
      bias=jax_initial_vars.layer_norm.bias,
      scale=jax_initial_vars.layer_norm.scale)
  tf_initial_vars.residual_dropout = py_utils.NestedMap()
  tf_initial_vars.residual_droppath = py_utils.NestedMap()
  return tf_initial_vars

def replace_jax_attention_vars_to_tf(
    jax_initial_vars: NestedMap,
    cross_attention: Optional[bool] = False) -> NestedMap:
  """Replaces JAX attention vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX attention layer vars.
    cross_attention: Whether cross attention is involved.

  Returns:
    tf_initial_vars which is TF compatible.
  """
  tf_initial_vars = jax_initial_vars.copy()
  tf_initial_vars.fflayer = jax_initial_vars.ff_layer
  tf_initial_vars.fflayer.fflayer = py_utils.NestedMap()
  is_moe = 'gate' in jax_initial_vars.ff_layer
  tf_initial_vars.fflayer.residual_dropout = py_utils.NestedMap()
  if is_moe:
    tf_initial_vars.fflayer.fflayer.layer_norm = py_utils.NestedMap()
    tf_initial_vars.fflayer.fflayer.layer_norm.scale = jax_initial_vars.ff_layer.layer_norm.scale
    tf_initial_vars.fflayer.fflayer.layer_norm.bias = jax_initial_vars.ff_layer.layer_norm.bias
    tf_initial_vars.fflayer.fflayer.gate = jax_initial_vars.ff_layer.gate
    tf_initial_vars.fflayer.fflayer.wi_0 = jax_initial_vars.ff_layer.wi_0
    tf_initial_vars.fflayer.fflayer.wo_0 = jax_initial_vars.ff_layer.wo_0
  else:
    tf_initial_vars.fflayer.fflayer.dropout = [1.0, 1.0]
    tf_initial_vars.fflayer.fflayer.fc = [NestedMap(), NestedMap()]
    tf_initial_vars.fflayer.fflayer.fc[0].w = (
        jax_initial_vars.ff_layer.ffn_layer1.linear.w)
    tf_initial_vars.fflayer.fflayer.fc[0].b = (
        jax_initial_vars.ff_layer.ffn_layer1.bias.b)
    tf_initial_vars.fflayer.fflayer.fc[1].w = (
        jax_initial_vars.ff_layer.ffn_layer2.linear.w)
    tf_initial_vars.fflayer.fflayer.fc[1].b = (
        jax_initial_vars.ff_layer.ffn_layer2.bias.b)
  tf_initial_vars.self_atten = NestedMap()
  tf_initial_vars.self_atten.layer_norm = jax_initial_vars.layer_norm
  tf_initial_vars.self_atten.atten = jax_initial_vars.self_attention
  tf_initial_vars.self_atten.atten.atten_dropout = py_utils.NestedMap()
  tf_initial_vars.self_atten.residual_dropout = 1.0
  if cross_attention:
    tf_initial_vars.cross_atten = NestedMap()
    tf_initial_vars.cross_atten.layer_norm = jax_initial_vars.layer_norm
    tf_initial_vars.cross_atten.atten = jax_initial_vars.cross_attention
    tf_initial_vars.cross_atten.atten.atten_dropout = py_utils.NestedMap()
    tf_initial_vars.cross_atten.residual_dropout = 1.0
  return tf_initial_vars

def replace_jax_single_shard_full_softmax_vars_to_tf(
    jax_initial_vars: NestedMap) -> NestedMap:
  """Replaces JAX Single Shard Full Softmax vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX ConvBNAct layer vars.

  Returns:
    tf_initial_vars which is TF compatible with ConvBNAct.
  """
  tf_initial_vars = jax_initial_vars.copy()
  tf_initial_vars.linear = py_utils.NestedMap(
      w=jax_initial_vars.logits_ffn.linear.w)
  tf_initial_vars.bias = py_utils.NestedMap(
      b=jax_initial_vars.logits_ffn.bias.b)
  del tf_initial_vars.logits_ffn
  return tf_initial_vars

def replace_jax_simple_full_softmax_vars_to_tf(
    jax_initial_vars: NestedMap) -> NestedMap:
  """Replaces JAX Simple Full Softmax vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX ConvBNAct layer vars.

  Returns:
    tf_initial_vars which is TF compatible with ConvBNAct.
  """
  tf_initial_vars = jax_initial_vars.copy()
  tf_initial_vars.weight_0 = jax_initial_vars.logits_ffn.linear.w
  tf_initial_vars.bias_0 = jax_initial_vars.logits_ffn.bias.b
  del tf_initial_vars.logits_ffn
  return tf_initial_vars

def replace_jax_conv_bnact_vars_to_tf(jax_initial_vars: NestedMap) -> NestedMap:
  """Replaces JAX ConvBNAct variables to TF compatible variables.

  Args:
    jax_initial_vars: JAX ConvBNAct layer vars.

  Returns:
    tf_initial_vars which is TF compatible with ConvBNAct.
  """
  tf_initial_vars = jax_initial_vars.copy()
  tf_initial_vars.conv = NestedMap(w=jax_initial_vars.w)
  tf_initial_vars.act = NestedMap()
  del tf_initial_vars.w
  return tf_initial_vars

def replace_jax_res_net_block_vars_to_tf(
    jax_initial_vars: NestedMap) -> NestedMap:
  """Replaces the JAX ResNetBlock vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX ResNetBlock vars.

  Returns:
    tf_initial_vars which is TF compatible with ResNetBlock.
  """
  tf_initial_vars = jax_initial_vars.copy()
  body_prefix = 'body_'
  body_keys = sorted(
      [k for k in tf_initial_vars.keys() if k.startswith(body_prefix)],
      key=lambda x: int(x[len(body_prefix):]))
  tf_initial_vars.body = [
      replace_jax_conv_bnact_vars_to_tf(getattr(tf_initial_vars, bk))
      for bk in body_keys
  ]
  if 'shortcut' in tf_initial_vars:
    tf_initial_vars.shortcut = replace_jax_conv_bnact_vars_to_tf(
        tf_initial_vars.shortcut)
  # Activations does not own vars, but lingvo TF needs the field.
  tf_initial_vars.postact = NestedMap()
  return tf_initial_vars

def replace_jax_res_net_vars_to_tf(jax_initial_vars: NestedMap) -> NestedMap:
  """Replaces the JAX ResNet vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX ResNet layer vars.

  Returns:
    tf_initial_vars which is TF compatible with ResNet.
  """
  tf_initial_vars = jax_initial_vars.copy()
  tf_initial_vars.entryflow_conv = replace_jax_conv_bnact_vars_to_tf(
      tf_initial_vars.entryflow_conv)
  # A few layers do not own vars, but lingvo TF may need the fields.
  tf_initial_vars.entryflow_maxpool = NestedMap()
  tf_initial_vars.output_spatial_pooling = NestedMap()
  stage_id = 0
  block_id = 0
  block = f'stage_{stage_id}_block_{block_id}'
  while block in tf_initial_vars:
    while block in tf_initial_vars:
      tf_initial_vars[block] = replace_jax_res_net_block_vars_to_tf(
          tf_initial_vars[block])
      block_id += 1
      block = f'stage_{stage_id}_block_{block_id}'
    stage_id += 1
    block_id = 0
    block = f'stage_{stage_id}_block_{block_id}'
  return tf_initial_vars

def replace_jax_light_conv_vars_to_tf(
    jax_initial_vars: NestedMap, jax_initial_non_trainable_vars) -> NestedMap:
  """Replace the JAX LightConv vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX LightConv vars.
    jax_initial_non_trainable_vars: JAX LightConv non-trainable vars.

  Returns:
    tf_initial_vars which is TF compatible with LightConv.
  """
  tf_initial_vars = py_utils.NestedMap()

  tf_initial_vars.ln = py_utils.NestedMap()
  tf_initial_vars.ln.bias = jax_initial_vars.ln.bias
  tf_initial_vars.ln.scale = jax_initial_vars.ln.scale

  tf_initial_vars.norm = py_utils.NestedMap()
  tf_initial_vars.norm.beta = jax_initial_vars.conv_norm.beta
  tf_initial_vars.norm.gamma = jax_initial_vars.conv_norm.gamma
  tf_initial_vars.norm.moving_mean = (
      jax_initial_non_trainable_vars.conv_norm.moving_mean)
  tf_initial_vars.norm.moving_variance = (
      jax_initial_non_trainable_vars.conv_norm.moving_variance)

  tf_initial_vars.dropout = [py_utils.NestedMap(), py_utils.NestedMap()]

  tf_initial_vars.depthwise_conv1d = py_utils.NestedMap()
  tf_initial_vars.depthwise_conv1d.w = np.expand_dims(
      jax_initial_vars.depthwise_conv1d.w, axis=-1)

  tf_initial_vars.linear_end = py_utils.NestedMap()
  tf_initial_vars.linear_end.w = jax_initial_vars.linear_end.linear.w
  tf_initial_vars.linear_end.b = jax_initial_vars.linear_end.bias.b

  tf_initial_vars.linear_start = py_utils.NestedMap()
  tf_initial_vars.linear_start.w = np.concatenate([
      jax_initial_vars.linear_start_gated.linear.w,
      jax_initial_vars.linear_start_act.linear.w
  ],
                                                  axis=-1)
  tf_initial_vars.linear_start.b = np.concatenate([
      jax_initial_vars.linear_start_gated.bias.b,
      jax_initial_vars.linear_start_act.bias.b
  ],
                                                  axis=-1)

  tf_initial_vars = to_tf_nmap(tf_initial_vars)
  return tf_initial_vars

def replace_jax_conformer_layer_vars_to_tf(
    jax_initial_vars: NestedMap,
    jax_initial_non_trainable_vars: NestedMap) -> NestedMap:
  """Replace the JAX conformer layer vars to TF compatible vars.

  Args:
    jax_initial_vars: JAX conformer layer vars.
    jax_initial_non_trainable_vars: JAX conformer layer non_trainable_vars.

  Returns:
    tf_initial_vars which is TF compatible with ConformerLayer.
  """

  tf_initial_vars = py_utils.NestedMap()

  tf_initial_vars.lconv = replace_jax_light_conv_vars_to_tf(
      jax_initial_vars.lconv, jax_initial_non_trainable_vars.lconv)

  tf_initial_vars.final_ln = py_utils.NestedMap()
  tf_initial_vars.final_ln.bias = jax_initial_vars.final_ln.bias
  tf_initial_vars.final_ln.scale = jax_initial_vars.final_ln.scale

  tf_initial_vars.fflayer_start = py_utils.NestedMap()
  tf_initial_vars.fflayer_start.residual_dropout = py_utils.NestedMap()
  tf_initial_vars.fflayer_start.layer_norm = jax_initial_vars.fflayer_start.layer_norm
  tf_initial_vars.fflayer_start.fflayer = py_utils.NestedMap()
  tf_initial_vars.fflayer_start.fflayer.dropout = [
      py_utils.NestedMap(), py_utils.NestedMap()
  ]
  tf_initial_vars.fflayer_start.fflayer.fc = [
      py_utils.NestedMap(), py_utils.NestedMap()
  ]
  tf_initial_vars.fflayer_start.fflayer.fc[
      0].w = jax_initial_vars.fflayer_start.ffn_layer1.linear.w
  tf_initial_vars.fflayer_start.fflayer.fc[
      0].b = jax_initial_vars.fflayer_start.ffn_layer1.bias.b
  tf_initial_vars.fflayer_start.fflayer.fc[
      1].w = jax_initial_vars.fflayer_start.ffn_layer2.linear.w
  tf_initial_vars.fflayer_start.fflayer.fc[
      1].b = jax_initial_vars.fflayer_start.ffn_layer2.bias.b

  tf_initial_vars.fflayer_end = py_utils.NestedMap()
  tf_initial_vars.fflayer_end.layer_norm = jax_initial_vars.fflayer_end.layer_norm
  tf_initial_vars.fflayer_end.residual_dropout = py_utils.NestedMap()
  tf_initial_vars.fflayer_end.fflayer = py_utils.NestedMap()
  tf_initial_vars.fflayer_end.fflayer.dropout = [
      py_utils.NestedMap(), py_utils.NestedMap()
  ]
  tf_initial_vars.fflayer_end.fflayer.fc = [
      py_utils.NestedMap(), py_utils.NestedMap()
  ]
  tf_initial_vars.fflayer_end.fflayer.fc[
      0].w = jax_initial_vars.fflayer_end.ffn_layer1.linear.w
  tf_initial_vars.fflayer_end.fflayer.fc[
      0].b = jax_initial_vars.fflayer_end.ffn_layer1.bias.b
  tf_initial_vars.fflayer_end.fflayer.fc[
      1].w = jax_initial_vars.fflayer_end.ffn_layer2.linear.w
  tf_initial_vars.fflayer_end.fflayer.fc[
      1].b = jax_initial_vars.fflayer_end.ffn_layer2.bias.b

  tf_initial_vars.trans_atten = py_utils.NestedMap()
  tf_initial_vars.trans_atten.layer_norm = jax_initial_vars.trans_atten.norm
  tf_initial_vars.trans_atten.residual_dropout = py_utils.NestedMap()
  tf_initial_vars.trans_atten.atten = jax_initial_vars.trans_atten.self_atten
  tf_initial_vars.trans_atten.atten.atten_dropout = py_utils.NestedMap()
  tf_initial_vars = to_tf_nmap(tf_initial_vars)
  return tf_initial_vars

def get_tfevent_scalars(root: str) -> Mapping[str, float]:
  """Extracts dict of scalars from all tfevents proto files under a dir."""
  # recursively walk from root and collect all tfevent files
  tfevent_files = []
  for dirname, subdir, fnames in tf.io.gfile.walk(root):
    if subdir:
      continue

    for fname in fnames:
      if fname.startswith('events.out.tfevents'):
        tfevent_files.append(os.path.join(dirname, fname))

  # for all tfevent files extract scalar tensor values
  scalars = {}
  for tfevent_file in tfevent_files:
    for event in tf.compat.v1.train.summary_iterator(tfevent_file):
      for value in event.summary.value:
        if value.metadata.plugin_data.plugin_name != 'scalars':
          continue

        if not value.HasField('tensor'):
          continue

        np_value = tf.make_ndarray(value.tensor)
        scalars[value.tag] = np_value.item()

  return scalars


text:
'''
test file for testing various scenarios in security center's repositories
functionality
'''
import os

import pytest

from tenable.errors import APIError, UnexpectedValueError
from tests.pytenable_log_handler import log_exception
from ..checker import check

@pytest.fixture
def repository(request, vcr, admin):
    '''
    test fixture for repository
    '''
    with vcr.use_cassette('repository'):
        repo = admin.repositories.create(name='Example Repo')

    def teardown():
        try:
            admin.repositories.delete(int(repo['id']))
        except APIError as error:
            log_exception(error)

    request.addfinalizer(teardown)
    return repo

def test_repositories_constructor_nessus_sched_typeerror(security_center):
    '''
    test repositories constructor for 'nessus sched' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(nessus_sched=1)

def test_repositories_constructor_mobile_sched_typeerror(security_center):
    '''
    test repositories constructor for 'mobile sched' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(mobile_sched=1)

def test_repositories_constructor_remote_sched_typeerror(security_center):
    '''
    test repositories constructor for 'remote sched' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(remote_sched=1)

def test_repositories_constructor_name_typeerror(security_center):
    '''
    test repositories constructor for 'name' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(name=1)

    with pytest.raises(TypeError):
        security_center.repositories._constructor(nessus_sched={'type': 'dependent', 'dependentID': 1}, name=1)

def test_repositories_constructor_description_typeerror(security_center):
    '''
    test repositories constructor for 'description' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(description=1)

def test_repositories_constructor_format_typeerror(security_center):
    '''
    test repositories constructor for 'format' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(format=1)

def test_repositories_constructor_format_unexpectedvalueerror(security_center):
    '''
    test repositories constructor for 'format' unexpected value error.
    '''
    with pytest.raises(UnexpectedValueError):
        security_center.repositories._constructor(format='none')

def test_repositories_constructor_orgs_typeerror(security_center):
    '''
    test repositories constructor for 'orgs' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(orgs=1)

def test_repositories_constructor_org_item_typeerror(security_center):
    '''
    test repositories constructor for 'org item' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(orgs=['one'])

def test_repositories_constructor_trending_typeerror(security_center):
    '''
    test repositories constructor for 'trending' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(trending='one')

def test_repositories_constructor_trending_unexpectedvalueerror(security_center):
    '''
    test repositories constructor for 'trending' unexpected value error
    '''
    with pytest.raises(UnexpectedValueError):
        security_center.repositories._constructor(trending=999)

def test_repositories_constructor_fulltext_search_typerror(security_center):
    '''
    test repositories constructor for 'full text search' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(fulltext_search='yup')

def test_repositories_constructor_lce_correlation_typeerror(security_center):
    '''
    test repositories constructor for 'lce correlation' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(lce_correlation='yup')

def test_repositories_constructor_allowed_ips_typeerror(security_center):
    '''
    test repositories constructor for 'allowed ips' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(allowed_ips='127.0.0.1')

def test_repositories_constructor_allowed_ips_item_typeerror(security_center):
    '''
    test repositories constructor for 'allowed ips item' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(allowed_ips=[1])

def test_repositories_constructor_remote_ip_typeerror(security_center):
    '''
    test repositories constructor for 'remote ip' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(remote_ip=1)

def test_repositories_constructor_remote_repo_typeerror(security_center):
    '''
    test repositories constructor for 'remote repo' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(remote_repo='one')

def test_repositories_constructor_preferences_typeerror(security_center):
    '''
    test repositories constructor for 'preferences' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(preferences=1)

def test_repositories_constructor_preferences_key_typeerror(security_center):
    '''
    test repositories constructor for 'preferences key' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(preferences={1: 'one'})

def test_repositories_constructor_preferences_value_typeerror(security_center):
    '''
    test repositories constructor for 'preferences value' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(preferences={'key': 1})

def test_repositories_constructor_mdm_id_typeerror(security_center):
    '''
    test repositories constructor for 'mdm id' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(mdm_id='one')

def test_repositories_constructor_scanner_id_typeerror(security_center):
    '''
    test repositories constructor for 'scanner id' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._constructor(scanner_id='one')

def test_repositories_constructor_success(security_center):
    '''
    test repositories constructor for success
    '''
    resp = security_center.repositories._constructor(
        nessus_sched={'type': 'ical', 'start': 'start', 'repeatRule': 'rule'},
        mobile_sched={'type': 'never'},
        remote_sched={'type': 'never'},
        name='Test Constructor',
        description='Desc',
        format='IPv4',
        repo_type='Local',
        orgs=[1],
        trending=90,
        fulltext_search=True,
        lce_correlation=[1],
        allowed_ips=['127.0.0.1'],
        remote_ip='127.0.0.1',
        remote_repo=1,
        preferences={'name': 'value'},
        mdm_id=1,
        scanner_id=1
    )
    assert resp == {
        'nessusSchedule': {
            'type': 'ical',
            'start': 'start',
            'repeatRule': 'rule'
        },
        'mobileSchedule': {'type': 'never'},
        'remoteSchedule': {'type': 'never'},
        'name': 'Test Constructor',
        'description': 'Desc',
        'dataFormat': 'IPv4',
        'type': 'Local',
        'organizations': [{'id': 1}],
        'trendingDays': 90,
        'trendWithRaw': 'true',
        'correlation': [{'id': 1}],
        'ipRange': '127.0.0.1',
        'remoteIP': '127.0.0.1',
        'remoteID': 1,
        'preferences': {
            'name': 'value'
        },
        'mdm': {'id': 1},
        'scanner': {'id': 1}
    }

@pytest.mark.vcr()
def test_repositories_create_success(repository):
    '''
    test repositories create for success
    '''
    assert isinstance(repository, dict)
    check(repository, 'createdTime', str)
    check(repository, 'dataFormat', str)
    check(repository, 'description', str)
    check(repository, 'downloadFormat', str)
    check(repository, 'id', str)
    check(repository, 'lastSyncTime', str)
    check(repository, 'lastVulnUpdate', str)
    check(repository, 'modifiedTime', str)
    check(repository, 'name', str)
    check(repository, 'organizations', list)
    check(repository, 'remoteID', str, allow_none=True)
    check(repository, 'remoteIP', str, allow_none=True)
    check(repository, 'running', str)
    check(repository, 'type', str)
    check(repository, 'typeFields', dict)
    check(repository['typeFields'], 'correlation', list)
    check(repository['typeFields'], 'ipCount', str)
    check(repository['typeFields'], 'ipRange', str)
    check(repository['typeFields'], 'lastGenerateNessusTime', str)
    check(repository['typeFields'], 'lastTrendUpdate', str)
    check(repository['typeFields'], 'nessusSchedule', dict)
    check(repository['typeFields']['nessusSchedule'], 'repeatRule', str)
    check(repository['typeFields']['nessusSchedule'], 'start', str)
    check(repository['typeFields']['nessusSchedule'], 'type', str)
    check(repository['typeFields'], 'runningNessus', str)
    check(repository['typeFields'], 'trendWithRaw', str)
    check(repository['typeFields'], 'trendingDays', str)
    check(repository, 'vulnCount', str)

def test_repositories_details_id_typeerror(security_center):
    '''
    test repositories details for 'id' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.details('one')

def test_repositories_details_fields_typeerror(security_center):
    '''
    test repositories details for 'fields' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.details(1, fields=1)

def test_repositories_details_field_item_typeerror(security_center):
    '''
    test repositories details for 'field item' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.details(1, fields=[1])

@pytest.mark.vcr()
def test_repositories_remote_sync(admin):
    '''
    test repositories remote sync for success
    '''
    admin.repositories.remote_sync(200001)

@pytest.mark.vcr()
def test_repositories_mobile_sync(admin):
    '''
    test repositories mobile sync for success
    '''
    admin.repositories.mobile_sync(200001)

@pytest.mark.vcr()
def test_repositories_details_success(admin, repository):
    '''
    test repositories details for success
    '''
    repository = admin.repositories.details(int(repository['id']))
    assert isinstance(repository, dict)
    check(repository, 'createdTime', str)
    check(repository, 'dataFormat', str)
    check(repository, 'description', str)
    check(repository, 'downloadFormat', str)
    check(repository, 'id', str)
    check(repository, 'lastSyncTime', str)
    check(repository, 'lastVulnUpdate', str)
    check(repository, 'modifiedTime', str)
    check(repository, 'name', str)
    check(repository, 'organizations', list)
    check(repository, 'remoteID', str, allow_none=True)
    check(repository, 'remoteIP', str, allow_none=True)
    check(repository, 'running', str)
    check(repository, 'type', str)
    check(repository, 'typeFields', dict)
    check(repository['typeFields'], 'correlation', list)
    check(repository['typeFields'], 'ipCount', str)
    check(repository['typeFields'], 'ipRange', str)
    check(repository['typeFields'], 'lastGenerateNessusTime', str)
    check(repository['typeFields'], 'lastTrendUpdate', str)
    check(repository['typeFields'], 'nessusSchedule', dict)
    check(repository['typeFields']['nessusSchedule'], 'repeatRule', str)
    check(repository['typeFields']['nessusSchedule'], 'start', str)
    check(repository['typeFields']['nessusSchedule'], 'type', str)
    check(repository['typeFields'], 'runningNessus', str)
    check(repository['typeFields'], 'trendWithRaw', str)
    check(repository['typeFields'], 'trendingDays', str)
    check(repository, 'vulnCount', str)

@pytest.mark.vcr()
def test_repositories_list_success(admin):
    '''
    test repositories list for success
    '''
    for repo in admin.repositories.list(fields=['id', 'name'], repo_type='Local'):
        assert isinstance(repo, dict)
        check(repo, 'name', str)
        check(repo, 'id', str)

@pytest.mark.vcr()
def test_repositories_create_success_data_format_ipv6(admin):
    '''
    test repositories create success with data format ipv6
    '''
    repo = admin.repositories.create(dataFormat='IPv6', type='remote')
    assert isinstance(repo, dict)
    check(repo, 'name', str)
    check(repo, 'id', str)
    admin.repositories.delete(int(repo['id']))

@pytest.mark.vcr()
def test_repositories_create_success_data_format_mobile(admin):
    '''
    test repositories create success with data format mobile
    '''
    repo = admin.repositories.create(dataFormat='mobile')
    assert isinstance(repo, dict)
    check(repo, 'name', str)
    check(repo, 'id', str)
    admin.repositories.delete(int(repo['id']))

def test_repositories_delete_id_typeerror(security_center):
    '''
    test repositories delete for id type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.delete('one')

@pytest.mark.vcr()
def test_repositories_delete_success(admin, repository):
    '''
    test repositories delete for success
    '''
    admin.repositories.delete(int(repository['id']))

def test_repositories_edit_id_typeerror(security_center):
    '''
    test repositories edit for id type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.edit('one')

@pytest.mark.vcr()
def test_repositories_edit_success(admin, repository):
    '''
    test repositories edit for success
    '''
    repository = admin.repositories.edit(int(repository['id']), name='New Name')
    assert isinstance(repository, dict)
    check(repository, 'createdTime', str)
    check(repository, 'dataFormat', str)
    check(repository, 'description', str)
    check(repository, 'downloadFormat', str)
    check(repository, 'id', str)
    check(repository, 'lastSyncTime', str)
    check(repository, 'lastVulnUpdate', str)
    check(repository, 'modifiedTime', str)
    check(repository, 'name', str)
    check(repository, 'organizations', list)
    check(repository, 'remoteID', str, allow_none=True)
    check(repository, 'remoteIP', str, allow_none=True)
    check(repository, 'running', str)
    check(repository, 'type', str)
    check(repository, 'typeFields', dict)
    check(repository['typeFields'], 'correlation', list)
    check(repository['typeFields'], 'ipCount', str)
    check(repository['typeFields'], 'ipRange', str)
    check(repository['typeFields'], 'lastGenerateNessusTime', str)
    check(repository['typeFields'], 'lastTrendUpdate', str)
    check(repository['typeFields'], 'nessusSchedule', dict)
    check(repository['typeFields']['nessusSchedule'], 'repeatRule', str)
    check(repository['typeFields']['nessusSchedule'], 'start', str)
    check(repository['typeFields']['nessusSchedule'], 'type', str)
    check(repository['typeFields'], 'runningNessus', str)
    check(repository['typeFields'], 'trendWithRaw', str)
    check(repository['typeFields'], 'trendingDays', str)
    check(repository, 'vulnCount', str)

def test_repositories_rules_constructor_plugin_id_typeerror(security_center):
    '''
    test repositories rules constructor for 'plugin id' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._rules_constructor(plugin_id='one')

def test_repositories_rules_constructor_port_typeerror(security_center):
    '''
    test repositories rules constructor for 'port' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._rules_constructor(port='one')

def test_repositories_rules_constructor_org_typeerror(security_center):
    '''
    test repositories rules constructor for 'org' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._rules_constructor(orgs=1)

def test_repositories_rules_constructor_org_item_typeerror(security_center):
    '''
    test repositories rules constructor for 'org item' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._rules_constructor(orgs=['one'])

def test_repositories_rules_constructor_fields_typeerror(security_center):
    '''
    test repositories rules constructor for 'fields' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._rules_constructor(fields=1)

def test_repositories_rules_constructor_field_item_typeerror(security_center):
    '''
    test repositories rules constructor for 'field item' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories._rules_constructor(fields=[1])

def test_repositories_rules_constructor_success(security_center):
    '''
    test repositories rules constructor for success
    '''
    resp = security_center.repositories._rules_constructor(
        plugin_id=1,
        port=1,
        orgs=[1, 2],
        fields=['name1', 'name2'])
    assert resp == {
        'pluginID': 1,
        'port': 1,
        'organizationIDs': '1,2',
        'fields': 'name1,name2'
    }

def test_repositories_accept_risk_rules_id_typeerror(security_center):
    '''
    test repositories accept risk rules for 'id' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.accept_risk_rules('one')

@pytest.mark.skip(reason='Need VCRed data to test against')
@pytest.mark.vcr()
def test_repositories_accept_risk_rules_success():
    '''
    test repositories accept risk rules for success
    '''
    pass

def test_repositories_recast_risk_rules_id_typeerror(security_center):
    '''
    test repositories recast risk rules for 'id' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.recast_risk_rules('one')

@pytest.mark.skip(reason='Need VCRed data to test against')
@pytest.mark.vcr()
def test_repositories_recast_risk_rules_success():
    '''
    test repositories recast risk rules for success
    '''
    pass

def test_repositories_asset_intersections_id_typeerror(security_center):
    '''
    test repositories asset intersections for id type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.asset_intersections('one')

def test_repositories_asset_intersections_uuid_typeerror(security_center):
    '''
    test repositories asset intersections for uuid type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.asset_intersections(1, uuid=1)

def test_repositories_asset_intersections_uuid_unexpectedvalueerror(security_center):
    '''
    test repositories asset intersections for uuid unexpected value error
    '''
    with pytest.raises(UnexpectedValueError):
        security_center.repositories.asset_intersections(1, uuid='something')

def test_repositories_asset_intersections_dns_typerrror(security_center):
    '''
    test repositories asset intersections for dns type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.asset_intersections(1, dns=1)

def test_repositories_asset_intersections_ip_typeerror(security_center):
    '''
    test repositories asset intersections for ip type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.asset_intersections(1, ip=1)

@pytest.mark.vcr()
def test_repositories_asset_intersections_success(admin, repository):
    '''
    test repositories asset intersections for success
    '''
    asset_lists = admin.repositories.asset_intersections(
        int(repository['id']), ip_address='192.168.0.1')
    assert isinstance(asset_lists, list)
    for asset_list in asset_lists:
        check(asset_list, 'description', str)
        check(asset_list, 'id', str)
        check(asset_list, 'name', str)

def test_repositories_import_repository_id_typeerror(security_center):
    '''
    test repositories import repository for id type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.import_repository('one', 1)

@pytest.mark.vcr()
@pytest.mark.datafiles(os.path.join(
    os.path.dirname(os.path.realpath(__file__)),
    '..', 'test_files', 'sc_repo.tgz'))
def test_repositories_import_repository_success(admin, datafiles, repository):
    '''
    test repositories import repository for success
    '''
    # offline = admin.repositories.create(name='Offline', type='Offline')
    with open(os.path.join(str(datafiles), 'sc_repo.tgz'), 'rb') as repo:
        admin.repositories.import_repository(int(repository['id']), repo)

def test_repositories_export_repository_id_typeerror(security_center):
    '''
    test repositories export repository for id type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.export_repository('one', 1)

@pytest.mark.vcr()
def test_repositories_export_repository_success(admin, repository):
    '''
    test repositories export repository for success
    '''
    with open('{}'.format(repository['id']), 'wb') as repo:
        admin.repositories.export_repository(int(repository['id']), repo)
    os.remove('{}'.format(repository['id']))

def test_repositories_device_info_id_typeerror(security_center):
    '''
    test repositories device info for id type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.device_info('one')

def test_repositories_device_into_dns_typeerror(security_center):
    '''
    test repositories device info for dns type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.device_info(1, dns=1)

def test_repositories_device_info_ip_typeerror(security_center):
    '''
    test repositories device info for ip type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.device_info(1, ip=1)

def test_repositories_device_info_uuid_typeerror(security_center):
    '''
    test repositories device info for uuid type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.device_info(1, uuid=1)

def test_repositories_device_info_uuid_unexpectedvalueerror(security_center):
    '''
    test repositories device info for uuid unexpected value error
    '''
    with pytest.raises(UnexpectedValueError):
        security_center.repositories.device_info(1, uuid='something')

def test_repositories_device_info_fields_typeerror(security_center):
    '''
    test repositories device info for fields type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.device_info(1, fields=1)

def test_repositories_device_info_field_item_typeerror(security_center):
    '''
    test repositories device info for 'field item' type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.device_info(1, fields=[1])

@pytest.mark.vcr()
def test_repositories_device_info_success(admin, repository):
    '''
    test repositories device info for success
    '''
    repo = admin.repositories.device_info(int(repository['id']), dns='server')
    assert isinstance(repo, dict)
    check(repo, 'biosGUID', str)
    check(repo, 'hasCompliance', str)
    check(repo, 'hasPassive', str)
    check(repo, 'ip', str)
    check(repo, 'lastAuthRun', str)
    check(repo, 'lastScan', str)
    check(repo, 'lastUnauthRun', str)
    check(repo, 'links', list)
    check(repo, 'macAddress', str)
    check(repo, 'mcafeeGUID', str)
    check(repo, 'netbiosName', str)
    check(repo, 'os', str)
    check(repo, 'osCPE', str)
    check(repo, 'pluginSet', str)
    check(repo, 'pluginSet', str)
    check(repo, 'policyName', str)
    check(repo, 'repository', dict)
    check(repo['repository'], 'description', str)
    check(repo['repository'], 'id', str)
    check(repo['repository'], 'name', str)
    check(repo, 'score', str)
    check(repo, 'severityAll', str)
    check(repo, 'severityCritical', str)
    check(repo, 'severityInfo', str)
    check(repo, 'severityLow', str)
    check(repo, 'severityMedium', str)
    check(repo, 'total', str)
    check(repo, 'tpmID', str)
    check(repo, 'uniqueness', str)
    check(repo, 'uuid', str)

@pytest.mark.vcr()
def test_repositories_device_info_success_ip_info(admin, repository):
    '''
    test repositories device info success with ip info
    '''
    admin._version = "5.6.0"
    repo = admin.repositories.device_info(int(repository['id']), dns='server')
    assert isinstance(repo, dict)
    check(repo, 'biosGUID', str)
    check(repo, 'hasCompliance', str)
    check(repo, 'hasPassive', str)
    check(repo, 'ip', str)

def test_repositories_remote_authorize_host_typeerror(security_center):
    '''
    test repositories remote authorize for host type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.remote_authorize(1, 'user', 'pass')

def test_repositories_remote_authorize_username_typeerror(security_center):
    '''
    test repositories remote authorize for username type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.remote_authorize('host', 1, 'pass')

def test_repositories_remote_authorize_password_typeerror(security_center):
    '''
    test repositories remote authorize for password type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.remote_authorize('host', 'user', 1)

@pytest.mark.skip(reason='No Downstream SC to Test with yet')
def test_repositories_remote_authorize_success():
    '''
    test repositories remote authorize for success
    '''
    pass

def test_repositories_remote_fetch_host_typeerror(security_center):
    '''
    test repositories remote fetch for host type error
    '''
    with pytest.raises(TypeError):
        security_center.repositories.remote_fetch(1)

@pytest.mark.skip(reason='No Downstream SC to Test with yet')
def test_repositories_remote_fetch_success():
    '''
    test repositories remote fetch for success
    '''
    pass


text:
package humanize.util;

import java.util.Locale;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestUTF8Control
{

    // TODO implement test
    @Test
    public void newBundle()
    {

        UTF8Control control = new UTF8Control();
        try
        {
            control.newBundle("", Locale.getDefault(), "", TestUTF8Control.class.getClassLoader(), true);
        } catch (Exception e)
        {
            Assert.fail(e.getMessage(), e);
        }

    }
}