text:
"""Reproduce an Counter state."""
from __future__ import annotations

import asyncio
from collections.abc import Iterable
import logging
from typing import Any

from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import Context, HomeAssistant, State

from . import (
    ATTR_INITIAL,
    ATTR_MAXIMUM,
    ATTR_MINIMUM,
    ATTR_STEP,
    DOMAIN,
    SERVICE_CONFIGURE,
    VALUE,
)

_LOGGER = logging.getLogger(__name__)

async def _async_reproduce_state(
    hass: HomeAssistant,
    state: State,
    *,
    context: Context | None = None,
    reproduce_options: dict[str, Any] | None = None,
) -> None:
    """Reproduce a single state."""
    if (cur_state := hass.states.get(state.entity_id)) is None:
        _LOGGER.warning("Unable to find entity %s", state.entity_id)
        return

    if not state.state.isdigit():
        _LOGGER.warning(
            "Invalid state specified for %s: %s", state.entity_id, state.state
        )
        return

    # Return if we are already at the right state.
    if (
        cur_state.state == state.state
        and cur_state.attributes.get(ATTR_INITIAL) == state.attributes.get(ATTR_INITIAL)
        and cur_state.attributes.get(ATTR_MAXIMUM) == state.attributes.get(ATTR_MAXIMUM)
        and cur_state.attributes.get(ATTR_MINIMUM) == state.attributes.get(ATTR_MINIMUM)
        and cur_state.attributes.get(ATTR_STEP) == state.attributes.get(ATTR_STEP)
    ):
        return

    service_data = {ATTR_ENTITY_ID: state.entity_id, VALUE: state.state}
    service = SERVICE_CONFIGURE
    if ATTR_INITIAL in state.attributes:
        service_data[ATTR_INITIAL] = state.attributes[ATTR_INITIAL]
    if ATTR_MAXIMUM in state.attributes:
        service_data[ATTR_MAXIMUM] = state.attributes[ATTR_MAXIMUM]
    if ATTR_MINIMUM in state.attributes:
        service_data[ATTR_MINIMUM] = state.attributes[ATTR_MINIMUM]
    if ATTR_STEP in state.attributes:
        service_data[ATTR_STEP] = state.attributes[ATTR_STEP]

    await hass.services.async_call(
        DOMAIN, service, service_data, context=context, blocking=True
    )

async def async_reproduce_states(
    hass: HomeAssistant,
    states: Iterable[State],
    *,
    context: Context | None = None,
    reproduce_options: dict[str, Any] | None = None,
) -> None:
    """Reproduce Counter states."""
    await asyncio.gather(
        *(
            _async_reproduce_state(
                hass, state, context=context, reproduce_options=reproduce_options
            )
            for state in states
        )
    )

redpajama_set_name: RedPajamaGithub


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivityFragment"
    android:background="@color/primary_theme_color"
    android:orientation="vertical"
    android:weightSum="1">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="25dp"
        android:layout_weight=".5">

        <ImageView
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_gravity="center"
            android:src="@drawable/logo"/>
    </FrameLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".5">

        <com.twitter.sdk.android.core.identity.TwitterLoginButton
            android:id="@+id/twitter_login_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginBottom="40dp"
            android:layout_centerInParent="true"/>
    </FrameLayout>

</LinearLayout>


text:
@implementation BackgroundPlayer
@synthesize player=_player;

static BackgroundPlayer *instance = nil;

+ (BackgroundPlayer *)sharedInstance
{
    if (!instance) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[BackgroundPlayer alloc] init];
        });
    }
    return instance;
}

- (BOOL)isPlaying
{
    if (_player) {
        return [_player isPlaying];
    }
    return NO;
}

- (void)play
{
    if ([self isPlaying]) {
        return;
    }
    NSError *error = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"Silent Roar-euphoria" withExtension:@"mp3"] error:nil];
    [_player prepareToPlay];
    [_player setMeteringEnabled:YES];
    [_player play];

    // NSTimer running in background thread
    NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(sendCurrentProgress:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

- (float)normalizedPowerLevel
{
    [_player updateMeters];

    CGFloat normalizedValue;
    normalizedValue = [self _normalizedPowerLevelFromDecibels:[_player averagePowerForChannel:0]];
    return normalizedValue;
}

- (float)progress
{
    return _player.currentTime/_player.duration;
}

- (NSTimeInterval)currentTime
{
    return _player.currentTime;
}

- (NSTimeInterval)duration
{
    return _player.duration;
}

#pragma mark - private

- (void)sendCurrentProgress:(NSTimer *)timer
{
    [_delegate currentTime:_player.currentTime withDuration:_player.duration];
}

- (CGFloat)_normalizedPowerLevelFromDecibels:(CGFloat)decibels
{
    if (decibels < -60.0f || decibels == 0.0f) {
        return 0.0f;
    }

    return powf((powf(10.0f, 0.05f * decibels) - powf(10.0f, 0.05f * -60.0f)) * (1.0f / (1.0f - powf(10.0f, 0.05f * -60.0f))), 1.0f / 2.0f);
}

@end


text:
package com.spike.giantdataanalysis.task.execution.core.executor;

import java.util.List;

import com.google.common.collect.Lists;
import com.spike.giantdataanalysis.coordination.CoordinationRole;
import com.spike.giantdataanalysis.coordination.Coordinations;
import com.spike.giantdataanalysis.task.execution.core.activity.TaskActivity;
import com.spike.giantdataanalysis.task.execution.core.activity.TaskActivitys;
import com.spike.giantdataanalysis.task.execution.core.threads.TaskThreads;

/**
 * 负责启动和停止[执行]实际任务的工具.
 * @author zhoujiagen
 */
public class TaskWorker {

  private final TaskActivitys taskActivityFactory;

  private List<TaskActivity> taskActivities = Lists.newArrayList();
  private List<Thread> taskActivityThreads = Lists.newArrayList();

  public TaskWorker(TaskActivitys taskActivityFactory) {
    this.taskActivityFactory = taskActivityFactory;
  }

  public void start() {
    String id = Coordinations.id();
    TaskActivity taskExecuteActivity = taskActivityFactory.newTaskExecuteActivity(id);
    taskActivities.add(taskExecuteActivity);
    Thread taskExecuteActivityThread =
        TaskThreads.I().newThread(CoordinationRole.WORKER.name(), "TaskExecuteActivity-" + id,
          taskExecuteActivity);
    taskActivityThreads.add(taskExecuteActivityThread);
    TaskThreads.I().start(taskExecuteActivityThread);
  }

  public void cancel() {
    for (TaskActivity ta : taskActivities) {
      taskActivityFactory.delete(ta);
    }
    taskActivityThreads.clear();
  }

  public void join() {
    for (Thread t : taskActivityThreads) {
      TaskThreads.I().join(t);
    }
  }
}


text:
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Timing;
using Abp.Zero;
using Abp.Zero.Configuration;
using HealthCheckExample.Authorization.Roles;
using HealthCheckExample.Authorization.Users;
using HealthCheckExample.Configuration;
using HealthCheckExample.Localization;
using HealthCheckExample.MultiTenancy;
using HealthCheckExample.Timing;

namespace HealthCheckExample
{
    [DependsOn(typeof(AbpZeroCoreModule))]
    public class HealthCheckExampleCoreModule : AbpModule
    {
        public override void PreInitialize()
        {
            Configuration.Auditing.IsEnabledForAnonymousUsers = true;

            // Declare entity types
            Configuration.Modules.Zero().EntityTypes.Tenant = typeof(Tenant);
            Configuration.Modules.Zero().EntityTypes.Role = typeof(Role);
            Configuration.Modules.Zero().EntityTypes.User = typeof(User);

            HealthCheckExampleLocalizationConfigurer.Configure(Configuration.Localization);

            // Enable this line to create a multi-tenant application.
            Configuration.MultiTenancy.IsEnabled = HealthCheckExampleConsts.MultiTenancyEnabled;

            // Configure roles
            AppRoleConfig.Configure(Configuration.Modules.Zero().RoleManagement);

            Configuration.Settings.Providers.Add<AppSettingProvider>();
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(HealthCheckExampleCoreModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            IocManager.Resolve<AppTimes>().StartupTime = Clock.Now;
        }
    }
}


text:
package org.apache.drill.exec.physical.config;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.drill.exec.physical.base.AbstractReceiver;
import org.apache.drill.exec.physical.base.PhysicalVisitor;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.proto.UserBitShared.CoreOperatorType;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;

@JsonTypeName("unordered-receiver")
public class UnorderedReceiver extends AbstractReceiver{
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UnorderedReceiver.class);

  private List<DrillbitEndpoint> senders;

  @JsonCreator
  public UnorderedReceiver(@JsonProperty("sender-major-fragment") int oppositeMajorFragmentId,
                        @JsonProperty("senders") List<DrillbitEndpoint> senders) {
    super(oppositeMajorFragmentId);
    this.senders = senders;
  }

  @Override
  @JsonProperty("senders")
  public List<DrillbitEndpoint> getProvidingEndpoints() {
    return senders;
  }

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

  @Override
  public <T, X, E extends Throwable> T accept(PhysicalVisitor<T, X, E> physicalVisitor, X value) throws E {
    return physicalVisitor.visitUnorderedReceiver(this, value);
  }

  @Override
  public int getOperatorType() {
    return CoreOperatorType.UNORDERED_RECEIVER_VALUE;
  }

  @JsonIgnore
  public int getNumSenders() {
    return senders.size();
  }
}


text:
/*
This question is from https://leetcode.com/problems/flatten-nested-list-iterator/
Difficulty: medium

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:

Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,
             the order of elements returned by next should be: [1,1,2,1,1].
Example 2:

Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,
             the order of elements returned by next should be: [1,4,6].
*/

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */

// Impressive method https://leetcode.com/problems/flatten-nested-list-iterator/discuss/80146/Real-iterator-in-Python-Java-C%2B%2B

// stack method, T:O(N), S:O(N), 5 ms
public class NestedIterator implements Iterator<Integer> {

    Stack<NestedInteger> stack;

    public NestedIterator(List<NestedInteger> nestedList) {
        stack = new Stack();
        for(int i = nestedList.size() - 1; i >= 0; i--){
            stack.push(nestedList.get(i));
        }
    }

    @Override
    public Integer next() {
        if(hasNext()){
            return stack.pop().getInteger();
        }

        return 0;
    }

    @Override
    public boolean hasNext() {

        while(!stack.isEmpty()){
            NestedInteger current = stack.peek();

            if(current.isInteger()){
                return true;
            }

            stack.pop();

            for(int i = current.getList().size() - 1 ; i >= 0; i--){
                stack.push(current.getList().get(i));
            }
        }

        return false;
    }
}

// straight forward, T:O(N), S:O(N), 59 ms
public class NestedIterator implements Iterator<Integer> {

    List<Integer> list;
    int index;

    public NestedIterator(List<NestedInteger> nestedList) {
        list = new LinkedList();

        insert(nestedList);

        index = 0;

        // for(int n : list) System.out.println(n);
        // System.out.println("=======");
    }

    private void insert(List<NestedInteger> nestedList){
        for(int i = 0; i < nestedList.size(); i++){
            if(nestedList.get(i).isInteger()){
                list.add(nestedList.get(i).getInteger());
            }else{
                insert(nestedList.get(i).getList());
            }
        }
    }

    @Override
    public Integer next() {
        if(hasNext()){
            int current = list.get(index);
            index++;
            return current;
        }else{
            return 0;
        }
    }

    @Override
    public boolean hasNext() {
        if(index < list.size()){
            return true;
        }else{
            return false;
        }
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */