text:
'use strict';

fw.main(function(pg){
	var tmpl = pg.tmpl;
	var _ = tmpl.i18n;

	var showPage = function(){
		if(pg.destroyed) return;
		var userInfo = pg.parent.userInfo;
		if(!userInfo.id) {

			// login page
			var $content = $('#content').html(tmpl.login());
			// section switch
			$content.find('.section_title a').click(function(e){
				e.preventDefault();
				var $section = $(this).closest('.section');
				if(!$section.hasClass('section_folded')) return;
				$section.parent().children('.section:not(.section_folded)').addClass('section_folded')
					.children('form').slideUp(200, function(){
						$section.removeClass('section_folded').children('form').slideDown(200);
					});
			});
			$content.find('.section_folded>form').hide();
			// submit forms
			$content.find('form').each(function(){
				var $form = $(this);
				pg.form(this, function(){
					if($form.find('.passwordRe').length) {
						if($form.find('.passwordRe').val() !== $form.find('.password').val()) {
							$form.find('.passwordRe').val('').focus();
							return false;
						}
					}
					if($form.find('.password').val())
						$form.find('[name=password]').val(
							CryptoJS.SHA256($form.find('[name=id]').val().toLowerCase() +'|'+ $form.find('.password').val())
						);
					$form.find('[type=submit]').prop('disabled', true);
				}, function(err){
					if(err) {
						$form.find('[type=submit]').prop('disabled', false);
						$form.find('.error').html(tmpl.error(err));
						return;
					}
					location.pathname = '/wp.backstage/home';
				}, function(){
					$form.find('[type=submit]').prop('disabled', false);
					$form.find('.error').html(tmpl.error({ timeout: true }));
				});
			});

		} else {

			// common page
			var $content = $('#content').html(tmpl.main({
				username: userInfo.id,
				displayName: userInfo.displayName,
				type: userInfo.type,
				email: userInfo.email,
				url: userInfo.url,
				description: userInfo.description,
				avatar: (userInfo.avatar ? userInfo.avatar+'/128.png' : wp.gravatarUrl(userInfo.email, 128)),
				avatarDel: !!userInfo.avatar
			}));
			// user settings
			var $user = $content.children('.home_user');
			$user.find('.avatar_file input').change(function(){
				// read, convert and send image
				var file = this.files[0];
				var url = URL.createObjectURL(file);
				var img = document.createElement('img');
				img.onload = function(){
					URL.revokeObjectURL(url);
					var canvas = document.createElement('canvas');
					canvas.width = canvas.height = 128;
					canvas.getContext('2d').drawImage(img, 0, 0, 128, 128);
					$user.find('.avatar_error').html('');
					$('.avatar').fadeTo(200, 0.5);
					pg.rpc('user:avatar', canvas.toDataURL('image/png'), function(err){
						if(err) $user.find('.avatar_error').html(tmpl.error(err));
						else location.reload();
					}, function(){
						$user.find('.avatar_error').html(tmpl.error({ timeout: true }));
					});
				};
				img.src = url;
			});
			$user.find('.avatar_del a').click(function(e){
				e.preventDefault();
				$(this).hide();
				$('.avatar').fadeTo(200, 0.5);
				pg.rpc('user:avatar', '', function(err){
					if(err) $user.find('.avatar_error').html(tmpl.error(err));
					else location.reload();
				});
			});
			$user.find('.avatar').click(function(){
				$user.find('.avatar_file input').click();
			});
			var $form = $user.find('.user_info').on('click', '.info', function(){
				$form.find('.info').hide();
				$form.find('input, textarea').css('display', 'block');
			});
			pg.form($form[0], function(){
				$form.find('.error').html('');
				$form.find('.submit').attr('disabled', true);
			}, function(err){
				$form.find('.submit').attr('disabled', false);
				if(err) $form.find('.error').html(tmpl.error(err));
				else location.reload();
			}, function(){
				$form.find('.submit').attr('disabled', false);
				$form.find('.error').html(tmpl.error({ timeout: true }));
			});
			var $pwdForm = $user.find('.user_password');
			$user.find('.modify_password').click(function(e){
				e.preventDefault();
				$(this).hide();
				$pwdForm.fadeIn(200);
			});
			pg.form($pwdForm[0], function(){
				if($pwdForm.find('.new').val() !== $pwdForm.find('.newRe').val()) {
					$pwdForm.find('.newRe').val('').focus();
					return false;
				}
				$pwdForm.find('[name=password]').val(CryptoJS.SHA256(userInfo.id.toLowerCase() +'|'+ $pwdForm.find('.new').val()));
				$pwdForm.find('[name=original]').val(CryptoJS.SHA256(userInfo.id.toLowerCase() +'|'+ $pwdForm.find('.original').val()));
				$pwdForm.find('.error').html('');
				$pwdForm.find('.submit').attr('disabled', true);
			}, function(err){
				$pwdForm.find('.submit').attr('disabled', false);
				if(err) $pwdForm.find('.error').html(tmpl.error(err));
				else {
					$pwdForm.hide();
					$user.find('.modify_password').fadeIn(200);
				}
			}, function(){
				$pwdForm.find('.submit').attr('disabled', false);
				$pwdForm.find('.error').html(tmpl.error({ timeout: true }));
			});

		}
	};

	if(pg.parent.userInfo) {
		showPage();
	} else {
		pg.parent.on('userInfoReady', showPage);
	}
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ReactiveRTM.RTC;
using ReactiveRTM.Component;
using ReactiveRTM.Port;
using ReactiveRTM.Management;

/// <summary>
/// データポートからの入力データをコンソールに出力する
/// </summary>
class Program
{
    public static void Main(string[] args)
    {
        using (var manager = new RtcManager(args))
        {
            var comp = new ConsoleOut();

            manager.RegisterComponent(comp);

            manager.Run();
        }
    }
}

class ConsoleOut : ReactiveComponent
{
    private ReactiveInPort<TimedLong> _inport = new ReactiveInPort<TimedLong>("in");

    public ConsoleOut()
        : base("ConsoleOut")
    {
        AddPort(_inport);
    }

    private IDisposable _disposer;
    protected override ReturnCode_t OnActivated(int execHandle)
    {
        _disposer = _inport.Subscribe(x => Console.WriteLine(x.Data));

        return ReturnCode_t.RTC_OK;
    }

    protected override ReturnCode_t OnDeactivated(int execHandle)
    {
        _disposer.Dispose();
        return ReturnCode_t.RTC_OK;
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;

namespace System.IO
{
    public enum FileEnumFlags
    {
        Files = 0x0001,
        Directories = 0x0002,
        FilesAndDirectories = Files | Directories,
    }

    public class FileEnum : IEnumerator, IDisposable
    {
        private NativeFindFile  m_findFile;
        private NativeFileInfo  m_currentFile;
        private FileEnumFlags   m_flags;
        private string          m_path;
        private bool            m_disposed;
        private object          m_openForReadHandle;

        public FileEnum(string path, FileEnumFlags flags)
        {
            m_flags = flags;
            m_path  = path;

            m_openForReadHandle = FileSystemManager.AddToOpenListForRead(m_path);
            m_findFile          = new NativeFindFile(m_path, "*");
        }

        #region IEnumerator Members

        public object Current
        {
            get
            {
                if (m_disposed)
#if EXCEPTION_STRINGS
                    throw new ObjectDisposedException("");
#else
                    throw new ObjectDisposedException(null);
#endif

                return Path.Combine(m_path, m_currentFile.FileName);
            }
        }

        public bool MoveNext()
        {
            if (m_disposed)
#if EXCEPTION_STRINGS
                throw new ObjectDisposedException("");
#else
                throw new ObjectDisposedException(null);
#endif

            NativeFileInfo fileinfo = m_findFile.GetNext();

            while (fileinfo != null)
            {
                if (m_flags != FileEnumFlags.FilesAndDirectories)
                {
                    uint targetAttribute = (0 != (m_flags & FileEnumFlags.Directories) ? (uint)FileAttributes.Directory : 0);

                    if ((fileinfo.Attributes & (uint)FileAttributes.Directory) == targetAttribute)
                    {
                        m_currentFile = fileinfo;
                        break;
                    }
                }
                else
                {
                    m_currentFile = fileinfo;
                    break;
                }

                fileinfo = m_findFile.GetNext();
            }

            if (fileinfo == null)
            {
                m_findFile.Close();
                m_findFile = null;

                FileSystemManager.RemoveFromOpenList(m_openForReadHandle);
                m_openForReadHandle = null;
            }

            return fileinfo != null;
        }

        public void Reset()
        {
            if (m_disposed)
#if EXCEPTION_STRINGS
                throw new ObjectDisposedException("");
#else
                throw new ObjectDisposedException(null);
#endif

            if (m_findFile != null)
            {
                m_findFile.Close();
            }

            if(m_openForReadHandle == null)
            {
                m_openForReadHandle = FileSystemManager.AddToOpenListForRead(m_path);
            }

            m_findFile = new NativeFindFile(m_path, "*");
        }

        #endregion

        protected virtual void Dispose(bool disposing)
        {
            if (m_findFile != null)
            {
                m_findFile.Close();
                m_findFile = null;
            }

            if (m_openForReadHandle != null)
            {
                FileSystemManager.RemoveFromOpenList(m_openForReadHandle);
                m_openForReadHandle = null;
            }

            m_disposed = true;
        }

        ~FileEnum()
        {
            Dispose(false);
        }

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }

    public class FileEnumerator : IEnumerable
    {
        private string m_path;
        private FileEnumFlags m_flags;

        public FileEnumerator(string path, FileEnumFlags flags)
        {
            m_path  = Path.GetFullPath(path);
            m_flags = flags;

            if (!Directory.Exists(m_path))
#if EXCEPTION_STRINGS
                throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound);
#else
                throw new IOException();
#endif
        }

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            return new FileEnum(m_path, m_flags);
        }

        #endregion
    }
}


text:
#pragma once
#include <aws/migrationhubstrategy/MigrationHubStrategyRecommendations_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace MigrationHubStrategyRecommendations
{
namespace Model
{
  class AWS_MIGRATIONHUBSTRATEGYRECOMMENDATIONS_API StartAssessmentResult
  {
  public:
    StartAssessmentResult();
    StartAssessmentResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    StartAssessmentResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     * <p> The ID of the assessment. </p>
     */
    inline const Aws::String& GetAssessmentId() const{ return m_assessmentId; }

    /**
     * <p> The ID of the assessment. </p>
     */
    inline void SetAssessmentId(const Aws::String& value) { m_assessmentId = value; }

    /**
     * <p> The ID of the assessment. </p>
     */
    inline void SetAssessmentId(Aws::String&& value) { m_assessmentId = std::move(value); }

    /**
     * <p> The ID of the assessment. </p>
     */
    inline void SetAssessmentId(const char* value) { m_assessmentId.assign(value); }

    /**
     * <p> The ID of the assessment. </p>
     */
    inline StartAssessmentResult& WithAssessmentId(const Aws::String& value) { SetAssessmentId(value); return *this;}

    /**
     * <p> The ID of the assessment. </p>
     */
    inline StartAssessmentResult& WithAssessmentId(Aws::String&& value) { SetAssessmentId(std::move(value)); return *this;}

    /**
     * <p> The ID of the assessment. </p>
     */
    inline StartAssessmentResult& WithAssessmentId(const char* value) { SetAssessmentId(value); return *this;}

  private:

    Aws::String m_assessmentId;
  };

} // namespace Model
} // namespace MigrationHubStrategyRecommendations
} // namespace Aws


text:
{% extends 'analyses/new_analysis_base.html' %}

{% load crispy_forms_tags crispy_forms_filters static compress %}

{% block title %}New RNA-Seq Analysis{% endblock %}

{% block content %}

New RNA-Seq Analysis

	{% crispy form %}
{% endblock %}

{% block scripts %}
{{ block.super }}
{% compress js %}

{% endcompress %}
{% endblock scripts %}


text:
package org.apache.bcel.util;

import org.apache.bcel.classfile.JavaClass;

/**
 * Abstract definition of a class repository. Instances may be used
 * to load classes from different sources and may be used in the
 * Repository.setRepository method.
 *
 * @see org.apache.bcel.Repository
 * @version $Id: Repository.java 386056 2006-03-15 11:31:56Z tcurdt $
 * @author M. Dahm
 * @author David Dixon-Peugh
 */
public interface Repository extends java.io.Serializable {

    /**
     * Store the provided class under "clazz.getClassName()"
     */
    public void storeClass( JavaClass clazz );

    /**
     * Remove class from repository
     */
    public void removeClass( JavaClass clazz );

    /**
     * Find the class with the name provided, if the class
     * isn't there, return NULL.
     */
    public JavaClass findClass( String className );

    /**
     * Find the class with the name provided, if the class
     * isn't there, make an attempt to load it.
     */
    public JavaClass loadClass( String className ) throws java.lang.ClassNotFoundException;

    /**
     * Find the JavaClass instance for the given run-time class object
     */
    public JavaClass loadClass( Class clazz ) throws java.lang.ClassNotFoundException;

    /** Clear all entries from cache.
     */
    public void clear();

    /** Get the ClassPath associated with this Repository
     */
    public ClassPath getClassPath();
}


text:
@extends('default')

@section('title') {{{ $caption }}} :: @parent @stop

@section('link')
@parent
<link rel="stylesheet" type="text/css" href="{{ $root }}/js/plugins/datatables/css/dataTables.bootstrap.css">
@stop

@section('content')
@include('topbar')

   @include('list.header', ['buttons' => ['passive' => lang('admin.button.make_passive', 'Pasifleştir')]])

    @if (isset($list) && $list->total)

         <input type="checkbox" name="check-all" value="all">

       #ID
       @lang('admin.label.created_at', 'Oluşturma')
       @lang('admin.label.group_name', 'Grup Adı')
       @lang('admin.label.role', 'Rolü')
       @lang('admin.label.total_members', 'Üye Sayısı')
       @lang('admin.label.status', 'Durum')

      @foreach ($list->rows as $row)

         <input type="checkbox" name="check[]" value="{{ $row->id }}">

       {{ $row->id }}
       created_at) }}" title="{{{ date_show($row->created_at, 'long', true) }}}">{{{ date_ago($row->created_at) }}}
       name }}">
        id)">{{{ $row->first_name }}}

       {{{ $row->role }}}
       {{{ $row->totalMembers }}}

         <button type="button" class="btn btn-{{ $row->active ? 'primary' : 'inverse' }} btn-xs br2 dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
          {{{ $row->status }}}

         </button>

           id)">@lang('admin.button.edit', 'Düzenle')

           id }}">@lang('admin.button.delete', 'Sil')

           id }}">@lang('admin.button.passive', 'Pasifleştir')

      @endforeach

    @else
    @include('list.empty')
    @endif

  <form id="filter-form" class="p15 admin-form" method="post" action="@url()">

@lang('admin.label.filters', 'Filtreler')

     <input type="text" id="filter-id" name="filter-id" class="gui-input" placeholder="# ID">

@lang('admin.label.role', 'Rolü')

     <select id="filter-role" name="filter-role">
      <option value="0" selected="selected">@lang('admin.label.filter_by_role', 'Role Göre Filtrele')</option>
      @foreach ($roles as $roleId => $roleTitle)
      <option value="{{ $roleId }}">{{{ $roleTitle }}}</option>
      @endforeach
     </select>

@lang('admin.label.group', 'Grup')

     <input type="text" id="filter-title" name="filter-title" class="gui-input">

     <button type="submit" class="btn btn-default btn-sm ph25">
      @lang('admin.button.filter', 'Filtrele')
     </button>

  </form>

@include('list.delete', ['url' => url($prefix . 'system/groups/form')])
@stop

@section('script')
@parent

@stop


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
    JBoss, Home of Professional Open Source
    Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
    contributors by the @authors tag. See the copyright.txt in the
    distribution for a full listing of individual contributors.

    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>
    <groupId>org.jboss.quickstarts.eap</groupId>
    <artifactId>jboss-picketlink-sts</artifactId>
    <version>7.0.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>JBoss EAP Quickstart: picketlink-sts</name>
    <description>This project is an implementation of a WS-Trust Security Token Service.</description>
    <url>http://www.jboss.org/products/eap</url>

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

    <!-- Activate JBoss Product Maven repository.

        NOTE: Configuring the Maven repository in the pom.xml file is not a recommended procedure
        and is only done here to make it easier to use the quickstarts.

        For more information about how to configure Maven for your application,
        see the section entitled 'Use the Maven Repository'
        in the Development Guide for Red Hat JBoss Enterprise Application Platform located here:

        https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/
    -->
    <repositories>
        <repository>
            <id>jboss-developer-staging-repository</id>
            <url>http://jboss-developer.github.io/temp-maven-repo/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>jboss-developer-staging-repository</id>
            <url>http://jboss-developer.github.io/temp-maven-repo/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <!-- Explicitly declaring the source encoding eliminates the following message: -->
        <!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
                         resources, i.e. build is platform dependent! -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!-- JBoss dependency versions -->

        <!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
        <version.jboss.bom.eap>7.0.0-build-7</version.jboss.bom.eap>

        <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>

        <!-- other plug-in versions -->
        <version.war.plugin>2.1.1</version.war.plugin>
        <version.exec.plugin>1.2.1</version.exec.plugin>

        <!-- maven-compiler-plugin -->
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- Define the version of the JBoss Java EE APIs we want to use -->
            <!-- JBoss distributes a complete set of Java EE APIs including
                                 a Bill of Materials (BOM). A BOM specifies the versions of a "stack" (or
                a collection) of artifacts. We use this here so that we always get the correct
                versions of artifacts. Here we use the jboss-javaee-7.0 stack (you can
                read this as the JBoss stack of the Java EE APIs). You can actually
                use this stack with any version of JBoss EAP that implements Java EE. -->
            <dependency>
                <groupId>org.jboss.bom</groupId>
                <artifactId>jboss-javaee-7.0-eap-with-tools</artifactId>
                <version>${version.jboss.bom.eap}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.picketlink</groupId>
            <artifactId>picketlink</artifactId>
            <scope>provided</scope>
            <exclusions>
              <exclusion>
                <groupId>org.jboss.security</groupId>
                <artifactId>jbossxacml</artifactId>
              </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.picketlink</groupId>
            <artifactId>picketlink-common</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.picketlink</groupId>
            <artifactId>picketlink-federation</artifactId>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <!-- Set the name of the WAR, used as the context root when the app
                         is deployed -->
        <finalName>${project.artifactId}</finalName>
        <plugins>

            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-war-plugin</artifactId>
              <version>${version.war.plugin}</version>
              <configuration>
                <packagingExcludes>WEB-INF/classes/org/jboss/**</packagingExcludes>
              </configuration>
            </plugin>

            <!-- WildFly plug-in to deploy the WAR -->
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>${version.wildfly.maven.plugin}</version>
            </plugin>

            <!-- exec maven plug-in to execute client to show how to get security token from PicketLink STS  -->
            <plugin>
              <groupId>org.codehaus.mojo</groupId>
              <artifactId>exec-maven-plugin</artifactId>
                <version>${version.exec.plugin}</version>
              <executions>
                <execution>
                  <goals>
                    <goal>java</goal>
                  </goals>
                </execution>
              </executions>
              <configuration>
                <classpathScope>test</classpathScope>
                <mainClass>org.jboss.as.quickstarts.picketlink.WSTrustClientExample</mainClass>
                <executable>java</executable>
                <arguments>
                  <argument>UserA</argument>
                  <argument>PassA</argument>
                </arguments>
              </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verrucaria osloensis H. Magn.

### Remarks
null


text:
package com.afwsamples.testdpc.policy;

import android.annotation.TargetApi;
import android.app.AlertDialog.Builder;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.ArraySet;
import android.view.View;
import android.widget.EditText;
import androidx.preference.Preference;
import com.afwsamples.testdpc.DeviceAdminReceiver;
import com.afwsamples.testdpc.R;
import com.afwsamples.testdpc.common.BaseSearchablePolicyPreferenceFragment;
import com.afwsamples.testdpc.common.preference.DpcPreference;
import com.afwsamples.testdpc.common.preference.DpcSwitchPreference;
import com.google.common.base.Joiner;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;

@TargetApi(VERSION_CODES.Q)
public class CrossProfileCalendarFragment extends BaseSearchablePolicyPreferenceFragment
    implements Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {

  private static final String CROSS_PROFILE_CALENDAR_SET_ALLOWED_PACKAGES_KEY =
      "cross_profile_calendar_set_allowed_packages";
  private static final String CROSS_PROFILE_CALENDAR_ALLOW_ALL_PACKAGES_KEY =
      "cross_profile_calendar_allow_all_packages";

  private DevicePolicyManager mDevicePolicyManager;

  private ComponentName mAdminComponentName;
  private DpcPreference mSetAllowedPackagesPreference;
  private DpcSwitchPreference mAllowAllPackagesPreference;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    mDevicePolicyManager = getActivity().getSystemService(DevicePolicyManager.class);
    mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
    getActivity().getActionBar().setTitle(R.string.cross_profile_calendar);
    super.onCreate(savedInstanceState);
  }

  @Override
  public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    addPreferencesFromResource(R.xml.cross_profile_calendar_preferences);

    mSetAllowedPackagesPreference =
        (DpcPreference) findPreference(CROSS_PROFILE_CALENDAR_SET_ALLOWED_PACKAGES_KEY);
    mSetAllowedPackagesPreference.setOnPreferenceClickListener(this);

    mAllowAllPackagesPreference =
        (DpcSwitchPreference) findPreference(CROSS_PROFILE_CALENDAR_ALLOW_ALL_PACKAGES_KEY);
    mAllowAllPackagesPreference.setOnPreferenceChangeListener(this);

    reloadAllowAllPackagesUi();
  }

  @Override
  public boolean isAvailable(Context context) {
    return true;
  }

  @Override
  public boolean onPreferenceClick(Preference preference) {
    String key = preference.getKey();
    switch (key) {
      case CROSS_PROFILE_CALENDAR_SET_ALLOWED_PACKAGES_KEY:
        showSetPackagesDialog();
        return true;
    }
    return false;
  }

  @Override
  public boolean onPreferenceChange(Preference preference, Object newValue) {
    String key = preference.getKey();
    switch (key) {
      case CROSS_PROFILE_CALENDAR_ALLOW_ALL_PACKAGES_KEY:
        mDevicePolicyManager.setCrossProfileCalendarPackages(
            mAdminComponentName, newValue.equals(true) ? null : Collections.emptySet());
        reloadAllowAllPackagesUi();
    }
    return false;
  }

  @TargetApi(VERSION_CODES.Q)
  private void reloadAllowAllPackagesUi() {
    final Set<String> packages =
        mDevicePolicyManager.getCrossProfileCalendarPackages(mAdminComponentName);
    mAllowAllPackagesPreference.setChecked(packages == null);
    mSetAllowedPackagesPreference.setEnabled(!mAllowAllPackagesPreference.isChecked());
  }

  /** Shows a dialog that asks the user for a set of package names to be allowed. */
  private void showSetPackagesDialog() {
    if (getActivity() == null || getActivity().isFinishing()) {
      return;
    }

    final View dialogView =
        getActivity().getLayoutInflater().inflate(R.layout.simple_edittext, null);
    final EditText setPackagesEditText = (EditText) dialogView.findViewById(R.id.input);

    setPackagesEditText.setText(
        Joiner.on(",")
            .join(mDevicePolicyManager.getCrossProfileCalendarPackages(mAdminComponentName)));

    new Builder(getActivity())
        .setTitle(R.string.cross_profile_calendar_set_allowed_packages_title)
        .setView(dialogView)
        .setPositiveButton(
            android.R.string.ok,
            (dialogInterface, i) -> {
              final String packageNamesString = setPackagesEditText.getText().toString();
              final Set<String> packageNames =
                  packageNamesString.isEmpty()
                      ? Collections.emptySet()
                      : new ArraySet<>(
                          Arrays.asList(packageNamesString.replace(" ", "").split(",")));
              mDevicePolicyManager.setCrossProfileCalendarPackages(
                  mAdminComponentName, packageNames);
            })
        .setNegativeButton(android.R.string.cancel, null)
        .show();
  }
}


text:
cmd=$1
docDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # chrmarti: Changed to script's directory.
packageJsonTemplate=$docDir/new_package.json.template
repoJsonTemplate=$docDir/new_repo.json.template

function Bail
{
    echo "ERROR: $@"
    exit 1
}

function BailIfFileMissing {
    file="$1"
    if [ ! -f "$file" ]; then
        Bail "File $file does not exist"
    fi
}

function Usage {
    echo "USAGE: Manage repos and packages in an apt repository"
    echo "$0 -config FILENAME -listrepos | -listpkgs | -addrepo FILENAME | -addpkg FILENAME |"
    echo "-addpkgs FILENAME | -check ID | -delrepo REPOID | -delpkg PKGID"
    echo -e "\t-config FILENAME    :   JSON file containing API server name and creds"
    echo -e "Package Operations:"
    echo -e "\t-listpkgs [REGEX]   :   List packages, optionally filter by REGEX"
    echo -e "\t-addpkg FILENAME    :   Add package to repo using the specified JSON file"
    echo -e "\t-addpkgs FILENAME   :   Add packages to repo using urls contained in FILENAME"
    echo -e "\t-check ID           :   Check upload operation by ID"
    echo -e "\t-delpkg PKGID       :   Delete the specified package by ID"
    echo -e "File Operations:"
    echo -e "\t-uploadfile FILENAME:   Upload FILENAME (does not publish) "
    echo -e "\t-addfile FILENAME   :   Upload FILENAME AND publish to the repo"
    echo -e "\t-listfiles          :   List uploaded files"
    echo -e "\t-delfile FILEID     :   Delete uploaded file by ID"
    echo -e "Repository Operations:"
    echo -e "\t-listrepos          :   List repositories"
    echo -e "\t-addrepo FILENAME   :   Create a new repo using the specified JSON file"
    echo -e "\t-delrepo REPOID     :   Delete the specified repo by ID"
    exit 1
}

function ParseFromJson {
    if [ -z "$secretContents" ]; then
        Bail "Unable to parse value because no JSON contents were specified"
    elif [ -z "$1" ]; then
        Bail "Unable to parse value from JSON because no key was specified"
    fi
    # Write value directly to stdout to be used by caller
    echo $secretContents | jq "$1" | tr -d '"'
}

function ParseConfigFile {
    configFile="$1"
    if [ -z "$configFile" ]; then
        echo "Must specify -config option"
        Usage
    fi
    BailIfFileMissing "$configFile"
    secretContents=$(cat "$configFile")

    server=$(ParseFromJson .server)
    protocol=$(ParseFromJson .protocol)
    port=$(ParseFromJson .port)
    repositoryId=$(ParseFromJson .repositoryId)
    user=$(ParseFromJson .username)
    pass=$(ParseFromJson .password)
    baseurl="$protocol://$user:$pass@$server:$port"
}

# List Repositories
function ListRepositories
{
    echo "Fetching repo list from $server..."
    curl -k "$baseurl/v1/repositories" | sed 's/,/,\n/g' | sed 's/^"/\t"/g'
    echo ""
}

# List packages, using $1 as a regex to filter results
function ListPackages
{
    echo "Fetching package list from $server"
    curl -k "$baseurl/v1/packages" | sed 's/{/\n{/g' | egrep "$1" | sed 's/,/,\n/g' | sed 's/^"/\t"/g'
    echo ""
}

# Create a new Repo using the specified JSON file
function AddRepo
{
    repoFile=$1
    if [ -z $repoFile ]; then
        Bail "Error: Must specify a JSON-formatted file. Reference $repoJsonTemplate"
    fi
    if [ ! -f $repoFile ]; then
        Bail "Error: Cannot create repo - $repoFile does not exist"
    fi
    packageUrl=$(grep "url" $repoFile  | head -n 1 | awk '{print $2}' | tr -d ',')
    echo "Creating new repo on $server [$packageUrl]"
    curl -i -k "$baseurl/v1/repositories" --data @$repoFile -H "Content-Type: application/json"
    echo ""
}

# Upload AND publish the file
function AddFile
{
    packageFile=$1
    # Validity checks are performed by UploadFile
    echo "Uploading package to $server [$packageFile]"
    response=$(UploadFile $packageFile "true")
    id=$(echo $response | jq -r ".id")

    # Parse package metadata first to confirm it's a valid deb/rpm
    # Needs to be performed in this function so we can use it to publish the package
    jsonFile=$(WritePackageInfoToFile $packageFile)

    sed -i "s/REPOSITORYID/$repositoryId/g" $jsonFile
    # Replace the url field with fileId
    sed -i "s/PACKAGEURL/$id/g" $jsonFile
    sed -i "s/sourceUrl/fileId/g" $jsonFile

    AddPackage $jsonFile
    rm -f $jsonFile
    echo ""
}

# Upload a file
function UploadFile
{
    packageFile=$1
    quick=$2
    if [ -z $packageFile ]; then
        Bail "Error: Must specify the path to a file to upload "
    fi
    if [ ! -f $packageFile ]; then
        Bail "Error: Cannot upload - $packageFile does not exist"
    fi

    # Additional validation and output if quick mode isn't enabled
    # Basically, if this is part of a publish operation, these steps are handled elsewhere
    if [ "$quick" != "true" ]; then
        # Parse package metadata first to confirm it's a valid deb/rpm
        jsonFile=$(WritePackageInfoToFile $packageFile)
        rm -f $jsonFile

        echo "Uploading package to $server [$packageFile]"
    fi
    curl -s -k -X POST -F file=@$packageFile "$baseurl/v1/files"
    echo ""
}

function ListFiles
{
    curl -s -k "$baseurl/v1/files" | jq
}

function DeleteFile
{
    fileId=$1
    if [ -z "$fileId" ]; then
        Bail "Error: Must specify an ID to delete"
    fi
    curl -s -X DELETE "$baseurl/v1/files/$fileId"
}

# Upload a single package using the specified JSON file
function AddPackage
{
    packageFile=$1
    if [ -z $packageFile ]; then
        Bail "Error: Must specify a JSON-formatted file. Reference $packageJsonTemplate"
    fi
    if [ ! -f $packageFile ]; then
        Bail "Error: Cannot add package - $packageFile does not exist"
    fi
    packageUrl=$(grep "sourceUrl" $packageFile  | head -n 1 | awk '{print $2}')
    echo "Adding package to $server [$packageUrl]"
    curl -i -k "$baseurl/v1/packages" --data @$packageFile -H "Content-Type: application/json"
    echo ""
}

# Gets the package name and version and writes it to a file
function WritePackageInfoToFile
{
    packageFile=$1
    tmpOut=$(mktemp)
    if [ -z "$packageFile" ]; then
        Bail "Error: Must specify path to a deb/rpm package"
    elif [ ! -f "$packageFile" ]; then
        Bail "Error: Specified file $packageFile does not exist"
    fi
    if dpkg -I $packageFile > $tmpOut 2> /dev/null; then
        >&2 echo "File is deb format"
        pkgName=$(grep "^\s*Package:" $tmpOut | awk '{print $2}')
        pkgVer=$(grep "^\s*Version:" $tmpOut | awk '{print $2}')
    elif rpm -qpi $packageFile > $tmpOut 2> /dev/null; then
        >&2 echo "File is rpm format"
        pkgName=$(egrep "^Name" $tmpOut | tr -d ':' | awk '{print $2}')
        pkgVer=$(egrep "^Version" $tmpOut | tr -d ':' | awk '{print $2}')
    else
        rm -f $tmpOut
        Bail "File is not a valid deb/rpm package $url"
    fi

    rm -f $tmpOut
    if [ -z "$pkgName" ]; then
        Bail "Unable to parse package name for $url"
    elif [ -z "$pkgVer" ]; then
        Bail "Unable to parse package version number for $url"
    fi

    # Create Package .json file
    outJson=$(mktemp)
    escapedUrl=$(echo "$url" | sed 's/\//\\\//g' | sed 's/\&/\\\&/g')
    cp $packageJsonTemplate $outJson
    sed -i "s/PACKAGENAME/$pkgName/g" $outJson
    sed -i "s/PACKAGEVERSION/$pkgVer/g" $outJson

    # Return path to json file
    echo $outJson
}

# Upload a single package by dynamically creating a JSON file using a provided URL
function AddPackageByUrl
{
    url=$(echo "$1")
    if [ -z "$url" ]; then
        Bail "Unable to publish package because no URL was specified"
    fi
    tmpFile=$(mktemp)
    if ! wget -q "$url" -O $tmpFile; then
        rm -f $tmpFile
        Bail "Unable to download URL $url"
    fi

    jsonFile=$(WritePackageInfoToFile $tmpFile)
    # Create Package .json file
    escapedUrl=$(echo "$url" | sed 's/\//\\\//g' | sed 's/\&/\\\&/g')
    sed -i "s/PACKAGEURL/$escapedUrl/g" $jsonFile
    sed -i "s/REPOSITORYID/$repositoryId/g" $jsonFile
    # Perform Upload
    AddPackage $jsonFile
    # Cleanup
    rm -f $jsonFile
}

# Upload multiple packages by reading urls line-by-line from the specified file
function AddPackages
{
    urlFile=$1
    if [ -z $urlFile ]; then
        Bail "Must specify a flat text file containing one or more URLs"
    fi
    if [ ! -f $urlFile ]; then
        Bail "Cannot add packages. File $urlFile does not exist"
    fi
    for url in $(cat $urlFile); do
        if [ -n "$url" ]; then
            AddPackageByUrl "$url"
        fi
        sleep 5
    done
}

# Check upload by ID
function CheckUpload {
    id=$1
    if [ -z "$id" ]; then
        Bail "Must specify an ID"
    fi
    curl -s -k $baseurl/v1/packages/queue/$id | jq
    echo ""
}

# Delete the specified repo
function DeleteRepo
{
    repoId=$1
    if [ -z $repoId ]; then
        Bail "Please specify repository ID. Run -listrepos for a list of IDs"
    fi
    curl -I -k -X DELETE "$baseurl/v1/repositories/$repoId"
}

# Delete the specified package
function DeletePackage
{
    packageId=$1
    if [ -z $packageId ]; then
        Bail "Please specify package ID. Run -listpkgs for a list of IDs"
    fi
    echo Removing pkgId $packageId from repo $repositoryId
    curl -I -k -X DELETE "$baseurl/v1/packages/$packageId"
}

# Parse params
# Not using getopts because this uses multi-char flags
operation=
while (( "$#" )); do
    if [[ "$1" == "-config" ]]; then
        shift
        configFile="$1"
    elif [[ "$1" == "-listrepos" ]]; then
        operation=ListRepositories
    elif [[ "$1" == "-listpkgs" ]]; then
        operation=ListPackages
        if [ -n "$2" ]; then
            shift
            operand="$1"
        fi
    elif [[ "$1" == "-addrepo" ]]; then
        operation=AddRepo
        shift
        operand="$1"
    elif [[ "$1" == "-addpkg" ]]; then
        operation=AddPackage
        shift
        operand="$1"
    elif [[ "$1" == "-addpkgs" ]]; then
        operation=AddPackages
        shift
        operand="$1"
    elif [[ "$1" == "-addfile" ]]; then
        operation=AddFile
        shift
        operand="$1"
    elif [[ "$1" == "-uploadfile" ]]; then
        operation=UploadFile
        shift
        operand="$1"
    elif [[ "$1" == "-listfiles" ]]; then
        operation=ListFiles
    elif [[ "$1" == "-delfile" ]]; then
        operation=DeleteFile
        shift
        operand="$1"
    elif [[ "$1" == "-check" ]]; then
        operation=CheckUpload
        shift
        operand="$1"
    elif [[ "$1" == "-delrepo" ]]; then
        operation=DeleteRepo
        shift
        operand="$1"
    elif [[ "$1" == "-delpkg" ]]; then
        operation=DeletePackage
        shift
        operand="$1"
    else
        Usage
    fi
    shift
done

echo "Performing $operation $operand"
# Parse config file
ParseConfigFile "$configFile"

# Exit if no operation was specified
if [ -z "operation" ]; then
    Usage
fi

$operation "$operand"


text:
package org.pantsbuild.testproject.unicode.unicodedep.provider

object Provider {
  val ε = "epsilon"
}


text:
const defaultState = {
  isLoading: true,
  photos: []
}

export default function userFeedPhotos(state = defaultState, action) {

  switch(action.type) {

  case 'REQUEST_USER_FEED_PHOTOS':
    return Object.assign({}, state, {
      isLoading: true
    })

  case 'RECEIVE_USER_FEED_PHOTOS':
    return Object.assign({}, state, {
      isLoading: false,
      photos: action.userFeedPhotos.result.posts
    })

  default:
    return state

  }

}


text:
use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;

use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;

#[derive(Debug)]
pub struct Entry {
    name: String,
    self_size: u64,
    children: Vec<Entry>,
    is_file: bool,
}

impl Entry {
    pub fn for_path(path: &Path) -> Result<Entry, String> {
        match fs::metadata(path) {
            Ok(metadata) => Entry::from_metadata(path, &metadata),
            Err(error) => Err(utils::describe_io_error(error))
        }
    }

    pub fn from_metadata(path: &Path, metadata: &fs::Metadata) -> Result<Entry, String> {
        let mut children = if metadata.is_dir() {
            Entry::in_directory(path)
        } else if metadata.is_file() {
            vec![]
        } else {
            return Err("not a file or directory".to_string());
        };

        children.sort_by(
            // Note: We change the ordering to get in descending order
            |a, b| b.size().cmp(&a.size())
        );

        Ok(Entry {
            name: utils::short_name_from_path(path, metadata.is_dir()),
            children: children,
            self_size: metadata.len(),
            is_file: metadata.is_file(),
        })
    }

    fn in_directory(dir: &Path) -> Vec<Entry> {
        match fs::read_dir(dir) {
            Ok(read_dir) => {
                read_dir.filter_map(|child| {
                    match child {
                        // TODO: Don't just ignore errors here; we should print them to STDERR and
                        // *then* ignore them.
                        Ok(child) => Entry::for_path(&child.path()).ok(),
                        Err(..) => None,
                    }
                }).collect()
            },
            Err(..) => Vec::new()
        }
    }

    fn descendent_size(&self) -> u64 {
        self.children.iter().map(|child| child.size()).fold(0, |a, n| a + n)
    }
}

impl DisplayableEntry for Entry {
    type Child = Entry;

    fn size(&self) -> u64 {
        self.self_size + self.descendent_size()
    }

    fn name(&self) -> &String {
        &self.name
    }

    fn children_iter(&self) -> Iter<Entry> {
        self.children.iter()
    }

    fn is_file(&self) -> bool {
        self.is_file
    }
}

impl fmt::Display for Entry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.name(), self.size().as_size_display())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use modes::DisplayableEntry;
    use std::path::Path;

    #[test]
    fn it_can_be_constructed_with_a_path() {
        let pwd = Entry::for_path(Path::new(".")).unwrap();

        assert_eq!(pwd.name(), "./");
        assert!(pwd.children_iter().count() > 0);
        assert!(pwd.size() > 0);
    }

    #[test]
    fn it_is_error_when_constructed_from_missing_path() {
        let missing = Entry::for_path(Path::new("./does-not-exist"));
        assert_eq!(missing.is_err(), true);
        assert_eq!(missing.unwrap_err(), "File not found");
    }

    #[test]
    fn it_is_hidden_when_filename_starts_with_a_dot() {
        let hidden = Entry::for_path(Path::new("./.gitignore")).unwrap();
        let normal = Entry::for_path(Path::new("./LICENSE")).unwrap();

        assert_eq!(hidden.is_hidden(), true);
        assert_eq!(normal.is_hidden(), false);
    }

    #[test]
    fn file_entry_has_no_children() {
        let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
        assert_eq!(file.children_iter().count(), 0);
    }

    #[test]
    fn it_can_be_displayed() {
        use utils::SizeDisplay;

        let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
        assert_eq!(format!("{}", file), format!("LICENSE {}", file.size().as_size_display()));
    }

    #[test]
    fn it_calculates_size_from_children() {
        let entry = Entry::for_path(Path::new(".")).unwrap();
        let children_size = entry
            .children_iter()
            .map(|child| child.size())
            .fold(0, |sum, item| sum + item);

        assert!(entry.size() >= children_size);
    }
}


text:
// Copyright (c) 2019 lriki. Distributed under the MIT license.
#pragma once
#include "Common.hpp"
#include "../Graphics/GraphicsResource.hpp"
#include "ShaderHelper.hpp"

namespace ln {
class DiagnosticsManager;
class Texture;
class Shader;
class ShaderConstantBuffer;
class ShaderParameter;
class ShaderTechnique;
class ShaderPass;
class ShaderCompilationProperties;
class GraphicsContext;
namespace detail {
class ShaderHelper;
class ShaderManager;
class UnifiedShader;
class IShaderPass;
class IShaderUniformBuffer;
}

/**
 * シェーダーを表すクラスです。
 *
 * このクラスは DirectX9 ~ 11 世代に提供されていた「エフェクト」と同様の、シェーダーステージをまとめて管理・適用する機能を持っています。
 */
class LN_API Shader final
    : public GraphicsResource
{
public:
    /*
     * 事前コンパイル済みシェーダファイルまたはシェーダプログラムファイルから Shader オブジェクトを作成します。
     *
     * @param[in]   filePath : 入力ファイル名
     *
     * シェーダプログラムファイル の読み込み機能はデバッグを目的として用意されています。
     *
     * シェーダプログラムファイルを読み込むことができるのは、デスクトップターゲットのみです。
     * モバイルターゲット、Web ターゲットでは事前コンパイル済みシェーダファイルのみを読み込むことができます。
     */
    static Ref<Shader> create(const StringRef& filePath, ShaderCompilationProperties* properties = nullptr);

    /*
     * Lumino の独自拡張 (technique 構文など) を使用しない HLSL シェーダをコンパイルし、Shader オブジェクトを作成します。
     *
     * 作成された Shader は、1 つの ShaderTechnique と 1 つの ShaderPass を持ちます。
     */
    static Ref<Shader> create(const StringRef& vertexShaderFilePath, const StringRef& pixelShaderFilePath, ShaderCompilationProperties* properties = nullptr);

    /*
     * 名前を指定してこの Shader に含まれる ShaderParameter を検索します。
     *
     * @param[in]   name : パラメータの名前
     * @return      一致した ShaderParameter。見つからない場合は nullptr。
     *
     * この関数の検索対象は次の通りです。
     * - "_Global" という名前の付いた ShaderConstantBuffer (cbuffer 構文を使用せず、グローバルスコープに直接定義した変数)
     * - texture 型のパラメータ
     *
     * @attention 現在、SamplerState の設定は未サポートです。将来的には、この関数で SamplerState 型のパラメータを検索できるようにする予定です。
     */
    ShaderParameter* findParameter(const StringRef& name) const;

    /*
     * 名前を指定してこの Shader に含まれる ShaderConstantBuffer を検索します。
     *
     * @param[in]   name : 定数バッファの名前
     * @return      一致した ShaderConstantBuffer。見つからない場合は nullptr。
     */
    ShaderConstantBuffer* findConstantBuffer(const StringRef& name) const;

    /*
     * 名前を指定してこの Shader に含まれる ShaderTechnique を検索します。
     *
     * @param[in]   name : 定数バッファの名前
     * @return      一致した ShaderConstantBuffer。見つからない場合は nullptr。
     */
    ShaderTechnique* findTechnique(const StringRef& name) const;

    /** この Shader に含まれる ShaderTechnique を取得します。 */
    Ref<ReadOnlyList<Ref<ShaderTechnique>>> techniques() const;

protected:
    virtual void onDispose(bool explicitDisposing) override;
    virtual void onChangeDevice(detail::IGraphicsDevice* device) override;

LN_CONSTRUCT_ACCESS:
	Shader();
    virtual ~Shader();
    void init();
    void init(const StringRef& filePath, ShaderCompilationProperties* properties = nullptr);
    void init(const StringRef& vertexShaderFilePath, const StringRef& pixelShaderFilePath, ShaderCompilationProperties* properties = nullptr);
    void init(const String& name, Stream* stream);

private:
    detail::ShaderSemanticsManager* semanticsManager() { return &m_semanticsManager; }
    ShaderTechnique* findTechniqueByClass(const detail::ShaderTechniqueClass& techniqueClass) const;
    void createFromStream(Stream* stream, DiagnosticsManager* diag);
	void createFromUnifiedShader(detail::UnifiedShader* unifiedShader, DiagnosticsManager* diag);
    void postInitialize();
    ShaderConstantBuffer* getOrCreateConstantBuffer(detail::IShaderUniformBuffer* buffer);
    ShaderParameter* getOrCreateTextureParameter(const String& name);

    detail::ShaderManager* m_manager;
    String m_name;
    List<Ref<ShaderConstantBuffer>> m_buffers;
    Ref<List<Ref<ShaderTechnique>>> m_techniques;
    List<Ref<ShaderParameter>> m_textureParameters;
    ShaderConstantBuffer* m_globalConstantBuffer;
    detail::ShaderSemanticsManager m_semanticsManager;

    friend class ShaderPass;
    friend class detail::ShaderHelper;
};

/**
 * シェーダプログラムに含まれる 1 つの入力パラメーターを表します。
 */
class LN_API ShaderParameter final
    : public Object
{
public:
    /** パラメータの名前を取得します。 */
    const String& name() const { return m_name; }

    /** bool 値を設定します。 */
    void setBool(bool value);

    /** 整数値を設定します。 */
    void setInt(int value);

    /** 整数値の配列を設定します。 */
    void setIntArray(const int* value, int count);

    /** 浮動小数点値を設定します。 */
    void setFloat(float value);

    /** 浮動小数点値の配列を設定します。 */
    void setFloatArray(const float* value, int count);

    /** ベクトルを設定します。 */
    void setVector(const Vector4& value);

    /** ベクトルの配列を設定します。 */
    void setVectorArray(const Vector4* value, int count);

    /** 行列を設定します。 */
    void setMatrix(const Matrix& value);

    /** 行列の配列を設定します。 */
    void setMatrixArray(const Matrix* value, int count);

    /** テクスチャを設定します。 */
    void setTexture(Texture* value);

protected:
    virtual void onDispose(bool explicitDisposing) override;

private:
    LN_INTERNAL_NEW_OBJECT;
    ShaderParameter();
    virtual ~ShaderParameter() = default;
    void init(ShaderConstantBuffer* owner, const detail::ShaderUniformTypeDesc& desc, const String& name);
    void init(ShaderParameterClass parameterClass, const String& name);

    const detail::ShaderUniformTypeDesc& desc() const { return m_desc; }
    const Ref<Texture>& texture() const { return m_textureValue; }

    ShaderConstantBuffer* m_owner;
    ShaderParameterClass m_class;
    detail::ShaderUniformTypeDesc m_desc;
    String m_name;
    Ref<Texture> m_textureValue;

    friend class Shader;
    friend class ShaderPass;
    friend class detail::ShaderValueSerializer;
};

/**
 * シェーダプログラムに含まれる 1 つの定数バッファを表します。
 */
class LN_API ShaderConstantBuffer final
    : public Object
{
public:
    /** 定数バッファの名前を取得します。 */
    const String& name() const { return m_name; }

    /** 定数バッファにデータを設定します。通常、シェーダプログラムで定義したレイアウトと同じ構造体を転送します。 */
    void setData(const void* data, int size);

    /** 定数バッファのバイトサイズを取得します。 */
    int size() const { return m_buffer.size(); }

    /*
     * 名前を指定してこの定数バッファに含まれる ShaderParameter を検索します。
     *
     * @param[in]   name : パラメータの名前
     * @return      一致した ShaderParameter。見つからない場合は nullptr。
     */
    ShaderParameter* findParameter(const StringRef& name) const;

private:
    LN_INTERNAL_NEW_OBJECT;
    ShaderConstantBuffer();
    virtual ~ShaderConstantBuffer() = default;
    void init(Shader* owner, detail::IShaderUniformBuffer* rhiObject);

    Shader* owner() const { return m_owner; }
    const std::string& asciiName() const { return m_asciiName; }
    ByteBuffer& buffer() { return m_buffer; }
    void commit(GraphicsContext* graphicsContext, detail::IShaderUniformBuffer* rhiObject);

    Shader* m_owner;
    String m_name;
    std::string m_asciiName;
    ByteBuffer m_buffer;
    List<Ref<ShaderParameter>> m_parameters;

    friend class Shader;
    friend class ShaderParameter;
    friend class ShaderPass;
};

/**
 * シェーダプログラムに含まれる 1 つのテクニックを表します。
 */
class LN_API ShaderTechnique final
    : public Object
{
public:
    /** この ShaderPass が含まれている Shader を取得します。 */
    Shader* shader() const { return m_owner; }

    /** テクニックの名前を取得します。 */
    const String& name() const { return m_name; }

    /** このテクニックに含まれる ShaderPass を取得します。 */
    Ref<ReadOnlyList<Ref<ShaderPass>>> passes() const;

private:
    LN_INTERNAL_NEW_OBJECT;
    ShaderTechnique();
    virtual ~ShaderTechnique();
    void init(const String& name);

    void setOwner(Shader* owner) { m_owner = owner; }
    void addShaderPass(ShaderPass* pass);

    Shader* m_owner;
    String m_name;
    Ref<List<Ref<ShaderPass>>> m_passes;
    detail::ShaderTechniqueClass m_techniqueClass;

    friend class Shader;
    friend class ShaderPass;
    friend class detail::ShaderHelper;
};

/**
 * シェーダプログラムに含まれる 1 つのパスを表します。
 */
class LN_API ShaderPass final
    : public Object
{
public:
    /** この ShaderPass が含まれている Shader を取得します。 */
    Shader* shader() const;

    /** パスの名前を取得します。 */
    const String& name() const { return m_name; }

protected:
    virtual void onDispose(bool explicitDisposing) override;

private:
    LN_INTERNAL_NEW_OBJECT;
    ShaderPass();
    virtual ~ShaderPass();
    void init(const String& name, detail::IShaderPass* rhiPass, detail::ShaderRenderState* renderState = nullptr);

    struct ConstantBufferEntry
    {
        ShaderConstantBuffer* buffer;
        Ref<detail::IShaderUniformBuffer> rhiObject;
    };

    void setOwner(ShaderTechnique* owner) { m_owner = owner; }
    void setupParameters();
    void commitContantBuffers(GraphicsContext* graphicsContext, bool* outModified);
    detail::IShaderPass* resolveRHIObject(GraphicsContext* graphicsContext, bool* outModified);

    ShaderTechnique* m_owner;
    String m_name;
    Ref<detail::IShaderPass> m_rhiPass;
    List<ConstantBufferEntry> m_bufferEntries;
    List<ShaderParameter*> m_textureParameters;
    Ref<detail::ShaderRenderState> m_renderState;

    friend class Shader;
    friend class ShaderTechnique;
    friend class detail::ShaderValueSerializer;
    friend class GraphicsContext;
    friend class detail::ShaderHelper;
};

class ShaderCompilationProperties
    : public Object
{
public:
    void addIncludeDirectory(const StringRef& value);
    void addDefinition(const StringRef& value);
    void setDiagnostics(DiagnosticsManager* diag);

    LN_CONSTRUCT_ACCESS : ShaderCompilationProperties();
    virtual ~ShaderCompilationProperties();
    void init();

private:
    List<String> m_includeDirectories;
    List<String> m_definitions;
    Ref<DiagnosticsManager> m_diag;

    friend class Shader;
};

} // namespace ln


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

import com.facebook.presto.Session;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.scalar.ScalarFunctionImplementation;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.Iterables;

import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.List;

import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.sql.relational.Expressions.call;
import static com.facebook.presto.sql.relational.Expressions.constant;
import static com.facebook.presto.sql.relational.Expressions.constantNull;
import static com.facebook.presto.sql.relational.Signatures.CAST;
import static com.facebook.presto.sql.relational.Signatures.COALESCE;
import static com.facebook.presto.sql.relational.Signatures.IF;
import static com.facebook.presto.sql.relational.Signatures.IN;
import static com.facebook.presto.sql.relational.Signatures.IS_NULL;
import static com.facebook.presto.sql.relational.Signatures.NULL_IF;
import static com.facebook.presto.sql.relational.Signatures.SWITCH;
import static com.facebook.presto.sql.relational.Signatures.TRY_CAST;
import static com.facebook.presto.util.ImmutableCollectors.toImmutableList;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.instanceOf;

public class ExpressionOptimizer
{
    private final FunctionRegistry registry;
    private final TypeManager typeManager;
    private final ConnectorSession session;

    public ExpressionOptimizer(FunctionRegistry registry, TypeManager typeManager, Session session)
    {
        this.registry = registry;
        this.typeManager = typeManager;
        this.session = session.toConnectorSession();
    }

    public RowExpression optimize(RowExpression expression)
    {
        return expression.accept(new Visitor(), null);
    }

    private class Visitor
            implements RowExpressionVisitor<Void, RowExpression>
    {
        @Override
        public RowExpression visitInputReference(InputReferenceExpression reference, Void context)
        {
            return reference;
        }

        @Override
        public RowExpression visitConstant(ConstantExpression literal, Void context)
        {
            return literal;
        }

        @Override
        public RowExpression visitCall(CallExpression call, Void context)
        {
            ScalarFunctionImplementation function;
            Signature signature = call.getSignature();

            if (signature.getName().equals(CAST)) {
                Signature functionSignature = registry.getCoercion(call.getArguments().get(0).getType(), call.getType());
                function = registry.getScalarFunctionImplementation(functionSignature);
            }
            else {
                switch (signature.getName()) {
                    // TODO: optimize these special forms
                    case IF:
                        checkState(call.getArguments().size() == 3, "IF function should have 3 arguments. Get " + call.getArguments().size());
                        RowExpression optimizedOperand = call.getArguments().get(0).accept(this, context);
                        if (optimizedOperand instanceof ConstantExpression) {
                            ConstantExpression constantOperand = (ConstantExpression) optimizedOperand;
                            checkState(constantOperand.getType().equals(BOOLEAN), "Operand of IF function should be BOOLEAN type. Get type " + constantOperand.getType().getDisplayName());
                            if (Boolean.TRUE.equals(constantOperand.getValue())) {
                                return call.getArguments().get(1).accept(this, context);
                            }
                            // FALSE and NULL
                            else {
                                return call.getArguments().get(2).accept(this, context);
                            }
                        }
                    case NULL_IF:
                    case SWITCH:
                    case "WHEN":
                    case TRY_CAST:
                    case IS_NULL:
                    case "IS_DISTINCT_FROM":
                    case COALESCE:
                    case "AND":
                    case "OR":
                    case IN:
                        List<RowExpression> arguments = call.getArguments().stream()
                                .map(argument -> argument.accept(this, null))
                                .collect(toImmutableList());
                        return call(signature, call.getType(), arguments);
                    default:
                        function = registry.getScalarFunctionImplementation(signature);
                }
            }

            List<RowExpression> arguments = call.getArguments().stream()
                    .map(argument -> argument.accept(this, context))
                    .collect(toImmutableList());

            if (Iterables.all(arguments, instanceOf(ConstantExpression.class)) && function.isDeterministic()) {
                MethodHandle method = function.getMethodHandle();

                if (method.type().parameterCount() > 0 && method.type().parameterType(0) == ConnectorSession.class) {
                    method = method.bindTo(session);
                }

                int index = 0;
                List<Object> constantArguments = new ArrayList<>();
                for (RowExpression argument : arguments) {
                    Object value = ((ConstantExpression) argument).getValue();
                    // if any argument is null, return null
                    if (value == null && !function.getNullableArguments().get(index)) {
                        return constantNull(call.getType());
                    }
                    constantArguments.add(value);
                    index++;
                }

                try {
                    return constant(method.invokeWithArguments(constantArguments), call.getType());
                }
                catch (Throwable e) {
                    if (e instanceof InterruptedException) {
                        Thread.currentThread().interrupt();
                    }
                    // Do nothing. As a result, this specific tree will be left untouched. But irrelevant expressions will continue to get evaluated and optimized.
                }
            }

            return call(signature, typeManager.getType(signature.getReturnType()), arguments);
        }
    }
}


text:
package com.google.errorprone.bugpatterns;

import static org.junit.Assume.assumeTrue;

import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.util.RuntimeVersion;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** {@link PrivateConstructorForUtilityClass} Test */
@RunWith(JUnit4.class)
public final class PrivateConstructorForUtilityClassTest {
  private final BugCheckerRefactoringTestHelper testHelper =
      BugCheckerRefactoringTestHelper.newInstance(
          PrivateConstructorForUtilityClass.class, getClass());

  @Test
  public void emptyClassesGetLeftAlone() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void privateClassesGetLeftAlone() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  private static class Blah {",
            "    static void blah() {}",
            "  }",
            "  private Test() {}",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void subClassesGetLeftAlone() {
    testHelper
        .addInputLines(
            "in/Foo.java", //
            "public class Foo<E> {",
            "  private E entity;",
            "  public E getEntity() {",
            "    return entity;",
            "  }",
            "  public void setEntity(E anEntity) {",
            "    entity = anEntity;",
            "  }",
            "  public static class BooleanFoo extends Foo<Boolean> {",
            "    private static final long serialVersionUID = 123456789012L;",
            "  }",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void implementingClassesGetLeftAlone() {
    testHelper
        .addInputLines(
            "in/Foo.java", //
            "import java.io.Serializable;",
            "public class Foo {",
            "  private int entity;",
            "  public int getEntity() {",
            "    return entity;",
            "  }",
            "  public void setEntity(int anEntity) {",
            "    entity = anEntity;",
            "  }",
            "  public static class Bar implements Serializable {",
            "    private static final long serialVersionUID = 123456789012L;",
            "  }",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void privateScopedClassesGetLeftAlone() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  private static class Blah {",
            "    static class Bleh {",
            "      static void bleh() {}",
            "    }",
            "  }",
            "  private Test() {}",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void utilityClassesGetAPrivateConstructor_onlyFields() {
    testHelper
        .addInputLines(
            "in/Test.java",
            "",
            "final class Test {",
            "  static final String SOME_CONSTANT = \"\";",
            "}")
        .addOutputLines(
            "out/Test.java",
            "",
            "final class Test {",
            "  static final String SOME_CONSTANT = \"\";",
            "  private Test() {}",
            "}")
        .doTest();
  }

  @Test
  public void utilityClassesGetAPrivateConstructor_onlyMethods() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  static void blah() {}",
            "}")
        .addOutputLines(
            "out/Test.java",
            "",
            "final class Test {",
            "  static void blah() {}",
            "  private Test() {}",
            "}")
        .doTest();
  }

  @Test
  public void utilityClassesGetAPrivateConstructor_onlyNestedClasses() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  static class Blah {}",
            "}")
        .addOutputLines(
            "out/Test.java",
            "",
            "final class Test {",
            "  static class Blah {}",
            "  private Test() {}",
            "}")
        .doTest();
  }

  @Test
  public void utilityClassesGetAPrivateConstructor_onlyStaticInitializer() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  static {}",
            "}")
        .addOutputLines(
            "out/Test.java", //
            "final class Test {",
            "  static {}",
            "  private Test() {}",
            "}")
        .doTest();
  }

  @Test
  public void utilityClassesWithAConstructorGetLeftAlone() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  static void blah() {}",
            "  Test() {}",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void otherClassesGetLeftAlone_field() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  private Object blah;",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void otherClassesGetLeftAlone_method() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  void blah() {}",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void otherClassesGetLeftAlone_innerClass() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  class Blah {}",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void otherClassesGetLeftAlone_initializer() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  {}",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void otherClassesGetLeftAlone_constructor() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "final class Test {",
            "  Test() {}",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void otherClassesGetLeftAlone_interface() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "interface Test {",
            "  void blah();",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void otherClassesGetLeftAlone_enum() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "enum Test {",
            "  INSTANCE;",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void b30170662() {
    CompilationTestHelper.newInstance(PrivateConstructorForUtilityClass.class, getClass())
        .addSourceLines(
            "Foo.java",
            "// BUG: Diagnostic contains:",
            "public class Foo {",
            "  enum Enum {}",
            "  @interface Annotation {}",
            "  interface Interface {}",
            "}")
        .doTest();
  }

  @Test
  public void ignoreTestClasses() {
    testHelper
        .addInputLines(
            "in/Test.java",
            "import org.junit.runner.RunWith;",
            "import org.junit.runners.JUnit4;",
            "@RunWith(JUnit4.class)",
            "final class Test {",
            "  @RunWith(JUnit4.class)",
            "  private static class Blah {",
            "    static void blah() {}",
            "  }",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void finalAdded() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "",
            "class Test {",
            "  static final String SOME_CONSTANT = \"\";",
            "}")
        .addOutputLines(
            "out/Test.java",
            "",
            "final class Test {",
            "  static final String SOME_CONSTANT = \"\";",
            "  private Test() {}",
            "}")
        .doTest();
  }

  @Test
  public void abstractClass_noPrivateConstructor() {
    testHelper
        .addInputLines(
            "in/Test.java", //
            "",
            "abstract class Test {",
            "  static final String SOME_CONSTANT = \"\";",
            "}")
        .expectUnchanged()
        .doTest();
  }

  @Test
  public void record() {
    assumeTrue(RuntimeVersion.isAtLeast16());
    CompilationTestHelper.newInstance(PrivateConstructorForUtilityClass.class, getClass())
        .addSourceLines(
            "ExampleUtilityClass.java",
            "package example;",
            "// BUG: Diagnostic contains:",
            "public final class ExampleUtilityClass {",
            "  public record SomeRecord(String value) {}",
            "}")
        .doTest();
  }
}


text:
define({
  "businessAnalyst": "Business Analyst",
  "defineWhichInfographics": "Definir infografia disponível no widget:",
  "defineWhichReports": "Definir relatórios disponíveis no widget:",
  "defaultValues": "Valores predefinidos:",
  "disable": "Desativar",
  "driveTime": "Tempo de condução",
  "infographics": "Infográficos",
  "invalidValueRing": "Os valores devem estar no intervalo de 0 a 1000.",
  "invalidValueDTWT": "Os valores devem estar no intervalo de 0 a 300.",
  "km": "km",
  "miles": "milhas",
  "minutes": "minutos",
  "radius": "Raio",
  "reports": "Relatórios",
  "rings": "Anéis",
  "selectCountry": "Selecionar país:",
  "thisEntryIsNotValid": "Esta entrada não é válida.",
  "time": "Hora",
  "walkTime": "Tempo de Caminhada"
});


text:
package k8sTest

import (
	"fmt"

	. "github.com/onsi/gomega"

	. "github.com/cilium/cilium/test/ginkgo-ext"
	"github.com/cilium/cilium/test/helpers"
)

var _ = SkipDescribeIf(helpers.DoesNotRunOnNetNextKernel, "K8sBandwidthTest", func() {
	var (
		kubectl        *helpers.Kubectl
		ciliumFilename string
		demoYAML       string
	)

	BeforeAll(func() {
		kubectl = helpers.CreateKubectl(helpers.K8s1VMName(), logger)

		ciliumFilename = helpers.TimestampFilename("cilium.yaml")

		demoYAML = helpers.ManifestGet(kubectl.BasePath(), "demo_bw.yaml")
		res := kubectl.ApplyDefault(demoYAML)
		res.ExpectSuccess("Unable to apply %s", demoYAML)
	})

	AfterAll(func() {
		kubectl.Delete(demoYAML)
		ExpectAllPodsTerminated(kubectl)

		UninstallCiliumFromManifest(kubectl, ciliumFilename)
		ExpectAllPodsTerminated(kubectl)

		kubectl.CloseSSHClient()
	})

	Context("Checks Bandwidth Rate-Limiting", func() {
		const (
			testDS10       = "run=netperf-10"
			testDS25       = "run=netperf-25"
			testClientPod  = "run=netperf-client-pod"
			testClientHost = "run=netperf-client-host"

			maxRateDeviation = 5
			minBandwidth     = 1
		)

		var (
			podLabels = []string{
				testDS10,
				testDS25,
			}
		)

		AfterFailed(func() {
			kubectl.CiliumReport("cilium bpf bandwidth list", "cilium endpoint list")
		})

		JustAfterEach(func() {
			kubectl.ValidateNoErrorsInLogs(CurrentGinkgoTestDescription().Duration)
		})

		waitForTestPods := func() {
			podLabels := []string{
				testDS10,
				testDS25,
				testClientPod,
				testClientHost,
			}
			for _, label := range podLabels {
				err := kubectl.WaitforPods(helpers.DefaultNamespace,
					fmt.Sprintf("-l %s", label), helpers.HelperTimeout)
				Expect(err).Should(BeNil())
			}
		}

		testNetperfFromPods := func(clientPodLabel, targetIP string, maxSessions, rate int) {
			pods, err := kubectl.GetPodNames(helpers.DefaultNamespace, clientPodLabel)
			ExpectWithOffset(1, err).Should(BeNil(), "cannot retrieve pod names by filter %q",
				clientPodLabel)
			for i := 1; i <= maxSessions; i++ {
				cmd := helpers.SuperNetperf(i, targetIP, helpers.TCP_MAERTS, "")
				for _, pod := range pods {
					By("Running %d netperf session from %s pod to pod with IP %s (expected rate: %d)",
						i, pod, targetIP, rate)
					res := kubectl.ExecPodCmd(helpers.DefaultNamespace, pod, cmd)
					ExpectWithOffset(1, res).Should(helpers.CMDSuccess(),
						"Request from %s pod to pod with IP %s failed", pod, targetIP)
					By("Session test completed, netperf result raw: %s", res.SingleOut())
					if rate > 0 {
						ExpectWithOffset(1, res.InRange(minBandwidth, rate+maxRateDeviation)).To(BeNil(),
							"Rate mismatch")
					}
				}
			}
		}

		testNetperf := func(podLabels []string, fromLabel string) {
			for _, label := range podLabels {
				podIPs, err := kubectl.GetPodsIPs(helpers.DefaultNamespace, label)
				ExpectWithOffset(1, err).Should(BeNil(), "Cannot retrieve pod IPs for %s", label)
				ExpectWithOffset(1, len(podIPs)).To(Equal(int(1)), "Expected pod IPs mismatch")
				rate := 0
				fmt.Sscanf(label, "run=netperf-%d", &rate)
				for _, podIP := range podIPs {
					testNetperfFromPods(fromLabel, podIP, 1, rate)
				}
			}
		}

		It("Checks Pod to Pod bandwidth, vxlan tunneling", func() {
			DeployCiliumOptionsAndDNS(kubectl, ciliumFilename, map[string]string{
				"bandwidthManager": "true",
				"tunnel":           "vxlan",
			})
			waitForTestPods()
			testNetperf(podLabels, testClientPod)
			testNetperf(podLabels, testClientHost)
		})
		It("Checks Pod to Pod bandwidth, geneve tunneling", func() {
			DeployCiliumOptionsAndDNS(kubectl, ciliumFilename, map[string]string{
				"bandwidthManager": "true",
				"tunnel":           "geneve",
			})
			waitForTestPods()
			testNetperf(podLabels, testClientPod)
			testNetperf(podLabels, testClientHost)
		})
		It("Checks Pod to Pod bandwidth, direct routing", func() {
			DeployCiliumOptionsAndDNS(kubectl, ciliumFilename, map[string]string{
				"bandwidthManager":     "true",
				"tunnel":               "disabled",
				"autoDirectNodeRoutes": "true",
			})
			waitForTestPods()
			testNetperf(podLabels, testClientPod)
			testNetperf(podLabels, testClientHost)
		})
	})
})


text:
import tensorflow as tf

class WordPadder:

    def __init__(self):
        self.variables = {}

        self.prepare_tensorflow_variables()

    def prepare_tensorflow_variables(self):
        self.variables["word_indices"] = tf.placeholder(tf.int32, [None, None])

    def pad(self, word_embeddings):
        word_embeddings = tf.pad(word_embeddings, [[1,0], [0,0]], "CONSTANT")
        word_embedding_matrix = tf.nn.embedding_lookup(word_embeddings, self.variables["word_indices"])
        return word_embedding_matrix

    def handle_variable_assignment(self, batch, mode):
        self.variable_assignments = {}

        self.variable_assignments["word_indices"] = batch.get_word_indexes_in_padded_sentence_matrix()

    def get_regularization(self):
        return 0


text:
/* Includes */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "em_bus.h"
#include "em_cmu.h"
#include "em_gpio.h"
#include "em_ldma.h"
#include "em_usart.h"

#ifndef WF200_WIFI
#include "FreeRTOS.h"
#include "event_groups.h"
#include "task.h"
#endif

#include "wfx_host_events.h"
#include "wifi_config.h"
#ifdef WF200_WIFI
#include "sl_wfx.h"
#endif
/* LwIP includes. */
#include "ethernetif.h"
#include "lwip/ethip6.h"
#include "lwip/timeouts.h"
#include "netif/etharp.h"

#ifndef EFR32_LOG
extern "C" {
void efr32Log(const char * aFormat, ...);
#define EFR32_LOG(...) efr32Log(__VA_ARGS__);
}
#endif

StaticSemaphore_t xEthernetIfSemaBuffer;

/*****************************************************************************
 * Defines
 ******************************************************************************/
#define STATION_NETIF0 's'
#define STATION_NETIF1 't'

#define LWIP_FRAME_ALIGNMENT 60

uint32_t gOverrunCount = 0;

/*****************************************************************************
 * Variables
 ******************************************************************************/

/*****************************************************************************
 * @fn static void low_level_init(struct netif *netif)
 * @brief
 *    Initializes the hardware parameters. Called from ethernetif_init().
 *
 * @param[in] netif: the already initialized lwip network interface structure
 *
 * @return
 *    None
 ******************************************************************************/
static void low_level_init(struct netif * netif)
{
    /* set netif MAC hardware address length */
    netif->hwaddr_len = ETH_HWADDR_LEN;

    /* Set netif MAC hardware address */
    sl_wfx_mac_address_t mac_addr;

    wfx_get_wifi_mac_addr(SL_WFX_STA_INTERFACE, &mac_addr);

    netif->hwaddr[0] = mac_addr.octet[0];
    netif->hwaddr[1] = mac_addr.octet[1];
    netif->hwaddr[2] = mac_addr.octet[2];
    netif->hwaddr[3] = mac_addr.octet[3];
    netif->hwaddr[4] = mac_addr.octet[4];
    netif->hwaddr[5] = mac_addr.octet[5];

    /* Set netif maximum transfer unit */
    netif->mtu = 1500;

    /* Accept broadcast address and ARP traffic */
    netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;

#if LWIP_IPV6_MLD
    netif->flags |= NETIF_FLAG_MLD6;
#endif /* LWIP_IPV6_MLD */
}

/********************************************************************************
 * @fn  static void low_level_input(struct netif *netif, uint8_t *b, uint16_t len)
 * @brief
 * Make PBUF out of a linear buffer - that can be fed into lwip
 * @param[in]  netif: the already initialized lwip network interface structure
 * @param[in]  len: length
 * @return
 *     None
 ************************************************************************************/
static void low_level_input(struct netif * netif, uint8_t * b, uint16_t len)
{
    struct pbuf *p, *q;
    uint32_t bufferoffset;

    if (len <= 0)
    {
        return;
    }
    if (len < LWIP_FRAME_ALIGNMENT)
    { /* 60 : LWIP frame alignment */
        len = LWIP_FRAME_ALIGNMENT;
    }

    /* Drop packets originated from the same interface and is not destined for the said interface */
    const uint8_t * src_mac = b + netif->hwaddr_len;
    const uint8_t * dst_mac = b;

    if (!(ip6_addr_ispreferred(netif_ip6_addr_state(netif, 0))) && (memcmp(netif->hwaddr, src_mac, netif->hwaddr_len) == 0) &&
        (memcmp(netif->hwaddr, dst_mac, netif->hwaddr_len) != 0))
    {
#ifdef WIFI_DEBUG_ENABLED
        EFR32_LOG("%s: DROP, [%02x:%02x:%02x:%02x:%02x:%02x]<-[%02x:%02x:%02x:%02x:%02x:%02x] type=%02x%02x", __func__,

                  dst_mac[0], dst_mac[1], dst_mac[2], dst_mac[3], dst_mac[4], dst_mac[5],

                  src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5],

                  b[12], b[13]);
#endif
        return;
    }

    /* We allocate a pbuf chain of pbufs from the Lwip buffer pool
     * and copy the data to the pbuf chain
     */
    if ((p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL)) != STRUCT_PBUF)
    {
        for (q = p, bufferoffset = 0; q != NULL; q = q->next)
        {
            memcpy((uint8_t *) q->payload, (uint8_t *) b + bufferoffset, q->len);
            bufferoffset += q->len;
        }
#ifdef WIFI_DEBUG_ENABLED
        EFR32_LOG("%s: ACCEPT %d, [%02x:%02x:%02x:%02x:%02x:%02x]<-[%02x:%02x:%02x:%02x:%02x:%02x] type=%02x%02x", __func__,
                  bufferoffset,

                  dst_mac[0], dst_mac[1], dst_mac[2], dst_mac[3], dst_mac[4], dst_mac[5],

                  src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5],

                  b[12], b[13]);
#endif

        if (netif->input(p, netif) != ERR_OK)
        {
            gOverrunCount++;
            EFR32_LOG("overrun count entering when fail to alloc value %d", gOverrunCount);
            pbuf_free(p);
        }
    }
    else
    {
        gOverrunCount++;
        EFR32_LOG("overrun count entering when fail to alloc value %d", gOverrunCount);
    }
}

/*****************************************************************************
 *  @fn  static err_t low_level_output(struct netif *netif, struct pbuf *p)
 *  @brief
 *    This function should does the actual transmission of the packet(s).
 *    The packet is contained in the pbuf that is passed to the function.
 *    This pbuf might be chained.
 *
 * @param[in] netif: the lwip network interface structure
 *
 * @param[in] p: the packet to send
 *
 * @return
 *    ERR_OK if successful
 ******************************************************************************/
#ifdef WF200_WIFI
static err_t low_level_output(struct netif * netif, struct pbuf * p)
{
    struct pbuf * q;
    sl_wfx_send_frame_req_t * tx_buffer;
    uint8_t * buffer;
    uint32_t framelength, asize;
    uint32_t bufferoffset;
    uint32_t padding;
    sl_status_t result;

    for (q = p, framelength = 0; q != NULL; q = q->next)
    {
        framelength += q->len;
    }
    if (framelength < LWIP_FRAME_ALIGNMENT)
    { /* 60 : Frame alignment for LWIP */
        padding = LWIP_FRAME_ALIGNMENT - framelength;
    }
    else
    {
        padding = 0;
    }

    /* choose padding of 64 */
    asize = SL_WFX_ROUND_UP(framelength + padding, 64) + sizeof(sl_wfx_send_frame_req_t);
    // 12 is size of other data in buffer struct, user shouldn't have to care about this?
    if (sl_wfx_host_allocate_buffer((void **) &tx_buffer, SL_WFX_TX_FRAME_BUFFER, asize) != SL_STATUS_OK)
    {
        EFR32_LOG("*ERR*EN-Out: No mem frame len=%d", framelength);
        gOverrunCount++;
        EFR32_LOG("overrun count exiting when faied to alloc value %d", gOverrunCount);
        return ERR_MEM;
    }
    buffer = tx_buffer->body.packet_data;
    /* copy frame from pbufs to driver buffers */
    for (q = p, bufferoffset = 0; q != NULL; q = q->next)
    {
        /* Get bytes in current lwIP buffer */
        memcpy((uint8_t *) ((uint8_t *) buffer + bufferoffset), (uint8_t *) ((uint8_t *) q->payload), q->len);
        bufferoffset += q->len;
    }
    /* No requirement to do this - but we should for security */
    if (padding)
    {
        memset(buffer + bufferoffset, 0, padding);
        framelength += padding;
    }
    /* transmit */
    int i  = 0;
    result = SL_STATUS_FAIL;

#ifdef WIFI_DEBUG_ENABLED
    EFR32_LOG("WF200: Out %d", (int) framelength);
#endif

    /* send the generated frame over Wifi network */
    while ((result != SL_STATUS_OK) && (i++ < 10))
    {
        result = sl_wfx_send_ethernet_frame(tx_buffer, framelength, SL_WFX_STA_INTERFACE, PRIORITY_0);
    }
    sl_wfx_host_free_buffer(tx_buffer, SL_WFX_TX_FRAME_BUFFER);

    if (result != SL_STATUS_OK)
    {
        EFR32_LOG("*ERR*Send enet %d", (int) framelength);
        return ERR_IF;
    }
    return ERR_OK;
}

/*****************************************************************************
 * @fn   void sl_wfx_host_received_frame_callback(sl_wfx_received_ind_t *rx_buffer)
 * @brief
 *    This function implements the wf200 received frame callback.
 *    Called from the context of the bus_task (not ISR)
 *
 * @param[in] rx_buffer: the ethernet frame received by the wf200
 *
 * @return
 *    None
 ******************************************************************************/
void sl_wfx_host_received_frame_callback(sl_wfx_received_ind_t * rx_buffer)
{
    struct netif * netif;

    /* Check packet interface to send to AP or STA interface */
    if ((rx_buffer->header.info & SL_WFX_MSG_INFO_INTERFACE_MASK) == (SL_WFX_STA_INTERFACE << SL_WFX_MSG_INFO_INTERFACE_OFFSET))
    {

        /* Send received frame to station interface */
        if ((netif = wfx_get_netif(SL_WFX_STA_INTERFACE)) != NULL)
        {
            uint8_t * buffer;
            uint16_t len;

            len    = rx_buffer->body.frame_length;
            buffer = (uint8_t *) &(rx_buffer->body.frame[rx_buffer->body.frame_padding]);

#ifdef WIFI_DEBUG_ENABLED
            EFR32_LOG("WF200: In %d", (int) len);
#endif

            low_level_input(netif, buffer, len);
        }
        else
        {
#ifdef WIFI_DEBUG_ENABLED
            EFR32_LOG("WF200: NO-INTF");
#endif
        }
    }
    else
    {
#ifdef WIFI_DEBUG_ENABLED
        EFR32_LOG("WF200: Invalid frame IN");
#endif
    }
}

#else /* For RS911x - using LWIP */
static SemaphoreHandle_t ethout_sem;
/*****************************************************************************
 *  @fn  static err_t low_level_output(struct netif *netif, struct pbuf *p)
 *  @brief
 *    This function is called from LWIP task when LWIP stack
 *    has some data to be forwarded over WiFi Network
 *
 * @param[in] netif: lwip network interface
 *
 * @param[in] p: the packet to send
 *
 * @return
 *    ERR_OK if successful
 ******************************************************************************/
static err_t low_level_output(struct netif * netif, struct pbuf * p)
{
    void * rsipkt;
    struct pbuf * q;
    uint16_t framelength;

    if (xSemaphoreTake(ethout_sem, portMAX_DELAY) != pdTRUE)
    {
        return ERR_IF;
    }
#ifdef WIFI_DEBUG_ENABLED
    EFR32_LOG("EN-RSI: Output");
#endif
    if ((netif->flags & (NETIF_FLAG_LINK_UP | NETIF_FLAG_UP)) != (NETIF_FLAG_LINK_UP | NETIF_FLAG_UP))
    {
        EFR32_LOG("EN-RSI:NOT UP");
        xSemaphoreGive(ethout_sem);
        return ERR_IF;
    }
    /* Confirm if packet is allocated */
    rsipkt = wfx_rsi_alloc_pkt();
    if (!rsipkt)
    {
        EFR32_LOG("EN-RSI:No buf");
        xSemaphoreGive(ethout_sem);
        return ERR_IF;
    }

#ifdef WIFI_DEBUG_ENABLED
    uint8_t * b = (uint8_t *) p->payload;
    EFR32_LOG("EN-RSI: Out [%02x:%02x:%02x:%02x:%02x:%02x][%02x:%02x:%02x:%02x:%02x:%02x]type=%02x%02x", b[0], b[1], b[2], b[3],
              b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13]);
#endif
    /* Generate the packet */
    for (q = p, framelength = 0; q != NULL; q = q->next)
    {
        wfx_rsi_pkt_add_data(rsipkt, (uint8_t *) (q->payload), (uint16_t) q->len, framelength);
        framelength += q->len;
    }
    if (framelength < LWIP_FRAME_ALIGNMENT)
    {
        /* Add junk data to the end for frame alignment if framelength is less than 60 */
        wfx_rsi_pkt_add_data(rsipkt, (uint8_t *) (p->payload), LWIP_FRAME_ALIGNMENT - framelength, framelength);
    }
#ifdef WIFI_DEBUG_ENABLED
    EFR32_LOG("EN-RSI: Sending %d", framelength);
#endif

    /* forward the generated packet to RSI to
     * send the data over wifi network
     */
    if (wfx_rsi_send_data(rsipkt, framelength))
    {
        EFR32_LOG("*ERR*EN-RSI:Send fail");
        xSemaphoreGive(ethout_sem);
        return ERR_IF;
    }

#ifdef WIFI_DEBUG_ENABLED
    EFR32_LOG("EN-RSI:Xmit %d", framelength);
#endif
    xSemaphoreGive(ethout_sem);

    return ERR_OK;
}

/*****************************************************************************
 *  @fn  void wfx_host_received_sta_frame_cb(uint8_t *buf, int len)
 *  @brief
 *    host received frame cb
 *
 * @param[in] buf: buffer
 *
 * @param[in] len: length
 *
 * @return
 *    None
 ******************************************************************************/
void wfx_host_received_sta_frame_cb(uint8_t * buf, int len)
{
    struct netif * ifp;

    /* get the network interface for STATION interface,
     * and forward the received frame buffer to LWIP
     */
    if ((ifp = wfx_get_netif(SL_WFX_STA_INTERFACE)) != (struct netif *) 0)
    {
        low_level_input(ifp, buf, len);
    }
}

#endif /* RS911x - with LWIP */

/*****************************************************************************
 *  @fn  err_t sta_ethernetif_init(struct netif *netif)
 *  @brief
 *    sta ethernet if initialization
 *
 * @param[in] netif: the lwip network interface structure
 *
 * @return
 *    ERR_OK if successful
 ******************************************************************************/
err_t sta_ethernetif_init(struct netif * netif)
{
    LWIP_ASSERT("netif != NULL", (netif != NULL));

    /* Set the netif name to identify the interface */
    netif->name[0] = STATION_NETIF0;
    netif->name[1] = STATION_NETIF1;

#if LWIP_IPV4 && LWIP_ARP
    netif->output = etharp_output;
#endif /* #if LWIP_IPV4 && LWIP_ARP */
#if LWIP_IPV6 && LWIP_ETHERNET
    netif->output_ip6 = ethip6_output;
#endif /* LWIP_IPV6 && LWIP_ETHERNET */
    netif->linkoutput = low_level_output;

    /* initialize the hardware */
    low_level_init(netif);
#ifndef WF200_WIFI
    /* Need single output only */
    ethout_sem = xSemaphoreCreateBinaryStatic(&xEthernetIfSemaBuffer);
    xSemaphoreGive(ethout_sem);
#endif
    return ERR_OK;
}


text:
'use strict';

describe('Service: dispatcher', function () {

	// load the service's module
	beforeEach(module('wdiApp'));

	// instantiate service
	var dispatcher;
	beforeEach(inject(function (_dispatcher_) {
		dispatcher = _dispatcher_;
	}));

	it('should just exist', function () {
		expect(dispatcher).toBeTruthy();
	});

});


text:
#include <time.h>
#include <stdio.h>
#include <langinfo.h>
#include "atomic.h"

const char *__nl_langinfo(nl_item);

char *__asctime(const struct tm *restrict tm, char *restrict buf)
{
	/* FIXME: change __nl_langinfo to __nl_langinfo_l with explicit C
	 * locale once we have locales */
	if (snprintf(buf, 26, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
		__nl_langinfo(ABDAY_1+tm->tm_wday),
		__nl_langinfo(ABMON_1+tm->tm_mon),
		tm->tm_mday, tm->tm_hour,
		tm->tm_min, tm->tm_sec,
		1900 + tm->tm_year) >= 26)
	{
		/* ISO C requires us to use the above format string,
		 * even if it will not fit in the buffer. Thus asctime_r
		 * is _supposed_ to crash if the fields in tm are too large.
		 * We follow this behavior and crash "gracefully" to warn
		 * application developers that they may not be so lucky
		 * on other implementations (e.g. stack smashing..).
		 */
		a_crash();
	}
	return buf;
}


text:
package com.opengamma.strata.math.impl.function.special;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.data.Offset.offset;

import org.junit.jupiter.api.Test;

import com.opengamma.strata.math.impl.function.DoubleFunction1D;

/**
 * Test.
 */
public class JacobiPolynomialFunctionTest {
  private static final double ALPHA = 0.12;
  private static final double BETA = 0.34;
  private static final DoubleFunction1D P0 = x -> 1d;
  private static final DoubleFunction1D P1 = x -> 0.5 * (2 * (ALPHA + 1) + (ALPHA + BETA + 2) * (x - 1));
  private static final DoubleFunction1D P2 =
      x -> 0.125 * (4 * (ALPHA + 1) * (ALPHA + 2) + 4 * (ALPHA + BETA + 3) *
          (ALPHA + 2) * (x - 1) + (ALPHA + BETA + 3) * (ALPHA + BETA + 4) * (x - 1) * (x - 1));
  private static final DoubleFunction1D[] P = new DoubleFunction1D[] {P0, P1, P2};
  private static final JacobiPolynomialFunction JACOBI = new JacobiPolynomialFunction();
  private static final double EPS = 1e-9;

  @Test
  public void testNoAlphaBeta() {
    assertThatExceptionOfType(UnsupportedOperationException.class)
        .isThrownBy(() -> JACOBI.getPolynomials(3));
  }

  @Test
  public void testNegativeN() {
    assertThatIllegalArgumentException()
        .isThrownBy(() -> JACOBI.getPolynomials(-3, ALPHA, BETA));
  }

  @Test
  public void testGetPolynomials() {
    assertThatExceptionOfType(UnsupportedOperationException.class)
        .isThrownBy(() -> JACOBI.getPolynomialsAndFirstDerivative(3));
  }

  @Test
  public void test() {
    DoubleFunction1D[] p = JACOBI.getPolynomials(0, ALPHA, BETA);
    assertThat(p.length).isEqualTo(1);
    final double x = 1.23;
    assertThat(p[0].applyAsDouble(x)).isCloseTo(1, offset(EPS));
    for (int i = 0; i <= 2; i++) {
      p = JACOBI.getPolynomials(i, ALPHA, BETA);
      for (int j = 0; j <= i; j++) {
        assertThat(P[j].applyAsDouble(x)).isCloseTo(p[j].applyAsDouble(x), offset(EPS));
      }
    }
  }
}


text:
package org.calrissian.mango.criteria.visitor;

import org.calrissian.mango.criteria.domain.Leaf;
import org.calrissian.mango.criteria.domain.ParentNode;

public class EmptyParentCollapseVisitor implements NodeVisitor {

    @Override
    public void begin(ParentNode node) {
        if (node.children() == null || node.children().size() == 0) {
            if (node.parent() != null) {
                node.parent().removeChild(node);
            }
        }
    }

    @Override
    public void end(ParentNode node) {

    }

    @Override
    public void visit(Leaf node) {

    }

}