text:
<?php
namespace Server\CoreBase;

use Server\SwooleMarco;

/**
 * Controller 控制器
 * 对象池模式,实例会被反复使用,成员变量缓存数据记得在销毁时清理
 * Created by PhpStorm.
 * User: tmtbe
 * Date: 16-7-15
 * Time: 上午11:59
 */
class Controller extends CoreBase
{
    /**
     * @var \Server\DataBase\RedisAsynPool
     */
    public $redis_pool;
    /**
     * @var \Server\DataBase\MysqlAsynPool
     */
    public $mysql_pool;
    /**
     * @var HttpInPut
     */
    public $http_input;
    /**
     * @var HttpOutPut
     */
    public $http_output;
    /**
     * 是否来自http的请求不是就是来自tcp
     * @var string
     */
    public $request_type;
    /**
     * @var \Server\Client\Client
     */
    public $client;
    /**
     * fd
     * @var int
     */
    protected $fd;
    /**
     * uid
     * @var int
     */
    protected $uid;
    /**
     * 用户数据
     * @var
     */
    protected $client_data;
    /**
     * http response
     * @var \swoole_http_request
     */
    protected $request;
    /**
     * http response
     * @var \swoole_http_response
     */
    protected $response;

    /**
     * Controller constructor.
     */
    public function __construct()
    {
        parent::__construct();
//        $this->server->reload();
        $this->http_input = new HttpInput();
        $this->http_output = new HttpOutput($this);
        $this->redis_pool = get_instance()->redis_pool;
        $this->mysql_pool = get_instance()->mysql_pool;
        $this->client = get_instance()->client;
    }

    /**
     * 设置客户端协议数据
     * @param $uid
     * @param $fd
     * @param $client_data
     */
    public function setClientData($uid, $fd, $client_data)
    {
        $this->uid = $uid;
        $this->fd = $fd;
        $this->client_data = $client_data;
        $this->request_type = SwooleMarco::TCP_REQUEST;
    }

    /**
     * set http Request Response
     * @param $request
     * @param $response
     */
    public function setRequestResponse($request, $response)
    {
        $this->request = $request;
        $this->response = $response;
        $this->http_input->set($request);
        $this->http_output->set($response);
        $this->request_type = SwooleMarco::HTTP_REQUEST;
    }

    /**
     * 异常的回调
     * @param \Exception $e
     */
    public function onExceptionHandle(\Exception $e)
    {
        switch ($this->request_type) {
            case SwooleMarco::HTTP_REQUEST:
                $this->http_output->end($e->getMessage());
                break;
            case SwooleMarco::TCP_REQUEST:
                $this->send($e->getMessage());
                break;
        }
    }

    /**
     * 向当前客户端发送消息
     * @param $data
     * @param $destory
     * @throws SwooleException
     */
    protected function send($data, $destory = true)
    {
        if ($this->is_destroy) {
            throw new SwooleException('controller is destory can not send data');
        }
        $data = get_instance()->encode($this->pack->pack($data));
        get_instance()->send($this->fd, $data);
        if ($destory) {
            $this->destroy();
        }
    }

    /**
     * 销毁
     */
    public function destroy()
    {
        parent::destroy();
        unset($this->fd);
        unset($this->uid);
        unset($this->client_data);
        unset($this->request);
        unset($this->response);
        $this->http_input->reset();
        $this->http_output->reset();
        ControllerFactory::getInstance()->revertController($this);
    }

    /**
     * sendToUid
     * @param $uid
     * @param $data
     * @throws SwooleException
     */
    protected function sendToUid($uid, $data, $destory = true)
    {
        if ($this->is_destroy) {
            throw new SwooleException('controller is destory can not send data');
        }
        get_instance()->sendToUid($uid, $data);
        if ($destory) {
            $this->destroy();
        }
    }

    /**
     * sendToUids
     * @param $uids
     * @param $data
     * @param $destory
     * @throws SwooleException
     */
    protected function sendToUids($uids, $data, $destory = true)
    {
        if ($this->is_destroy) {
            throw new SwooleException('controller is destory can not send data');
        }
        get_instance()->sendToUids($uids, $data);
        if ($destory) {
            $this->destroy();
        }
    }

    /**
     * sendToAll
     * @param $data
     * @param $destory
     * @throws SwooleException
     */
    protected function sendToAll($data, $destory = true)
    {
        if ($this->is_destroy) {
            throw new SwooleException('controller is destory can not send data');
        }
        get_instance()->sendToAll($data);
        if ($destory) {
            $this->destroy();
        }
    }

    /**
     * 发送给群
     * @param $groupId
     * @param $data
     * @param bool $destory
     * @throws SwooleException
     */
    protected function sendToGroup($groupId, $data, $destory = true)
    {
        if ($this->is_destroy) {
            throw new SwooleException('controller is destory can not send data');
        }
        get_instance()->sendToGroup($groupId, $data);
        if ($destory) {
            $this->destroy();
        }
    }

    /**
     * 踢用户
     * @param $uid
     */
    protected function kickUid($uid)
    {
        get_instance()->kickUid($uid);
    }
}


text:
<?php

namespace Oro\Bundle\FilterBundle\Form\Type\Filter;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;

abstract class AbstractChoiceType extends AbstractType
{
    /**
     * @var TranslatorInterface
     */
    protected $translator;

    /**
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * @param FormView      $view
     * @param FormInterface $form
     * @param array         $options
     */
    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        if (!empty($view->children['value'])) {
            /** @var FormView $valueFormView */
            $valueFormView   = $view->children['value'];
            $this->translateChoices($view, $valueFormView, $options);
        }
    }

    /**
     * Translates choices
     *
     * @param FormView $view
     * @param FormView $valueFormView
     * @param array    $options
     */
    protected function translateChoices(FormView $view, FormView $valueFormView, array $options)
    {
        if (!empty($valueFormView->vars['choices'])) {
            // get translation domain
            $translationDomain = 'messages';
            if (!empty($options['translation_domain'])) {
                $translationDomain = $options['translation_domain'];
            } elseif (!empty($view->parent->vars['translation_domain'])) {
                $translationDomain = $view->parent->vars['translation_domain'];
            }

            // translate choice values
            /** @var $choiceView ChoiceView */
            foreach ($valueFormView->vars['choices'] as $key => $choiceView) {
                $choiceView->label = $this->translator->trans(
                    $choiceView->label,
                    array(),
                    $translationDomain
                );
                $valueFormView->vars['choices'][$key] = $choiceView;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from distutils.core import setup
from distutils.command.build import build
import sys

class my_build(build):
    """ensure (at runtime) we are running python 3"""
    def __init__(self,*args,**kwargs):
        assert sys.version_info[0]==3
        build.__init__(self,*args,**kwargs)

setup(name='py3_only_pkg',
      packages=['py3_only_pkg'],
      version='0.1',
      cmdclass={'build':my_build},
      author='Mister Unicodé',
      author_email='mister.unicode@example.tld',
      description='Python 3 package with Unicodé fields',
      long_description='This is a Python 3 package with Unicodé data.',
      )


text:
package com.schaffer.base.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 *

 * zipFiles          : 批量压缩文件
 * zipFile           : 压缩文件
 * unzipFiles        : 批量解压文件
 * unzipFile         : 解压文件
 * unzipFileByKeyword: 解压带有关键字的文件
 * getFilesPath      : 获取压缩文件中的文件路径链表
 * getComments       : 获取压缩文件中的注释链表
 * getEntries        : 获取压缩文件中的文件对象
 *

 */
public final class ZipUtils {

    private static final int KB = 1024;

    private ZipUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 批量压缩文件
     *
     * @param resFiles    待压缩文件集合
     * @param zipFilePath 压缩文件路径
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFiles(final Collection<File> resFiles, final String zipFilePath)
            throws IOException {
        return zipFiles(resFiles, zipFilePath, null);
    }

    /**
     * 批量压缩文件
     *
     * @param resFiles    待压缩文件集合
     * @param zipFilePath 压缩文件路径
     * @param comment     压缩文件的注释
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFiles(final Collection<File> resFiles, final String zipFilePath, final String comment)
            throws IOException {
        return zipFiles(resFiles, FileUtils.getFileByPath(zipFilePath), comment);
    }

    /**
     * 批量压缩文件
     *
     * @param resFiles 待压缩文件集合
     * @param zipFile  压缩文件
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFiles(final Collection<File> resFiles, final File zipFile)
            throws IOException {
        return zipFiles(resFiles, zipFile, null);
    }

    /**
     * 批量压缩文件
     *
     * @param resFiles 待压缩文件集合
     * @param zipFile  压缩文件
     * @param comment  压缩文件的注释
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFiles(final Collection<File> resFiles, final File zipFile, final String comment)
            throws IOException {
        if (resFiles == null || zipFile == null) return false;
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            for (File resFile : resFiles) {
                if (!zipFile(resFile, "", zos, comment)) return false;
            }
            return true;
        } finally {
            if (zos != null) {
                zos.finish();
                ClosableUtils.closeIO(zos);
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param resFilePath 待压缩文件路径
     * @param zipFilePath 压缩文件路径
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFile(final String resFilePath, final String zipFilePath)
            throws IOException {
        return zipFile(resFilePath, zipFilePath, null);
    }

    /**
     * 压缩文件
     *
     * @param resFilePath 待压缩文件路径
     * @param zipFilePath 压缩文件路径
     * @param comment     压缩文件的注释
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFile(final String resFilePath, final String zipFilePath, final String comment)
            throws IOException {
        return zipFile(FileUtils.getFileByPath(resFilePath), FileUtils.getFileByPath(zipFilePath), comment);
    }

    /**
     * 压缩文件
     *
     * @param resFile 待压缩文件
     * @param zipFile 压缩文件
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFile(final File resFile, final File zipFile)
            throws IOException {
        return zipFile(resFile, zipFile, null);
    }

    /**
     * 压缩文件
     *
     * @param resFile 待压缩文件
     * @param zipFile 压缩文件
     * @param comment 压缩文件的注释
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    public static boolean zipFile(final File resFile, final File zipFile, final String comment)
            throws IOException {
        if (resFile == null || zipFile == null) return false;
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            return zipFile(resFile, "", zos, comment);
        } finally {
            if (zos != null) {
                ClosableUtils.closeIO(zos);
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param resFile  待压缩文件
     * @param rootPath 相对于压缩文件的路径
     * @param zos      压缩文件输出流
     * @param comment  压缩文件的注释
     * @return {@code true}: 压缩成功
{@code false}: 压缩失败
     * @throws IOException IO错误时抛出
     */
    private static boolean zipFile(final File resFile, String rootPath, final ZipOutputStream zos, final String comment)
            throws IOException {
        rootPath = rootPath + (isSpace(rootPath) ? "" : File.separator) + resFile.getName();
        if (resFile.isDirectory()) {
            File[] fileList = resFile.listFiles();
            // 如果是空文件夹那么创建它,我把'/'换为File.separator测试就不成功,eggPain
            if (fileList == null || fileList.length <= 0) {
                ZipEntry entry = new ZipEntry(rootPath + '/');
                if (!StringUtils.isEmpty(comment)) entry.setComment(comment);
                zos.putNextEntry(entry);
                zos.closeEntry();
            } else {
                for (File file : fileList) {
                    // 如果递归返回false则返回false
                    if (!zipFile(file, rootPath, zos, comment)) return false;
                }
            }
        } else {
            InputStream is = null;
            try {
                is = new BufferedInputStream(new FileInputStream(resFile));
                ZipEntry entry = new ZipEntry(rootPath);
                if (!StringUtils.isEmpty(comment)) entry.setComment(comment);
                zos.putNextEntry(entry);
                byte buffer[] = new byte[KB];
                int len;
                while ((len = is.read(buffer, 0, KB)) != -1) {
                    zos.write(buffer, 0, len);
                }
                zos.closeEntry();
            } finally {
                ClosableUtils.closeIO(is);
            }
        }
        return true;
    }

    /**
     * 批量解压文件
     *
     * @param zipFiles    压缩文件集合
     * @param destDirPath 目标目录路径
     * @return {@code true}: 解压成功
{@code false}: 解压失败
     * @throws IOException IO错误时抛出
     */
    public static boolean unzipFiles(final Collection<File> zipFiles, final String destDirPath)
            throws IOException {
        return unzipFiles(zipFiles, FileUtils.getFileByPath(destDirPath));
    }

    /**
     * 批量解压文件
     *
     * @param zipFiles 压缩文件集合
     * @param destDir  目标目录
     * @return {@code true}: 解压成功
{@code false}: 解压失败
     * @throws IOException IO错误时抛出
     */
    public static boolean unzipFiles(final Collection<File> zipFiles, final File destDir)
            throws IOException {
        if (zipFiles == null || destDir == null) return false;
        for (File zipFile : zipFiles) {
            if (!unzipFile(zipFile, destDir)) return false;
        }
        return true;
    }

    /**
     * 解压文件
     *
     * @param zipFilePath 待解压文件路径
     * @param destDirPath 目标目录路径
     * @return {@code true}: 解压成功
{@code false}: 解压失败
     * @throws IOException IO错误时抛出
     */
    public static boolean unzipFile(final String zipFilePath, final String destDirPath)
            throws IOException {
        return unzipFile(FileUtils.getFileByPath(zipFilePath), FileUtils.getFileByPath(destDirPath));
    }

    /**
     * 解压文件
     *
     * @param zipFile 待解压文件
     * @param destDir 目标目录
     * @return {@code true}: 解压成功
{@code false}: 解压失败
     * @throws IOException IO错误时抛出
     */
    public static boolean unzipFile(final File zipFile, final File destDir)
            throws IOException {
        return unzipFileByKeyword(zipFile, destDir, null) != null;
    }

    /**
     * 解压带有关键字的文件
     *
     * @param zipFilePath 待解压文件路径
     * @param destDirPath 目标目录路径
     * @param keyword     关键字
     * @return 返回带有关键字的文件链表
     * @throws IOException IO错误时抛出
     */
    public static List<File> unzipFileByKeyword(final String zipFilePath, final String destDirPath, final String keyword)
            throws IOException {
        return unzipFileByKeyword(FileUtils.getFileByPath(zipFilePath),
                FileUtils.getFileByPath(destDirPath), keyword);
    }

    /**
     * 解压带有关键字的文件
     *
     * @param zipFile 待解压文件
     * @param destDir 目标目录
     * @param keyword 关键字
     * @return 返回带有关键字的文件链表
     * @throws IOException IO错误时抛出
     */
    public static List<File> unzipFileByKeyword(final File zipFile, final File destDir, final String keyword)
            throws IOException {
        if (zipFile == null || destDir == null) return null;
        List<File> files = new ArrayList<>();
        ZipFile zf = new ZipFile(zipFile);
        Enumeration<?> entries = zf.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            String entryName = entry.getName();
            if (StringUtils.isEmpty(keyword) || FileUtils.getFileName(entryName).toLowerCase().contains(keyword.toLowerCase())) {
                String filePath = destDir + File.separator + entryName;
                File file = new File(filePath);
                files.add(file);
                if (entry.isDirectory()) {
                    if (!FileUtils.createOrExistsDir(file)) return null;
                } else {
                    if (!FileUtils.createOrExistsFile(file)) return null;
                    InputStream in = null;
                    OutputStream out = null;
                    try {
                        in = new BufferedInputStream(zf.getInputStream(entry));
                        out = new BufferedOutputStream(new FileOutputStream(file));
                        byte buffer[] = new byte[KB];
                        int len;
                        while ((len = in.read(buffer)) != -1) {
                            out.write(buffer, 0, len);
                        }
                    } finally {
                        ClosableUtils.closeIO(in, out);
                    }
                }
            }
        }
        return files;
    }

    /**
     * 获取压缩文件中的文件路径链表
     *
     * @param zipFilePath 压缩文件路径
     * @return 压缩文件中的文件路径链表
     * @throws IOException IO错误时抛出
     */
    public static List<String> getFilesPath(final String zipFilePath)
            throws IOException {
        return getFilesPath(FileUtils.getFileByPath(zipFilePath));
    }

    /**
     * 获取压缩文件中的文件路径链表
     *
     * @param zipFile 压缩文件
     * @return 压缩文件中的文件路径链表
     * @throws IOException IO错误时抛出
     */
    public static List<String> getFilesPath(final File zipFile)
            throws IOException {
        if (zipFile == null) return null;
        List<String> paths = new ArrayList<>();
        Enumeration<?> entries = getEntries(zipFile);
        while (entries.hasMoreElements()) {
            paths.add(((ZipEntry) entries.nextElement()).getName());
        }
        return paths;
    }

    /**
     * 获取压缩文件中的注释链表
     *
     * @param zipFilePath 压缩文件路径
     * @return 压缩文件中的注释链表
     * @throws IOException IO错误时抛出
     */
    public static List<String> getComments(final String zipFilePath)
            throws IOException {
        return getComments(FileUtils.getFileByPath(zipFilePath));
    }

    /**
     * 获取压缩文件中的注释链表
     *
     * @param zipFile 压缩文件
     * @return 压缩文件中的注释链表
     * @throws IOException IO错误时抛出
     */
    public static List<String> getComments(final File zipFile)
            throws IOException {
        if (zipFile == null) return null;
        List<String> comments = new ArrayList<>();
        Enumeration<?> entries = getEntries(zipFile);
        while (entries.hasMoreElements()) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            comments.add(entry.getComment());
        }
        return comments;
    }

    /**
     * 获取压缩文件中的文件对象
     *
     * @param zipFilePath 压缩文件路径
     * @return 压缩文件中的文件对象
     * @throws IOException IO错误时抛出
     */
    public static Enumeration<?> getEntries(final String zipFilePath)
            throws IOException {
        return getEntries(FileUtils.getFileByPath(zipFilePath));
    }

    /**
     * 获取压缩文件中的文件对象
     *
     * @param zipFile 压缩文件
     * @return 压缩文件中的文件对象
     * @throws IOException IO错误时抛出
     */
    public static Enumeration<?> getEntries(final File zipFile)
            throws IOException {
        if (zipFile == null) return null;
        return new ZipFile(zipFile).entries();
    }

    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}


text:
yum -y erase cpp wireless-tools system-config-securitylevel-tui
yum -y erase $(rpm -qa | grep kernel | grep -v `uname -r`)
yum -y clean all
rm -rf *.iso *.iso.?
rm -rf /tmp/*

sed -i 's/^HWADDR.*$//' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i 's/^UUID.*$//' /etc/sysconfig/network-scripts/ifcfg-eth0

echo Zeroing out unused space...
dd if=/dev/zero of=/EMPTY bs=1M
rm -rf /EMPTY


text:
using System;

namespace BowlingKata
{
    public static class PredicateHelper
    {
        public static void OrThrow<T>(this bool predicate) where T : Exception, new()
        {
            if (!predicate)
            {
                throw new T();
            }
        }

        public static T Then<T>(this bool predicate, T nextBall)
        {
            return predicate ? nextBall : default(T);
        }
    }
}


text:
module Helpers
  module HostnameTest
    require 'chef/mixin/shell_out'
    require 'wrong'
    include Chef::Mixin::ShellOut
    include MiniTest::Chef::Assertions
    include MiniTest::Chef::Context
    include MiniTest::Chef::Resources
    include Wrong
  end
end


text:
lxc-destroy -n left
lxc-destroy -n right
ifconfig br-left down
ifconfig br-right down
brctl delif br-left tap-left
brctl delif br-right tap-right
brctl delbr br-left
brctl delbr br-right
ifconfig tap-left down
ifconfig tap-right down
tunctl -d tap-left
tunctl -d tap-right


text:
package com.plugplayer.plugplayer.upnp;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.UPnP;
import org.cybergarage.xml.Node;
import org.cybergarage.xml.Parser;

import android.app.Activity;
import android.content.SharedPreferences;
import android.widget.ImageView;

import com.plugplayer.plugplayer.R;
import com.plugplayer.plugplayer.activities.MainActivity;
import com.plugplayer.plugplayer.activities.SettingsEditor;
import com.plugplayer.plugplayer.upnp.Item.ContentType;
import com.plugplayer.plugplayer.utils.StateMap;

public class MP3TunesServer extends Server
{
	public MP3TunesServer()
	{
		setOriginalName( "MP3tunes" );

		final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE );

		username = preferences.getString( "MP3TUNES_USERNAME", null );
		password = preferences.getString( "MP3TUNES_PASSWORD", null );
	}

	public static final String STATENAME = "MP3TunesServer";

	@Override
	public void toState( StateMap state )
	{
		super.toState( state );
		state.setName( STATENAME );
	}

	@Override
	public void fromState( StateMap state )
	{
		super.fromState( state );
	}

	public static MP3TunesServer createFromState( StateMap state )
	{
		MP3TunesServer rval = new MP3TunesServer();
		rval.fromState( state );
		return rval;
	}

	private static final String ROOT_ID = "0";

	// private static final String AUDIO_ID = "1";
	private static final String VIDEO_ID = "2";

	private static final String ARTISTS_ID = "3";
	private static final String ALBUMS_ID = "4";
	private static final String PLAYLISTS_ID = "5";

	private static final String ARTIST_PREFIX = "artist-";
	private static final String ALBUM_PREFIX = "album-";
	private static final String PLAYLIST_PREFIX = "playlist-";

	// private static final int REQUEST_COUNT = 50;

	private String session_id = null;
	private static final String partner_token = "3437733845";
	private String username = null;
	private String password = null;

	private synchronized void browseDir( Container parent, String search, BrowseResultsListener listener, int max )
	{
		if ( session_id == null )
			login();

		if ( session_id == null )
		{
			emitError( "Error logging into MP3tunes" );

			if ( listener != null )
				listener.onDone();

			password = null;

			if ( PlugPlayerControlPoint.getInstance().getCurrentServer() == this )
				PlugPlayerControlPoint.getInstance().setCurrentServer( null );

			return;
		}

		if ( listener != null && search == null )
		{
			// We copy because parent.getChildren() is used by the background thread
			ArrayList<DirEntry> copy = new ArrayList<DirEntry>();
			copy.addAll( parent.getChildren() );
			listener.onInitialChildren( copy, parent.getTotalCount() );
		}

		int entryCount = parent.getChildCount();
		int requestCount = 25;

		int entriesLeft;

		if ( parent.getTotalCount() == -1 )
			entriesLeft = requestCount;
		else
			entriesLeft = parent.getTotalCount() - entryCount;

		while ( entriesLeft > 0 && (max < 0 || parent.getChildCount() != max) )
		{
			ArrayList<DirEntry> subList = new ArrayList<DirEntry>();

			int numReturned = 0;

			// if ( parent.getObjectID().equals( ROOT_ID ) )
			// {
			// parent.setTotalCount( 2 );
			//
			// Container c = new Container();
			// c.setParent( parent );
			// c.setObjectID( AUDIO_ID );
			// c.setTitle( "Audio" );
			// parent.getChildren().add( c );
			// subList.add( c );
			//
			// c = new Container();
			// c.setParent( parent );
			// c.setObjectID( VIDEO_ID );
			// c.setTitle( "Video" );
			// parent.getChildren().add( c );
			// subList.add( c );
			//
			// numReturned = 2;
			// }
			// else if ( parent.getObjectID().equals( AUDIO_ID ) )
			if ( parent.getObjectID().equals( ROOT_ID ) )
			{
				parent.setTotalCount( 3 );

				Container c = new Container();
				c.setParent( parent );
				c.setObjectID( ARTISTS_ID );
				c.setTitle( "Artists" );
				parent.getChildren().add( c );
				subList.add( c );

				c = new Container();
				c.setParent( parent );
				c.setObjectID( ALBUMS_ID );
				c.setTitle( "Albums" );
				parent.getChildren().add( c );
				subList.add( c );

				c = new Container();
				c.setParent( parent );
				c.setObjectID( PLAYLISTS_ID );
				c.setTitle( "Playlists" );
				parent.getChildren().add( c );
				subList.add( c );

				numReturned = 3;
			}
			else if ( parent.getObjectID().equals( PLAYLISTS_ID ) )
			{
				try
				{
					Parser p = UPnP.getXMLParser();
					Node n = p.parse( new URL( "http://ws.mp3tunes.com/api/v1/lockerData?output=xml&sid=" + session_id + "&partner_token=" + partner_token
							+ "&type=playlist&count=" + requestCount + "&set=" + parent.getChildCount() / 25 ) );

					Node summary = n.getNode( "summary" );
					String totalResults = summary.getNodeValue( "totalResults" );
					parent.setTotalCount( Integer.parseInt( totalResults ) );

					Node artistList = n.getNode( "playlistList" );
					for ( int i = 0; i < artistList.getNNodes(); ++i )
					{
						Node item = artistList.getNode( i );
						String playlistId = item.getNodeValue( "playlistId" );
						String playlistTitle = item.getNodeValue( "playlistTitle" );
						// String albumCount = item.getNodeValue( "albumCount" );

						Container c = new Container();
						c.setParent( parent );
						c.setObjectID( PLAYLIST_PREFIX + playlistId );
						c.setTitle( playlistTitle );
						// c.setTotalCount( Integer.parseInt( albumCount ) );
						parent.getChildren().add( c );
						subList.add( c );
						numReturned++;
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					emitError( "error getting mp3tunes data" );
				}
			}
			else if ( parent.getObjectID().equals( ARTISTS_ID ) )
			{
				try
				{
					Parser p = UPnP.getXMLParser();
					Node n = p.parse( new URL( "http://ws.mp3tunes.com/api/v1/lockerData?output=xml&sid=" + session_id + "&partner_token=" + partner_token
							+ "&type=artist&count=" + requestCount + "&set=" + parent.getChildCount() / 25 ) );

					Node summary = n.getNode( "summary" );
					String totalResults = summary.getNodeValue( "totalResults" );
					parent.setTotalCount( Integer.parseInt( totalResults ) );

					Node artistList = n.getNode( "artistList" );
					for ( int i = 0; i < artistList.getNNodes(); ++i )
					{
						Node item = artistList.getNode( i );
						String artistid = item.getNodeValue( "artistId" );
						String artistname = item.getNodeValue( "artistName" );
						// String albumCount = item.getNodeValue( "albumCount" );

						Container c = new Container();
						c.setParent( parent );
						c.setObjectID( ARTIST_PREFIX + artistid );
						c.setTitle( artistname );
						// c.setTotalCount( Integer.parseInt( albumCount ) );
						parent.getChildren().add( c );
						subList.add( c );
						numReturned++;
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					emitError( "error getting mp3tunes data" );
				}
			}
			else if ( parent.getObjectID().equals( ALBUMS_ID ) )
			{
				try
				{
					Parser p = UPnP.getXMLParser();
					Node n = p.parse( new URL( "http://ws.mp3tunes.com/api/v1/lockerData?output=xml&sid=" + session_id + "&partner_token=" + partner_token
							+ "&type=album&count=" + requestCount + "&set=" + parent.getChildCount() / 25 ) );

					Node summary = n.getNode( "summary" );
					String totalResults = summary.getNodeValue( "totalResults" );
					parent.setTotalCount( Integer.parseInt( totalResults ) );

					Node artistList = n.getNode( "albumList" );
					for ( int i = 0; i < artistList.getNNodes(); ++i )
					{
						Node item = artistList.getNode( i );
						String albumId = item.getNodeValue( "albumId" );
						String albumTitle = item.getNodeValue( "albumTitle" );
						String albumArtURL = item.getNodeValue( "albumArtURL" );
						// String trackCount = item.getNodeValue( "trackCount" );

						Container c = new Container();
						c.setParent( parent );
						c.setObjectID( ALBUM_PREFIX + albumId );
						c.setTitle( albumTitle );
						// c.setTotalCount( Integer.parseInt( trackCount ) );
						if ( albumArtURL != null && albumArtURL.length() != 0 )
							c.setArtURL( albumArtURL );
						parent.getChildren().add( c );
						subList.add( c );
						numReturned++;
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					emitError( "error getting mp3tunes data" );
				}
			}
			else if ( parent.getObjectID().equals( VIDEO_ID ) )
			{
				try
				{
					Parser p = UPnP.getXMLParser();
					Node n = p.parse( new URL( "http://ws.mp3tunes.com/api/v1/lockerData?output=xml&sid=" + session_id + "&partner_token=" + partner_token
							+ "&type=video&count=" + requestCount + "&set=" + parent.getChildCount() / 25 ) );

					// Node summary = n.getNode( "summary" );
					// String totalResults = summary.getNodeValue( "totalResults" );
					// parent.setTotalCount( Integer.parseInt( totalResults ) );

					Node trackList = n.getNode( "trackList" );
					for ( int i = 0; i < trackList.getNNodes(); ++i )
					{
						Node itemNode = trackList.getNode( i );
						String trackId = itemNode.getNodeValue( "trackId" );
						String trackTitle = itemNode.getNodeValue( "trackTitle" );
						// String trackFileSize = itemNode.getNodeValue( "trackFileSize" );
						String trackFileMimeType = itemNode.getNodeValue( "trackFileMimeType" );
						String playURL = itemNode.getNodeValue( "playURL" );
						String trackLength = itemNode.getNodeValue( "trackLength" );

						Item item = new Item();
						item.setInternal( true );
						item.setObjectID( "video-" + trackId );
						item.setUpnpClass( "object.item.videoItem" );
						item.setContentType( ContentType.Video );
						item.setTitle( trackTitle );
						// item.setSize( trackFileSize );
						item.setMimeType( trackFileMimeType );

						if ( trackLength != null && trackLength.length() != 0 )
							item.setTotalSeconds( (long)(Double.parseDouble( trackLength ) / 1000) );

						item.setResourceURL( playURL );

						parent.getChildren().add( item );

						parent.setTotalCount( parent.getChildCount() );

						subList.add( item );
						numReturned++;
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					emitError( "error getting mp3tunes data" );
				}
			}
			else if ( parent.getObjectID().startsWith( ARTIST_PREFIX ) )
			{
				String artistkey = parent.getObjectID().replace( ARTIST_PREFIX, "" );

				try
				{
					Parser p = UPnP.getXMLParser();
					Node n = p.parse( new URL( "http://ws.mp3tunes.com/api/v1/lockerData?output=xml&sid=" + session_id + "&partner_token=" + partner_token
							+ "&type=album&count=" + requestCount + "&set=" + parent.getChildCount() / 25 + "&artist_id=" + artistkey ) );

					Node summary = n.getNode( "summary" );
					String totalResults = summary.getNodeValue( "totalResults" );
					parent.setTotalCount( Integer.parseInt( totalResults ) );

					Node artistList = n.getNode( "albumList" );
					for ( int i = 0; i < artistList.getNNodes(); ++i )
					{
						Node item = artistList.getNode( i );
						String albumId = item.getNodeValue( "albumId" );
						String albumTitle = item.getNodeValue( "albumTitle" );
						String albumArtURL = item.getNodeValue( "albumArtURL" );
						// String trackCount = item.getNodeValue( "trackCount" );

						Container c = new Container();
						c.setParent( parent );
						c.setObjectID( ALBUM_PREFIX + albumId );
						c.setTitle( albumTitle );
						// c.setTotalCount( Integer.parseInt( trackCount ) );
						if ( albumArtURL != null && albumArtURL.length() != 0 )
							c.setArtURL( albumArtURL );
						parent.getChildren().add( c );
						subList.add( c );
						numReturned++;
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					emitError( "error getting mp3tunes data" );
				}
			}
			else if ( parent.getObjectID().startsWith( ALBUM_PREFIX ) )
			{
				String albumkey = parent.getObjectID().replace( ALBUM_PREFIX, "" );

				try
				{
					Parser p = UPnP.getXMLParser();
					Node n = p.parse( new URL( "http://ws.mp3tunes.com/api/v1/lockerData?output=xml&sid=" + session_id + "&partner_token=" + partner_token
							+ "&type=track&count=" + requestCount + "&set=" + parent.getChildCount() / 25 + "&album_id=" + albumkey ) );

					Node summary = n.getNode( "summary" );
					String totalResults = summary.getNodeValue( "totalResults" );
					parent.setTotalCount( Integer.parseInt( totalResults ) );

					Node trackList = n.getNode( "trackList" );
					for ( int i = 0; i < trackList.getNNodes(); ++i )
					{
						Node itemNode = trackList.getNode( i );
						String trackId = itemNode.getNodeValue( "trackId" );
						String trackTitle = itemNode.getNodeValue( "trackTitle" );
						// String trackFileSize = itemNode.getNodeValue( "trackFileSize" );
						String trackFileMimeType = itemNode.getNodeValue( "trackFileMimeType" );
						String playURL = itemNode.getNodeValue( "playURL" );
						String albumTitle = itemNode.getNodeValue( "albumTitle" );
						String artistName = itemNode.getNodeValue( "artistName" );
						String trackLength = itemNode.getNodeValue( "trackLength" );

						Item item = new Item();
						item.setInternal( true );
						item.setObjectID( "audio-" + trackId );
						item.setUpnpClass( "object.item.audioItem.musicTrack" );
						item.setContentType( ContentType.Audio );
						item.setTitle( trackTitle );
						item.setAlbum( albumTitle );
						item.setArtist( artistName );
						// item.setSize( trackFileSize );
						item.setMimeType( trackFileMimeType );

						if ( trackLength != null && trackLength.length() != 0 )
							item.setTotalSeconds( (long)(Double.parseDouble( trackLength ) / 1000) );

						item.setResourceURL( playURL );
						if ( parent.getArtURL() != null && parent.getArtURL().length() != 0 )
							item.setArtURL( parent.getArtURL() );

						// item.setArtURL( "thumbnail:" + item.getObjectID() );
						// if ( parent.getArtURL() == DirEntry.NOART || parent.getArtURL() == null )
						// parent.setArtURL( "thumbnail:" + item.getObjectID() );

						parent.getChildren().add( item );
						subList.add( item );
						numReturned++;
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					emitError( "error getting mp3tunes data" );
				}
			}
			else if ( parent.getObjectID().startsWith( PLAYLIST_PREFIX ) )
			{
				String playlistId = parent.getObjectID().replace( PLAYLIST_PREFIX, "" );

				try
				{
					Parser p = UPnP.getXMLParser();
					Node n = p.parse( new URL( "http://ws.mp3tunes.com/api/v1/lockerData?output=xml&sid=" + session_id + "&partner_token=" + partner_token
							+ "&type=track&count=" + requestCount + "&set=" + parent.getChildCount() / 25 + "&playlist_id=" + playlistId ) );

					Node summary = n.getNode( "summary" );
					String totalResults = summary.getNodeValue( "totalResults" );
					parent.setTotalCount( Integer.parseInt( totalResults ) );

					Node trackList = n.getNode( "trackList" );
					for ( int i = 0; i < trackList.getNNodes(); ++i )
					{
						Node itemNode = trackList.getNode( i );
						String trackId = itemNode.getNodeValue( "trackId" );
						String trackTitle = itemNode.getNodeValue( "trackTitle" );
						// String trackFileSize = itemNode.getNodeValue( "trackFileSize" );
						String trackFileMimeType = itemNode.getNodeValue( "trackFileMimeType" );
						String playURL = itemNode.getNodeValue( "playURL" );
						String albumTitle = itemNode.getNodeValue( "albumTitle" );
						String artistName = itemNode.getNodeValue( "artistName" );
						String hasArt = itemNode.getNodeValue( "hasArt" );
						String trackFileKey = itemNode.getNodeValue( "trackFileKey" );
						String trackLength = itemNode.getNodeValue( "trackLength" );

						Item item = new Item();
						item.setInternal( true );
						item.setObjectID( "audio-" + trackId );
						item.setUpnpClass( "object.item.audioItem.musicTrack" );
						item.setContentType( ContentType.Audio );
						item.setTitle( trackTitle );
						item.setAlbum( albumTitle );
						item.setArtist( artistName );
						// item.setSize( trackFileSize );
						item.setMimeType( trackFileMimeType );

						if ( trackLength != null && trackLength.length() != 0 )
							item.setTotalSeconds( (long)(Double.parseDouble( trackLength ) / 1000) );

						item.setResourceURL( playURL );

						if ( hasArt != null && hasArt.length() != 0 && !hasArt.equals( "0" ) )
						{
							item.setArtURL( "http://content.mp3tunes.com/storage/albumartget/" + trackFileKey + "?sid=" + session_id + "&partner_token="
									+ partner_token );
							if ( parent.getArtURL() == DirEntry.NOART || parent.getArtURL() == null )
								parent.setArtURL( item.getArtURL() );
						}

						parent.getChildren().add( item );
						subList.add( item );
						numReturned++;
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					emitError( "error getting mp3tunes data" );
				}
			}
			entryCount += numReturned;

			if ( numReturned < 25 ) // MP3tunes sometimes returns inaccurate total counts (e.g. "most played" playlist always reports 50)
			{
				parent.setTotalCount( parent.getChildCount() );
				entriesLeft = 0;
			}

			entriesLeft = parent.getTotalCount() - entryCount;

			// if ( requestCount == 10 )
			// requestCount = REQUEST_COUNT;

			if ( listener != null && !listener.loadMore() )
			{
				return;
			}

			if ( listener != null )
				listener.onMoreChildren( subList, parent.getTotalCount() );
		}

		if ( listener != null )
			listener.onDone();
	}

	private void login()
	{
		try
		{
			String url = "https://shop.mp3tunes.com/api/v1/login?output=xml&username=" + URLEncoder.encode( username ) + "&password="
					+ URLEncoder.encode( password ) + "&partner_token=" + partner_token;
			// System.out.println( url );
			Parser p = UPnP.getXMLParser();
			Node n = p.parse( new URL( url ) );
			session_id = n.getNodeValue( "session_id" );
			if ( session_id.length() == 0 || session_id.equals( "0" ) )
				session_id = null;
		}
		catch ( Exception e )
		{
			e.printStackTrace();
			emitError( "error logging into mp3tunes" );
		}
	}

	@Override
	public void browseDir( Container parent )
	{
		browseDir( parent, null, null, -1 );
	}

	@Override
	public void browseDir( Container parent, int max )
	{
		browseDir( parent, null, null, max );
	}

	@Override
	public void browseDir( final Container parent, final BrowseResultsListener listener )
	{
		if ( listener != null )
		{
			// We copy because parent.getChildren() is used by the background thread
			ArrayList<DirEntry> copy = new ArrayList<DirEntry>();
			copy.addAll( parent.getChildren() );
			listener.onMoreChildren( copy, parent.getTotalCount() );
		}

		new Thread( new Runnable()
		{
			public void run()
			{
				browseDir( parent, null, listener, -1 );
			}
		} ).start();
	}

	@Override
	public boolean canSearch()
	{
		return false;
	}

	@Override
	public void searchDir( Container parent, String query )
	{
		browseDir( parent, query, null, -1 );
	}

	@Override
	public void searchDir( final Container parent, final String query, final BrowseResultsListener listener )
	{
		new Thread( new Runnable()
		{
			public void run()
			{
				browseDir( parent, query, listener, -1 );
			}
		} ).start();
	}

	@Override
	public void updateServices( Device dev )
	{
	}

	@Override
	public void loadIcon( ImageView imageView )
	{
		imageView.setImageResource( R.drawable.mp3tunes_vertical );
	}

	@Override
	public boolean isAlive()
	{
		return username != null && password != null;
	}

	public String getUsername()
	{
		return username;
	}

	public String getPassword()
	{
		return password;
	}

	public void setUsername( String username )
	{
		this.username = username;

		final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE );
		preferences.edit().putString( "MP3TUNES_USERNAME", username ).commit();
	}

	public boolean setPassword( String password )
	{
		this.password = password;

		session_id = null;

		login();

		if ( session_id != null )
		{
			final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE );
			preferences.edit().putString( "MP3TUNES_PASSWORD", password ).commit();
			return true;
		}
		else
		{
			return false;
		}
	}
}


text:
package org.tuntuni.videocall.audio;

import java.util.LinkedList;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import org.tuntuni.connection.DataFrame;
import org.tuntuni.connection.StreamServer;
import org.tuntuni.models.Logs;
import org.tuntuni.videocall.VideoFormat;

/**
 *
 * @author Sudipto Chandra
 */
public class AudioPlayer extends StreamServer implements Runnable {

    static final int QUEUE_SIZE = 1;

    private SourceDataLine mSourceLine;
    private Thread mPlayerThread;
    private final LinkedList<byte[]> mData;

    public AudioPlayer(int port) {
        super(port);
        mData = new LinkedList<>();
    }

    /**
     * Starts the player
     */
    public void start() {
        try {
            // start source line
            DataLine.Info info = new DataLine.Info(
                    SourceDataLine.class, VideoFormat.getAudioFormat());
            mSourceLine = (SourceDataLine) AudioSystem.getLine(info);
            mSourceLine.open(VideoFormat.getAudioFormat());

            mPlayerThread = new Thread(this);
            mPlayerThread.setDaemon(true);
            mPlayerThread.start();
        } catch (LineUnavailableException ex) {
            Logs.error(getClass(), "Failed to start the audio line. ERROR: {0}", ex);
        }
    }

    /**
     * Stops the player
     */
    public void stop() {
        try {
            mPlayerThread.interrupt();
            // close player
            mSourceLine.close();
        } catch (Exception ex) {
        }
    }

    @Override
    public String getName() {
        return "AudioPlayer";
    }

    @Override
    public void dataReceived(Object data) {
        if (data != null && data instanceof DataFrame) {
            DataFrame frame = (DataFrame) data;
            // play the audio data
            synchronized (mData) {
                mData.add(frame.getBuffer());
                if (mData.size() > QUEUE_SIZE) {
                    mData.poll();
                }
                mData.notify();
            }
        }
    }

    @Override
    public void run() {
        mSourceLine.start();
        while (!Thread.interrupted()) {
            synchronized (mData) {
                if (mData.isEmpty()) {
                    try {
                        mData.wait();
                    } catch (InterruptedException ex) {
                        Logs.error(getName(), "Wait interrupted. {0}", ex);
                    }
                }
                byte[] data = mData.poll();
                if (data != null) {
                    // play the audio data
                    mSourceLine.write(data, 0, data.length);
                }
            }
        }
    }

}


text:
"""DataClass that holds a single batch of counts and covariates.

A few assumptions:
* The data set contains infected controls, active controls, uninfected controls,
  and samples. These are indicated by an "actives" column. The values of the
  actives column are encoded in the Actives enum.
* Controls get special handling: we order compounds and treatments so that
  controls are first, and we assume that all active controls have the same
  compound and concentration.
* A row flagged as a sample is treated differently than a control even if the
  sample row has the same compound / concentration as a control.
"""

import dataclasses
import enum
import string
from typing import Any, Dict, List, Optional, Tuple

from cell_img.common import plate_utils
from jax import numpy as jnp
import numpy as np
import pandas as pd

class Actives(enum.IntEnum):
  INFECTED_CONTROL = 0
  ACTIVE_CONTROL = 1
  UNINFECTED_CONTROL = 2
  SAMPLE = 3

def actives_to_str(actives: Actives) -> str:
  return actives.name.lower()

def str_to_actives(s: str) -> Actives:
  return Actives[s.upper()]

@dataclasses.dataclass(frozen=True)
class Observations:
  """Dataclass containing counts and covariates."""
  # covariates
  plate_index: jnp.ndarray
  well_row: jnp.ndarray
  well_col: jnp.ndarray
  compound_index: jnp.ndarray
  treatment_index: jnp.ndarray
  log_concentration: jnp.ndarray
  # counts
  n_artifact: Optional[jnp.ndarray]
  n_hypnozoite: jnp.ndarray
  n_schizont: Optional[jnp.ndarray]
  n_hepatocyte: jnp.ndarray

  # values for converting Observations back to a dataframe
  sorted_plates: List[str]
  well_row_min: int
  well_row_max: int
  well_col_min: int
  well_col_max: int
  sorted_compounds: List[str]
  sorted_treatments: List[Tuple[str, float]]
  # preserve the compound / concentrations for controls
  control_compound_map: Dict[Actives, str]
  # Any allows for special concentrations (e.g. 0, -1, np.nan, etc)
  control_concentration_map: Dict[Actives, Any]

# default column names
PLATE_COL = 'plate'
WELL_COL = 'well'
ACTIVES_COL = 'actives'
COMPOUND_COL = 'blinded_concept'
CONCENTRATION_COL = 'concentration'

def from_dataframe(
    df: pd.DataFrame,
    well_row_min: int,
    well_row_max: int,
    well_col_min: int,
    well_col_max: int,
    hypnozoite_col: str,
    hepatocyte_col: str,
    artifact_col: Optional[str] = None,
    schizont_col: Optional[str] = None,
    plate_col: str = PLATE_COL,
    well_col: str = WELL_COL,
    actives_col: str = ACTIVES_COL,
    compound_col: str = COMPOUND_COL,
    concentration_col: str = CONCENTRATION_COL,
    ) -> Observations:
  """Create an Observations from a DataFrame.

  Args:
    df: DataFrame from which to obtain values
    well_row_min: minimum well row
    well_row_max: maximum well row
    well_col_min: minimum well column
    well_col_max: maximum well column
    hypnozoite_col: column containing hypnozoite counts
    hepatocyte_col: column containing hepatocyte counts
    artifact_col: column containing artifact counts
    schizont_col: column containing schizont counts
    plate_col: column containing plate names
    well_col: column containing wells
    actives_col: column containing actives information
    compound_col: column containing compound
    concentration_col: column containing concentration

  Returns:
    An Observations object.
  """

  # Map plates to integers
  sorted_plates = sorted(set(df[plate_col]))
  plate_index = []
  for plate in df[plate_col]:
    plate_index.append(sorted_plates.index(plate))
  plate_index = jnp.array(plate_index)

  # Map well row and column to floats between -1 and 1
  well_row_float = []
  well_col_float = []
  for well in df[well_col]:
    row_int = plate_utils.get_row_int(well)
    col_int = plate_utils.get_column_int(well)
    well_row_float.append(
        2. * (row_int - well_row_min) / (well_row_max - well_row_min) - 1.)
    well_col_float.append(
        2. * (col_int - well_col_min) / (well_col_max - well_col_min) - 1.)
  well_row_float = jnp.array(well_row_float)
  well_col_float = jnp.array(well_col_float)

  # Map compounds and treatments to integers
  control_compound = {}
  control_concentration = {}
  treatments = []
  for actives, compound, concentration in zip(
      df[actives_col],
      df[compound_col],
      df[concentration_col]):
    actives_enum = str_to_actives(actives)
    if actives_enum == Actives.SAMPLE:
      treatments.append((compound, concentration))
    else:
      if actives_enum in control_compound:
        if compound != control_compound[actives_enum]:
          raise ValueError(
              f'Multiple compounds for {actives_enum.name}:'
              f'{compound} != {control_compound[actives_enum]}')
      control_compound[actives_enum] = compound
      if actives_enum in control_concentration:
        if concentration != control_concentration[actives_enum]:
          raise ValueError(
              f'Multiple concentrations for {actives_enum.name}:'
              f'{concentration} != {control_concentration[actives_enum]}')
      control_concentration[actives_enum] = concentration
      actives_str = actives_to_str(actives_enum)
      treatments.append((actives_str, 1.))  # use dummy conc to prevent NaNs
  log_concentrations = jnp.log(jnp.array([t[1] for t in treatments]))

  compounds = [t[0] for t in treatments]
  sorted_compounds = sorted(set(compounds))
  sorted_treatments = sorted(set(treatments))

  # the initial compounds will *always* be the controls (even if they aren't
  # present in the input data)
  for actives_enum in reversed(list(Actives)):
    if actives_enum == Actives.SAMPLE:
      continue

    actives_str = actives_to_str(actives_enum)
    if actives_str in sorted_compounds:
      sorted_compounds.remove(actives_str)
    sorted_compounds = [actives_str] + sorted_compounds

    treatment = (actives_str, 0.)
    if treatment in sorted_treatments:
      sorted_treatments.remove(treatment)
    sorted_treatments = [treatment] + sorted_treatments

  # map compound -> compound_index
  compound_to_index = {c: i for i, c in enumerate(sorted_compounds)}
  compound_index = []
  for compound in compounds:
    compound_index.append(compound_to_index[compound])
  compound_index = jnp.array(compound_index)

  # map treatment -> treatment_index
  treatment_to_index = {t: i for i, t in enumerate(sorted_treatments)}
  treatment_index = []
  for treatment in treatments:
    treatment_index.append(treatment_to_index[treatment])
  treatment_index = jnp.array(treatment_index)

  n_hypnozoite = jnp.array(df[hypnozoite_col].to_numpy().astype(np.float32))
  n_hepatocyte = jnp.array(df[hepatocyte_col].to_numpy().astype(np.float32))
  if artifact_col:
    n_artifact = jnp.array(df[artifact_col].to_numpy().astype(np.float32))
  else:
    n_artifact = None
  if schizont_col:
    n_schizont = jnp.array(df[schizont_col].to_numpy().astype(np.float32))
  else:
    n_schizont = None

  return Observations(
      plate_index=plate_index,
      well_row=well_row_float,
      well_col=well_col_float,
      compound_index=compound_index,
      treatment_index=treatment_index,
      log_concentration=log_concentrations,
      n_hypnozoite=n_hypnozoite,
      n_hepatocyte=n_hepatocyte,
      n_artifact=n_artifact,
      n_schizont=n_schizont,
      sorted_plates=sorted_plates,
      well_row_min=well_row_min,
      well_row_max=well_row_max,
      well_col_min=well_col_min,
      well_col_max=well_col_max,
      control_compound_map=control_compound,
      control_concentration_map=control_concentration,
      sorted_compounds=sorted_compounds,
      sorted_treatments=sorted_treatments,)

def row_int_to_str(row_int: int) -> str:
  """Convert a row integer to a well row string."""
  row = []
  while row_int > 0:
    row_int -= 1
    row.append(string.ascii_uppercase[row_int % 26])
    row_int //= 26
  row.reverse()
  return ''.join(row)

def to_dataframe(
    obs: Observations,
    hypnozoite_col: str,
    hepatocyte_col: str,
    artifact_col: Optional[str] = None,
    schizont_col: Optional[str] = None,
    plate_col: str = PLATE_COL,
    well_col: str = WELL_COL,
    actives_col: str = ACTIVES_COL,
    compound_col: str = COMPOUND_COL,
    concentration_col: str = CONCENTRATION_COL) -> pd.DataFrame:
  """Create a DataFrame from an Observations.

  Args:
    obs: Observations from which to obtain values
    hypnozoite_col: column containing hypnozoite counts
    hepatocyte_col: column containing hepatocyte counts
    artifact_col: column containing artifact counts
    schizont_col: column containing schizont counts
    plate_col: column containing plate names
    well_col: column containing wells
    actives_col: column containing actives information
    compound_col: column containing compound
    concentration_col: column containing concentration

  Returns:
    A DataFrame.
  """
  n_hypnozoite = np.array(obs.n_hypnozoite)
  n_hepatocyte = np.array(obs.n_hepatocyte)

  plate = [obs.sorted_plates[pi] for pi in obs.plate_index]

  well = []
  for row, col in zip(obs.well_row, obs.well_col):
    row_int = int(round(
        obs.well_row_min +
        0.5 * (row + 1.) * (obs.well_row_max - obs.well_row_min)))
    row_str = row_int_to_str(row_int)
    col_int = int(round(
        obs.well_col_min +
        0.5 * (col + 1.) * (obs.well_col_max - obs.well_col_min)))
    col_str = str(col_int)
    well.append(row_str + col_str)

  compound = []
  actives = []
  concentration = np.exp(np.array(obs.log_concentration))
  for i, ci in enumerate(obs.compound_index.tolist()):
    if ci < len(Actives) and Actives(ci) != Actives.SAMPLE:
      actives_enum = Actives(ci)
      compound.append(obs.control_compound_map[actives_enum])
      # overwrite concentration for the controls (handles None / NA values)
      concentration[i] = obs.control_concentration_map[actives_enum]
      actives.append(actives_to_str(actives_enum))
    else:
      compound.append(obs.sorted_compounds[ci])
      actives.append(actives_to_str(Actives.SAMPLE))

  cols = {
      hypnozoite_col: n_hypnozoite,
      hepatocyte_col: n_hepatocyte,
      plate_col: plate,
      well_col: well,
      actives_col: actives,
      compound_col: compound,
      concentration_col: concentration,
  }
  if artifact_col:
    cols[artifact_col] = np.array(obs.n_artifact)
  if schizont_col:
    cols[schizont_col] = np.array(obs.n_schizont)
  return pd.DataFrame(cols)


text:
import { Component, ElementRef, EventEmitter } from '@angular/core';
import { InfoWindowManager } from '../services/managers/info-window-manager';
var infoWindowId = 0;
/**
 * AgmInfoWindow renders a info window inside a {@link AgmMarker} or standalone.
 *
 * ### Example
 * ```typescript
 * import { Component } from '@angular/core';
 *
 * @Component({
 *  selector: 'my-map-cmp',
 *  styles: [`
 *    .agm-map-container {
 *      height: 300px;
 *    }
 * `],
 *  template: `
 *    <agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
 *      <agm-marker [latitude]="lat" [longitude]="lng" [label]="'M'">
 *        <agm-info-window [disableAutoPan]="true">
 *          Hi, this is the content of the <strong>info window</strong>
 *        </agm-info-window>
 *      </agm-marker>
 *    </agm-map>
 *  `
 * })
 * ```
 */
var AgmInfoWindow = (function () {
    function AgmInfoWindow(_infoWindowManager, _el) {
        this._infoWindowManager = _infoWindowManager;
        this._el = _el;
        /**
         * Sets the open state for the InfoWindow. You can also call the open() and close() methods.
         */
        this.isOpen = false;
        /**
         * Emits an event when the info window is closed.
         */
        this.infoWindowClose = new EventEmitter();
        this._infoWindowAddedToManager = false;
        this._id = (infoWindowId++).toString();
    }
    AgmInfoWindow.prototype.ngOnInit = function () {
        this.content = this._el.nativeElement.querySelector('.agm-info-window-content');
        this._infoWindowManager.addInfoWindow(this);
        this._infoWindowAddedToManager = true;
        this._updateOpenState();
        this._registerEventListeners();
    };
    /** @internal */
    AgmInfoWindow.prototype.ngOnChanges = function (changes) {
        if (!this._infoWindowAddedToManager) {
            return;
        }
        if ((changes['latitude'] || changes['longitude']) && typeof this.latitude === 'number' &&
            typeof this.longitude === 'number') {
            this._infoWindowManager.setPosition(this);
        }
        if (changes['zIndex']) {
            this._infoWindowManager.setZIndex(this);
        }
        if (changes['isOpen']) {
            this._updateOpenState();
        }
        this._setInfoWindowOptions(changes);
    };
    AgmInfoWindow.prototype._registerEventListeners = function () {
        var _this = this;
        this._infoWindowManager.createEventObservable('closeclick', this).subscribe(function () {
            _this.isOpen = false;
            _this.infoWindowClose.emit();
        });
    };
    AgmInfoWindow.prototype._updateOpenState = function () {
        this.isOpen ? this.open() : this.close();
    };
    AgmInfoWindow.prototype._setInfoWindowOptions = function (changes) {
        var options = {};
        var optionKeys = Object.keys(changes).filter(function (k) { return AgmInfoWindow._infoWindowOptionsInputs.indexOf(k) !== -1; });
        optionKeys.forEach(function (k) { options[k] = changes[k].currentValue; });
        this._infoWindowManager.setOptions(this, options);
    };
    /**
     * Opens the info window.
     */
    AgmInfoWindow.prototype.open = function () { return this._infoWindowManager.open(this); };
    /**
     * Closes the info window.
     */
    AgmInfoWindow.prototype.close = function () {
        var _this = this;
        return this._infoWindowManager.close(this).then(function () { _this.infoWindowClose.emit(); });
    };
    /** @internal */
    AgmInfoWindow.prototype.id = function () { return this._id; };
    /** @internal */
    AgmInfoWindow.prototype.toString = function () { return 'AgmInfoWindow-' + this._id.toString(); };
    /** @internal */
    AgmInfoWindow.prototype.ngOnDestroy = function () { this._infoWindowManager.deleteInfoWindow(this); };
    return AgmInfoWindow;
}());
export { AgmInfoWindow };
AgmInfoWindow._infoWindowOptionsInputs = ['disableAutoPan', 'maxWidth'];
AgmInfoWindow.decorators = [
    { type: Component, args: [{
                selector: 'agm-info-window',
                inputs: ['latitude', 'longitude', 'disableAutoPan', 'isOpen', 'zIndex', 'maxWidth'],
                outputs: ['infoWindowClose'],
                template: "<div class='agm-info-window-content'>\n      <ng-content></ng-content>\n    </div>\n  "
            },] },
];
/** @nocollapse */
AgmInfoWindow.ctorParameters = function () { return [
    { type: InfoWindowManager, },
    { type: ElementRef, },
]; };
//# sourceMappingURL=info-window.js.map


text:
<html>
<body>

Reports redundant import statements.
</body>
</html>


text:
<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Core\Service\Tag;

use Doctrine\Common\Collections\Collection;
use Doctrine\ORM;
use Shlinkio\Shlink\Core\Entity\Tag;
use Shlinkio\Shlink\Core\Exception\TagConflictException;
use Shlinkio\Shlink\Core\Exception\TagNotFoundException;
use Shlinkio\Shlink\Core\Repository\TagRepository;
use Shlinkio\Shlink\Core\Util\TagManagerTrait;

class TagService implements TagServiceInterface
{
    use TagManagerTrait;

    private ORM\EntityManagerInterface $em;

    public function __construct(ORM\EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @return Tag[]
     * @throws \UnexpectedValueException
     */
    public function listTags(): array
    {
        /** @var Tag[] $tags */
        $tags = $this->em->getRepository(Tag::class)->findBy([], ['name' => 'ASC']);
        return $tags;
    }

    /**
     * @param string[] $tagNames
     */
    public function deleteTags(array $tagNames): void
    {
        /** @var TagRepository $repo */
        $repo = $this->em->getRepository(Tag::class);
        $repo->deleteByName($tagNames);
    }

    /**
     * Provided a list of tag names, creates all that do not exist yet
     *
     * @param string[] $tagNames
     * @return Collection|Tag[]
     */
    public function createTags(array $tagNames): Collection
    {
        $tags = $this->tagNamesToEntities($this->em, $tagNames);
        $this->em->flush();

        return $tags;
    }

    /**
     * @throws TagNotFoundException
     * @throws TagConflictException
     */
    public function renameTag(string $oldName, string $newName): Tag
    {
        /** @var TagRepository $repo */
        $repo = $this->em->getRepository(Tag::class);

        /** @var Tag|null $tag */
        $tag = $repo->findOneBy(['name' => $oldName]);
        if ($tag === null) {
            throw TagNotFoundException::fromTag($oldName);
        }

        $newNameExists = $newName !== $oldName && $repo->count(['name' => $newName]) > 0;
        if ($newNameExists) {
            throw TagConflictException::fromExistingTag($oldName, $newName);
        }

        $tag->rename($newName);
        $this->em->flush();

        return $tag;
    }
}